PHP更新准备语句问题

问题描述 投票:0回答:3

以下是希望更新其数据库的任何人的更新代码。谢谢大家的帮助。

<?php
  try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, 
 $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// prepare sql and bind parameters
$stmt = $conn->prepare("UPDATE test SET title=:title WHERE id=:id");
$stmt->bindParam(':title', $title);  
$stmt->bindParam(':id', $id);

// Update a row
$title = $_POST['title'];
$id = $_POST['id'];
$stmt->execute();
echo "Row updated"; 
echo "<br />";
echo "<strong>$title</strong> and <strong>$id</strong>";
 }
 catch(PDOException $e) {
echo "Error: " . $e->getMessage();
 }
$conn = null;
?>
php html sql
3个回答
1
投票

你仍然有一些混合的PDO和MySQLi,虽然现在只在你对bindParam的调用,你打电话就好像它是MySQLi::bind_param。同样在你的上一次编辑中,查询字符串搞砸了添加Values=?我不知道你为什么这样做?无论如何,这应该做你想要的:

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // prepare sql and bind parameters
    $stmt = $conn->prepare("UPDATE test SET title=:title WHERE id=:id");
    $stmt->bindParam(':title', $title);  
    $stmt->bindParam(':id', $id);

    // Update a row
    $title = $_POST['title'];
    $stmt->execute();
    echo "Row updated";
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;

1
投票

使用bind_param():

<?php
   $statement = $conn->prepare("UPDATE test SET title= ? WHERE id= ?");
   $statement->bind_param('si', $title,$id);
   $statement->execute();
   if ($statement->affected_rows >0) {
      echo "Record updated successfully";
   } else {
      echo "Error updating record: " . $conn->error;
   }
   $statement->close();
?> 

0
投票
use this.hope it will help you.
<?php
$statement = $conn->prepare("UPDATE myTable SET name = ? WHERE id = ?");
$statement->bind_param("si", $_POST['title'],$id);
$statement->execute();
$statement->close();
?>
© www.soinside.com 2019 - 2024. All rights reserved.