PHP 将旧的 mysql_query 更改为 PDO
我的代码中有一些旧的 mysql_query 查询,我想将其转换为 PDO,但正在努力工作.
I have some old mysql_query queries in my code which i want to convert in to PDO but am struggling to get to work.
我的原始代码是:
mysql_query("UPDATE people SET price='$price', contact='$contact', fname='$fname', lname='$lname' WHERE id='$id' AND username='$username' ")
or die(mysql_error());
现在我正在尝试:
$sql = "UPDATE people SET price='$price', contact='$contact', fname='$fname', lname='$lname' WHERE id='$id' AND username='$username'";
$q = $conn->query($sql) or die("failed!");
但似乎无法让它工作,有什么想法吗?
but can't seem to get it to work, any ideas?
更新代码:
$conn = new PDO("mysql:host=$host;dbname=$db",$user,$pass);
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$fname = mysql_real_escape_string(htmlspecialchars($_POST['fname']));
$lname = mysql_real_escape_string(htmlspecialchars($_POST['lname']));
$contact = mysql_real_escape_string(htmlspecialchars($_POST['contact']));
$price = mysql_real_escape_string(htmlspecialchars($_POST['price']));
// check that firstname/lastname fields are both filled in
if ($fname == '' || $lname == '' || $contact == '' || $price == '' )
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $fname, $lname, $contact, $price, $error);
}
else
{
// save the data to the database
$username = $_SESSION['username'];
$query = "UPDATE people
SET price=?,
contact=?,
fname=?,
lname=?
WHERE id=? AND
username=?";
$stmt = $db->prepare($query);
$stmt->bindParam(1, $price);
$stmt->bindParam(2, $contact);
$stmt->bindParam(3, $fname);
$stmt->bindParam(4, $lname);
$stmt->bindParam(5, $id);
$stmt->bindParam(6, $username);
$stmt->execute();
// once saved, redirect back to the view page
header("Location: view.php");
}
推荐答案
有关更多信息,请访问此链接:PHP PDO
For more information visit this link: PHP PDO
根据您的示例,
<?php
$query = "UPDATE people
SET price=?,
contact=?,
fname=?,
lname=?
WHERE id=? AND
username=?";
$stmt = $dbh->prepare($query);
$stmt->bindParam(1, $price);
$stmt->bindParam(2, $contact);
$stmt->bindParam(3, $fname);
$stmt->bindParam(4, $lname);
$stmt->bindParam(5, $id);
$stmt->bindParam(6, $username);
$stmt->execute();
?>
PDO 准备好的语句和存储过程
相关文章