PHP MySQL修改数据
通过PHP函数mysqli_query
执行SQL UPDATE
语句,可以将数据更新到MySQL表中。下面是将记录更新为test表的简单示例。要更新任何表中的记录,需要使用条件子句查找该记录。下面的示例使用主键来匹配test表中的记录。
请尝试以下示例以了解更新操作。您需要提供id以更新name字段。
<html>
<head>
<title>更新一条MySQL记录</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '123456';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('不能连接: ' . mysqli_error($conn));
}
if(isset($_POST['update'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$sql = "UPDATE test SET name = \"$name\" WHERE id = $id" ;
mysqli_select_db($conn,'test');
$retval = mysqli_query( $conn, $sql );
if(! $retval ) {
die('不能更新数据: ' . mysqli_error($conn));
}
echo "更新成功<br/>";
$sql = "SELECT * FROM test WHERE id=$id";
$query = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($query);
echo $row['id'].':::::::::'.$row['name'];
mysqli_close($conn);
}else {
?>
<form method = "post" action = "<?php echo $_SERVER['PHP_SELF']; ?>">
<table width = "400" border =" 0" cellspacing = "1" cellpadding = "2">
<tr>
<td width = "100"> ID</td>
<td><input name = "id" type = "text" name = "id"></td>
</tr>
<tr>
<td width = "100">Name</td>
<td><input name = "name" type = "text" ></td>
</tr>
<tr>
<td width = "100"> </td>
<td> </td>
</tr>
<tr>
<td width = "100"> </td>
<td>
<input name = "update" type = "submit" value = "更新数据">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>