I'm trying to update the MySQL row with the following code. This does not work and the values remain the same. Where am I wrong? I have made the analogy of the "?" format from other cases not exact:
$fname_upd=$_POST['fname'];
$lname_upd=$_POST['lname'];
$email_upd=$_POST['email'];
include('connection.php');
$q_ins="UPDATE myguests SET (firstname, lastname,email) VALUES(?,?,?) WHERE id=?";
$ins=$dbh->prepare($q_ins);
$res=$ins->execute(array($fname_upd,$lname_upd,$email_upd,$id));
print_r($res);
Please check this updated code , but let me know where you have defined $id variable because it is the variable on the basis of which we are updating the values.
What i did?
I have updated update query of yours with placeholder values and also make use of isset() function to check our $_POST values.
<?php
$fname_upd = isset($_POST['fname']) ? $_POST['fname'] : '';
$lname_upd = isset($_POST['lname']) ? $_POST['lname'] : "";
$email_upd = isset($_POST['email']) ? $_POST['email'] : "";
include('connection.php');
$sql = "UPDATE myguests SET firstname = :firstname, lastname = :lastname, email = :email WHERE id = :id";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':firstname', $fname_upd, PDO::PARAM_STR);
$stmt->bindParam(':lastname', $lname_upd, PDO::PARAM_STR);
$stmt->bindParam(':email', $email_upd, PDO::PARAM_STR);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
And also you need to update your used syntax because it is not correctly used which i have updated as
<?php
$fname_upd = isset($_POST['fname']) ? $_POST['fname'] : '';
$lname_upd = isset($_POST['lname']) ? $_POST['lname'] : "";
$email_upd = isset($_POST['email']) ? $_POST['email'] : "";
include('connection.php');
$q_ins = "UPDATE myguests SET firstname=?, lastname=?,email=? WHERE id=?";
$ins = $dbh->prepare($q_ins);
$res = $ins->execute(array($fname_upd, $lname_upd, $email_upd, $id));
print_r($res);
You have written wrong query. Below is the corrected query:
$q_ins="UPDATE myguests SET firstname=?, lastname=?,email=? WHERE id=?";
$ins=$dbh->prepare($q_ins);
Read php PDO manual.
I'm not sure that execute()
does anything with it's arguments. If you want to keep the ?
syntax, what you can do with a prepared statement is bind parameters before executing. So your code would look more like.
$q_ins="UPDATE myguests SET (firstname, lastname, email) VALUES(?,?,?) WHERE id=?";
$ins=$dbh->prepare($q_ins);
$ins->bind_param('ssss', $fname_upd, $lname_upd, $email_upd, $id);
$res=$ins->execute();
The first argument of the bind_params()
tells the prepared statement what types to expect. You might want to change the 's'
for the $id
to an 'i'
depending on how $id
is defined, but in my experience, it won't actually matter.
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.