Trying to update a record using PHP and PDO statements.
The query fires with no errors, and the console reads the update was successful, but there is no change in the table.
So confused as to why this is happening:
<?php
include("../include/sessions.php");
if(isset($_POST['editcriteria']))
{
$value = $_POST['editcriteria'];
$editUID = $value['editUID'];
$editAddDelete = $value['editAddDelete'];
$editeffectiveDate = $value['editeffectiveDate'];
try
{
$update = $conn->prepare("UPDATE primary_vehicle_data SET `add_delete` = :eadddelete,
`effective_date` = :eeffectivedate WHERE `uid` = :euid");
$update->execute([
'eadddelete' => $editAddDelete,
'eeffectivedate' => $editeffectiveDate,
'euid' => $editUID
]);
if($update)
{
echo "Success: Record Updated";
}
else
{
echo "Error: The Vehcile was not updated.";
}
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
}
?>
I simplified the above code as much as possible. There were several more parameters, but when I removed the parameters and left it with the 3 parameters above, I still get "Success: Record Updated". But the table is literally unaffected.
Why is this happening and how do I fix it?
* UPDATE *
I already confirmed the connection to the database is good. I'm lost.
$update is a PDOStatement object, so when you test
if ($update)
it will always succeed as a PDOStatement object is equivalent to true.
You should be:
checking the result of $update->execute e.g.
if ($update->execute([ /* params */])) {
checking the value in $update->rowCount, which will tell you if any rows were affected by the query.
Related
I m trying to delete a row in php mysql. The row is deleted quiet ok but mysqli_affected_rows($conn) is not giving a response so I can confirm the deletion for the user.
$sql="DELETE FROM `users` WHERE `memberID`='$id'";
$res=mysqli_query($conn,$sql);
if(mysqli_affected_rows($conn) == 1){
echo 'success'
} else {
echo "The User could not be deleted due to some error";
echo mysqli_affected_rows($conn);
}
You don't need to check by boolean value 0 or 1. But if you want to do it that way, you will need to declare a flag before that and then change the flag value according to condition after that you can do it [as your way]
(mysqli_affected_rows($conn) == 1)
But as default a simple if() conditon will check and return true on pass and false on fail.
So, simply you can do:
if($res)
{
//your codes if query is done
} else
{
//your codes if query fails
}
By default, the mysqli_query() function will return you a true if all went well or a false if there is any error. You can check if your query did not return any error like so:
if($res) {
echo "Delete success";
} else {
echo "Delete error: " . mysqli_error();
}
Here is my script structure:
try {
$dbh_conn->beginTransaction();
$stmt1 = $dbh_conn->prepare("SELECT user_id FROM activate_account WHERE token = ?");
$stmt1->execute(array($validate_activate_token));
$num_rows = $stmt1->fetch(PDO::FETCH_ASSOC);
if($num_rows) {
$user_id = $num_rows['user_id'];
$stmt2 = $dbh_conn->prepare("UPDATE users SET active = 1 WHERE id = ?");
$stmt2->execute(array($user_id));
$updated = $stmt2->rowCount();
if ( $updated > 0 ){
$stmt3 = $dbh_conn->prepare("DELETE FROM activate_account WHERE token = ?");
$stmt3->execute(array($validate_activate_token));
$status = "all fine";
} else {
$status = "first problem";
}
} else {
$status = "second problem";
}
$dbh_conn->commit();
echo $status;
die;
} catch(PDOException $e) {
$dbh_conn->rollBack();
$status = "third problem";
echo $status;
die;
}
The result of my code always is second problem. Why? And how can I rewrite my code to fix it?
Note that I've tested this condition if($num_rows) { separately (in another script singly) and it is true, but when I write it into script above, it is always false.
The purpose of transactions is to make sure that queries that must happen together are never broken up. In your use case, the first query can be executed in isolation with no downside.
Put the last two in a transaction, but leave the first alone. If the first fails, just don't run the other two.
If the first succeeds but one of the other two (in the transaction) fails so that neither of the two is committed, you're no worse off for having executed the first.
I use this code for update a record in mysql
This is my code:
<?php
$query = "update seeds set status='success' where id = $x";
$result = mysql_query($query);
if(!$result){
echo 'failed'.$result;
print_r($result);
}else{
echo 'successfully';
}
?>
always successfully printed out.
But when the server is crowded, the 'failed' string is printed out without any value for 'result' variable.
This query always work correctly but sometime returns NULL.
How can I fix this?
there is a issue.
i use transaction with this query.
in fact my actual code is this:
<?php
.
.
.
$QUERY_TRANSACTION = mysql_query('START TRANSACTION');
if(!$QUERY_TRANSACTION){
echo "error 101" ;
exit;
}
$seed_query = "INSERT INTO seeds VALUES('','$username','$theTime','در انتظار')";
$seed_result = mysql_query($seed_query);
if(mysql_affected_rows()!=1){
$QUERY_TROLLBACK = mysql_query('ROLLBACK');
echo "error 102";
exit;
}
$seed_id = mysql_insert_id();
$_SESSION['SEED_ID'] = $seed_id;
$query_values = "(NULL,'$list_number[0]',0,$seed_id)";
for($i=1;$i<count($list_number);$i++){
$query_values .= ",(NULL,'$list_number[$i]',0,$seed_id)";
}
$r_query = "INSERT INTO rc_members VALUES $query_values";
$r_result = mysql_query($r_query);
if(mysql_affected_rows()<=0){
$QUERY_TROLLBACK = mysql_query('ROLLBACK');
echo "error 103";
exit;
}
$QUERY_COMMIT = mysql_query('COMMIT');
//--------------
$QUERY_TRANSACTION = mysql_query('START TRANSACTION');
if(!$QUERY_TRANSACTION){
echo "error 104" ;
exit;
}
$s_status = the_process($list_number,$m,$seed_id);
if($s_status == 'successful_proc'){
$s_query = "UPDATE seeds SET status='انجام شده' WHERE id=$seed_id";
$s_result = mysql_query($s_query);
//----------------logg file
$filename = "debug.txt" ;
$filepointer =fopen($filename ,"w") ;
fwrite($filepointer , print_r($s_result,true)) ;
fclose($filepointer) ;
//-----------------------
if(!$s_result){
echo "error 105".$s_result;
exit;
}
$QUERY_COMMIT = mysql_query('COMMIT');
echo 'successfuly process';
}else{
$QUERY_TROLLBACK = mysql_query('ROLLBACK');
echo 'error 106';
exit;
}
$QUERY_COMMIT = mysql_query('COMMIT');
?>
that 'successfully' always printed out. but sometime 'error 105' printed out.
may be transaction is the reason of this error?
that update in db is performed but return null?
If mysql_query returned NULL, then that would be a bug on PHP. How do you know that it is actually returning NULL?
For update statements mysql_query should only return TRUE or FALSE. So your error checking code is fine. As to finding out what went wrong, you will have to call other function - mysql_error() would give you a blurb about what went wrong. So print the value of mysql_error() inside your false block. Like this:
echo 'failed. SQL Err: '. mysql_error()
Do that and you will probably get a clue to as to how 'record got updated, but return value is false'. It should not have happened.
$result in this case is just a resource, it does not contain the reason.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc,
mysql_query() returns TRUE on success or FALSE on error.
Source: PHP Manual
So you can only get TRUE / FALSE from it in your update query. It won't tell you the reason. But as you said it happens when your server is overcrowded so reason probably is "too many connections"
Everything with it is fine. The name of the database and table, the name of the columns etc. $username is good and exists in the database. Yet, after this runs, if I "alert" $dbuid it comes up as 0 and $dbusername comes up as empty. MySQLi throws no errors. (That is why I did if(! .. ) echo error;, to see if it throws an error on anything, but it works perfectly fine.) Where am I going wrong ?
if(!$msmysqli = new mysqli("localhost","root","","ms")){
echo $msmysqli->connect_error;
}
if(!$stmt = $msmysqli->prepare("SELECT id,name,password FROM accounts WHERE name=?")){
echo $msmysqli->error;
}
if(!$stmt->bind_param("s",$username)){
echo $stmt->error;
}
if(!$stmt->execute()){
echo $stmt->error;
}
if(!$stmt->bind_result($dbuid,$dbusername,$dbpassword)){
echo $stmt->error;
}
$stmt->close();
You simply forgt to fetch your result to get the row... thats why your code wasn't working as expected! Another thing to bare in mind is that an object, at least in php, returns always its instance while being constructed! The statement $msmysqli = new mysqli(...) is never going to be false! thats why you should check your connection as shown!
$msmysqli = new mysqli("localhost","root","","ms");
if ( $msmysqli->connect_errno ) echo $msmysqli->connect_error;
if( $stmt = $msmysqli->prepare("SELECT id,name,password FROM accounts WHERE name=?") ) {
$stmt->bind_param("s",$username);
$stmt->execute();
$stmt->bind_result($dbuid,$dbusername,$dbpassword);
$stmt->fetch();
$stmt->close();
} else {
echo $msmysqli->error;
}
$msmysqli->close();
This question already has answers here:
PDO mysql: How to know if insert was successful
(7 answers)
Closed 6 years ago.
How can I test to see if the following query executed successfully?
$STH = $this->_db->prepare("UPDATE UserCreds SET
VerificationString=:newVerificationString, ExpiryDate=:expiryDate
WHERE UserID = :userID;");
$STH->execute($params);
I know I can use lastInsertId() when I'm adding new rows, but what about UPDATEs and SELECTs?
The execute returns true on success and false on failure.
From Docs:
Returns TRUE on success or FALSE on failure.
So you can make sure query ran successfully like:
if ($STH->execute($params))
{
// success
}
else
{
// failure
}
execute() returns true/false based on success/failure of the query:
$status = $STH->execute($params);
if ($status) {
echo 'It worked!';
} else {
echo 'It failed!';
}
One note: a select query which returns no rows is NOT a failure. It's a perfectly valid result that just happens to have NO results.
simply i can count the number of row effected:
$stmt->execute();
$count = $stmt->rowCount();
if($count =='0'){
echo "Failed !";
}
else{
echo "Success !";
}
This is best way to verify Doctrine query result return success or failed
result and same way as per above suggest to check weather query
returns Success on True and Failed on false.
public static function removeStudent($teacher_id){
$q = Doctrine_Query::create()
->delete('Student s')
->where('s.teacher_id = ?');
$result = $q->execute(array($teacher_id));
if($result)
{
echo "success";
}else{
echo "failed";
}
}