我正在尝试通过编写一个小页面来学习PHP和Mysql。事情似乎有点奏效,但我的代码可能就是那么糟糕。我有emp_num作为mysql数据库的主键。我有一个名为page.php的页面,位于下方。
<?php
$mysqli = new mysqli('localhost','root','','train');
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//MySqli Select Query
$results = $mysqli->query("SELECT emp_num, name, supervisor FROM train2015 ORDER BY name desc");
print '<table border="1">';
while($row = $results->fetch_object()) {
print '<tr>';
print '<td>'.$row->emp_num.'</td>';
print '<td>'.$row->name.'</td>';
print '<td>'.$row->supervisor.'</td>';
print '<td>';
print '<a href="edituser.php?=$row[emp_num]"">Edit</a>';
print '</td>';
print '</tr>';
}
print '</table>';
// close connection
$mysqli->close();
?>
此页面显示表格中的记录,每个记录旁边都有一个编辑按钮。单击编辑后,将转到edituser.php。代码如下
$mysqli = new mysqli('localhost','root','','train');
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
mysql_connect(localhost,$username,$password);
mysql_close();
?>
<form method="post" action="includes/insert2.php" />
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name" value="<?php echo "$row[name]" ?>"></td>
</tr>
<tr>
<td>Supervisor:</td>
<td><input type="text" name="supervisor" value="<?php echo "$row[supervisor]" ?>"></td>
</tr>
</table>
<input type="submit" name="submit">
</form>
我希望在单击按钮后使用此页面编辑名称和主管。单击按钮后我的insert2.php代码进行更改。
<?php
// Your database info
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'train';
if (!empty($_POST))
{
$con = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if ($con->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
$sql = "INSERT INTO train2015 (name, supervisor) VALUES (?,?)";
if (!$stmt = $con->prepare($sql))
die('Query failed: (' . $con->errno . ') ' . $con->error);
if (!$stmt->bind_param('ss',$_POST['name'],$_POST['supervisor']))
die('Bind Param failed: (' . $con->errno . ') ' . $con->error);
if (!$stmt->execute())
die('Insert Error ' . $con->error);
echo "Record added";
$stmt->close();
$con->close();
header("Location: http://localhost/addsuccess.php");
}
?>
当我点击edituser.php上的按钮更新记录时,我收到一条消息,说明插入错误重复条目'0'表示关键'PRIMARY',这就是我被卡住的地方。
提前致谢。