如何使用PHP更新表中的值

时间:2015-04-13 05:40:52

标签: php mysql

如何使用PHP实际更新表的值?此代码未显示任何错误,也未显示任何错误。

<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'DB';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_error()) 
{
die("couldn't connect" . $conn->connect_error());
}
echo ("connected successfully");
$id = $_POST['Id'];
$name = $_POST['Name'];
$dept = $_POST['Department'];
$update = "update info set Name='$name', Department='$dept' where Id='$id'";
if($conn->query(update) === TRUE) {
echo ("Data updated successfully");
} 
else
{
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
?>

5 个答案:

答案 0 :(得分:4)

希望这个能帮到你!

$update = "update info set Name='".$name."', Department='".$dept."' where Id='".$id."'";

答案 1 :(得分:3)

检查代码的这一部分:

if($conn->query(update) === TRUE) {

应该是:

if($conn->query($update) === TRUE) {
  • 确保根据MySQL数据库使用正确的凭据(主机,用户名,密码,数据库名称)。
  • 您的表名列名也应该在您的查询中使用。
  • 确保您的查询条件部分与... WHERE Id='$id')匹配。通过在PhpMyAdmin页面中运行查询或Search ID来检查它,该ID也是您尝试在表单中输入的ID。
  • 确保传递的变量($_POST[])的名称正确无误。
  • 区分大小写。

尝试将您的连接更改为:

$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

执行查询的其他方法是:

mysqli_query($conn,$update);

建议:

在使用mysqli_real_escape_string()函数将变量值用于查询之前,您应该先将其转义:

$name = mysqli_real_escape_string($conn,$_POST["Name"]);

或者更好,因此您不必担心将变量绑定到查询中以及阻止SQL injections,您应该转移到mysqli_* prepared statement

if($stmt = $conn->prepare("UPDATE info SET Name=?, Department=? WHERE Id=?")){

  $stmt->bind_param("ssi",$_POST['Name'],$_POST['Department'],$_POST['Id']);
  $stmt->execute();
  $stmt->close();

}

答案 2 :(得分:2)

$update = "update info set Name='".$name."', Department='".$dept."' where Id='".$id."'";
 mysql_query($update);

答案 3 :(得分:1)

$ update =“update info set Name ='”。$ name。“',set Department ='”。$ dept。“'where Id ='”。$ id。“'”;

如果没有帮助,请提供表格代码。

答案 4 :(得分:0)

试试这个

<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'DB';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(!$conn) 
{
die("ERROR CONNECTING TO DATABASE!");
}
echo "Connected Successfully";
$id = $_POST['Id'];
$name = $_POST['Name'];
$dept = $_POST['Department'];
$update = "update info set Name='$name', Department='$dept' where Id='$id'";
$qry = mysqli_query($conn,$update);
if(!$qry) {
echo "Error Updating Details".mysqli_error($conn);
} 
else
{
echo "Data updated successfully";
}
mysqli_close($conn);
?>

(可选)使用安全的东西。为了更安全,请更改为此。

$id = mysqli_real_escape_string($conn,$_POST['Id']);
$name = mysqli_real_escape_string($conn,$_POST['Name']);
$dept = mysqli_real_escape_string($conn,$_POST['Department']);