How to tell when query executed successfully in PHP PDO? [duplicate] - php

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";
}
}

Related

Update reads successful in console, but the database is unaffected

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.

Confirming deletion of record in mysql php

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

What does true false actually do in php

I have seen many php function & many php scripts, I always find
function check() {
if(isset($_POST['example'])){
return true;
} else {
return false;
}
}
What does this true & false do? does false stops the query from executing further?
Actually i have a login page where I want to stop the executing if user is not found in database like:
if(mysqli_num_rows($query) !=1) {
// if result is not 1 then executing must be stop here, hello should not be echo
}
echo "hello";
further down are more script that should be executed only when result is 1
According to http://php.net/manual/en/function.return.php
-for those of you who think that using return in a script is the same as using exit note that: using return just exits the execution of the current script, exit the whole execution.
So i tried a code at my localhost
$a = 1;
if($a == 0){
echo "Its 0"; }
else{ return; }
echo "hi";
after wring return false the word hi was not executed & when i removed return false then the hi word was executed
Now i will tell you what i really want to know
$query3 =mysqli_query($connecDB, "SELECT * FROM users WHERE username='$username'");
if(mysqli_num_rows($query3) != 1)
{
$er1 = "Username doesn't exist";
}
else{
$query4 ="SELECT * FROM users WHERE email='$email'";
$result1=mysqli_query($connecDB, $query3);
if(mysqli_num_rows($result1) != 1)
{
$er1 = "Email doesn't exist";
} else {
// do this
}
}
Now you see above i have used if statement into else statement and more if statement into else which makes my php script very much complicated & very hard to understand
I just want to know what is the better way to execute script like shown below
$query3 =mysqli_query($connecDB, "SELECT * FROM users WHERE username='$username'");
if(mysqli_num_rows($query3) != 1)
{
$er1 = "Username doesn't exist";
}
else{ // stop the execution here & just print this $er1 on the page without exit or die }
i want to stop the execution because of below example
$a = 1;
if($a == 0){
echo "Its 0 "; }
else{ //if it's not 0 then it means user is not registered do not echo echo hi below }
echo "hi";
Now the hi is always executed
What makes the function stop executing is the Control Structure return, true or false are Boolean variables, also represented as 1 and 0 respectively.
if(function that returns a boolean !=1)
The if will only execute if function that returns a boolean is true (1)
Learn more about return and Boolean variables
Please note that mysql_* is now deprecated as of PHP7 because of security issues. It is suggested that you switch to mysqli_* or PDO extensions.

my sql sometimes ok, but sometimes failed

I was writing the php to query the MySQL DB, but the sql sentence works sometimes but failed sometimes .**when it works, it will return records, when it failed it will say: **You have an error in your SQL syntax. I don't know how to fix it,please give me a hand.thanks.the *_id and type is integer,others are string or date type.
function getMyAwardRecords()
{
global $db, $userId, $nickName;
$result0 = $db->fetchrows("SELECT user_nick,type,create_date FROM records WHERE type=0 AND user_id={$userId}");
// echo $userId;
$result = $db->fetchrows("SELECT records.user_nick, records.type, records.create_date, awards.code FROM records, awards WHERE records.award_id = awards.award_id AND records.user_id = {$userId}");
$result = array_merge($result, $result0);
// print_r($result);
if($result)
{
echo ajaxResponse(200,$result);
}
else
{
echo ajaxResponse(400);
}
}

How to test if a MySQL query was successful in modifying database table data?

I have the following simple php code snippet, which will, when called, delete a relevant article from a database. The result is passed to a javascript function, which will update the page via AJAX. I would like to return the string false if the query fails, as I've below.
if($cmd=="deleterec"){
$deleteQuery = "DELETE FROM AUCTIONS1 WHERE ARTICLE_NO = ?";
if ($delRecord = $con->prepare($deleteQuery)) {
$delRecord->bind_param("s", $pk);
$delRecord->execute();
$delRecord->close();
echo "true";
} else {
echo "false";
}
}
I would like to know what I have missed and the correct way to check if a query was successful or not.
You're currently only checking whether the SQL statement is correctly prepared, you're not checking whether it actually deleted the record.
Try:
...
echo ($delRecord->affected_rows > 0) ? 'true' : 'false';
$delRecord->close();
That doesn't address whether you're correctly checking the result string in your Javascript code - if that's a problem we'll need more information.
You need to use mysqli->affected_rows() for checking if the query was successful (or you could use mysqli_stmt->execute()'s result value).
Taking your example, and modifying nothing but for the above:
if($cmd=="deleterec") {
$deleteQuery = "DELETE FROM AUCTIONS1 WHERE ARTICLE_NO = ?";
if ($delRecord = $con->prepare($deleteQuery)) {
$delRecord->bind_param("s", $pk);
$delRecord->execute();
if ($delRecord->affected_rows > 0) {
echo "true";
} else {
echo "false";
}
$delRecord->close();
}
}
Use the return value of mysqli_stmt->execute() to see if the query was executed successful.
if($cmd=="deleterec"){
$deleteQuery = "DELETE FROM AUCTIONS1 WHERE ARTICLE_NO = ?";
$delRecord = $con->prepare($deleteQuery);
if ( $delRecord === false ) {
echo "false";
}
$delRecord->bind_param("s", $pk);
if ( $delRecord->execute() ) {
echo "true";
} else {
echo "false";
}
$delRecord->close();
}
Checking prepare() could be left out because the query is fixed and should be working (unless there is an error on the server side). execute() returns true, if the query was executed successful. Using affected_rows() can be misleading because perhaps there was no item to delete and therefore affected_rows() whould return 0. Nontheless the query was successfully executed.
function run_query($query,$conn,$dbname){
$conn->select_db($dbname);
if($result = $conn->query($query)){
return $result;
}
else{
echo 'error ';
exit();
}
}
run_query() accepts three parameters, the query, connection, and DB. will through an error if the query was unsuccessful, else result object will be returned.

Categories