簡體   English   中英

PHP更新准備的語句問題

[英]PHP Update Prepared Statement Issue

這是任何希望更新其數據庫的人的更新代碼。 謝謝大家的幫助。

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

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

盡管現在僅在對bindParam的調用中,您仍然有PDO和MySQLi的混合使用, bindParam在調用MySQLi::bind_param 同樣在上一次編輯中,查詢字符串被Values=?的添加弄亂了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;
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();
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM