简体   繁体   中英

PHP Update Prepared Statement Issue

Here is the updated code for anyone looking to update their database. Thank you everyone for all your help.

<?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;
?>

Use 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();
?> 

You still have a bit of a mix of PDO and MySQLi although only in your call to bindParam now, which you are calling as if it was MySQLi::bind_param . Also in your last edit the query string got messed up with the addition of Values=? I'm not sure why you did that? Anyway, this should do what you want:

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;
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();
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM