PDO execute in a if statment - php

I'm not sure if i'm doing this right.
This is the problem:
if ($result->execute() && $result2->execute()){}
Is this something that can be done or not?
My goal is to do something inside IF only if both queries works.
I couldn't find nothing online about that.

You can certainly do this. PDO's execute() statement returns true on success and false on failure. I would change the style somewhat so it's easier to read, but there's no reason you can't do this.
$success1 = $result->execute();
$success2 = $result2->execute();
if ( $success1 and $success2 ) {
// Do stuff here on failure
}
else {
// Do stuff on failure here
}

Related

How to debug PDO script?

I have a PHP script that is executed daily by my server thanks to cron.
This script contains PDO queries to add, edit, and delete data from my MySQL database.
The script does not work as expected, especially the last part of the query which is supposed to remove some rows:
$stmt = $conn->prepare("DELETE FROM `mkgaction` WHERE score IS NULL");
$stmt->execute();
if($stmt->execute()) {
echo "delete succeeded<br>";
} else {
echo "delete failed<br>";
}
When executed manually via PHPMyAdmin, every query works fine. When executed via this script it does not work despite the message showing "delete succeeded".
I suppose the best way to understand what actually happens is to read the response from the database, but I don't know how to do that.
Would you help me? :-)
Thanks
Always check the return value of prepare() and execute(). They return the boolean value false if there's a problem.
Then you should check the specific error and report that error to help debugging.
$stmt = $conn->prepare("DELETE FROM `mkgaction` WHERE score IS NULL");
if ($stmt === false) {
die(print_r($conn->errorInfo(), true));
}
$ok = $stmt->execute();
if ($ok === false) {
die(print_r($stmt->errorInfo(), true));
}
echo "delete succeeded<br>";
Admittedly, checking every call gets to be a lot of repetitive code. An alternative is to enable exceptions, if you're comfortable writing code to handle exceptions. See https://www.php.net/manual/en/pdo.error-handling.php

Getting an error when trying to insert data to table

So I have this code in a php file:
$query="INSERT INTO tec (name) VALUES ('$name')";
$done=mysql_query($query);
if($done == 'null') {
$output = json_encode(array('type'=>'error', 'message' => $mess['error'].$done.'</b></div>'));
} else {
$output = json_encode(array('type'=>'success', 'message' => $mess['success']));
}
It inserts a name into a table named "tec". If $done == 'null' then I print an error message.
The problem is that when I run the code, it inserts the data correctly, but I get the error message.
I tried to read $done and its equal to 1.
Should I do something like:
if($done == 1){
//OK
}else{
//NOT OK
}
Or is there any way to fix this?
The documentation says that mysql_query returns FALSE on error. That means instead of testing whether it's equal to 'null' (a string which compares as TRUE), you could just test the boolean-ness directly:
if($done){
//OK
}else{
//NOT OK
}
I would be remiss if I didn't mention that the mysql_* family of functions is deprecated, unsafe, and will be removed from future versions of PHP! Instead, I can personally recommend PDO, which I've used with a good amount of success.
As per the documentation of mysql_query function's php manual
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
So, search if it's TRUE or FALSE.
if ($done == TRUE) {
Hi I think you should use boolean
just try this (you'd better use mysqli instead mysql
if(!done)
{
// something wrong
echo mysql..
}
else
{
// everything works fine....
}
The error catching must be like the following:
if($done === false){
//NOT OK
}else{
//OK
}
But as #John Conde mentioned do not use mysql_* because its deprecated.

PHP or die and if else conditional idiosyncrasies

I have function that performs a mysql_query() and then does some other stuff.
I want to be able to perform another mysql_query() only if the first one succeeds.
Here is the function
function myFunction($qtext)
{
mysql_query($qtext) or die(mysql_error() . "\n");
//do some more stuff
return true;
}
I'm calling the function and attempting to check if it failed with an if else conditional...
if(!myFunction($query_text))
{
echo "first query failed";
}
else
{
mysql_query($query_text1) or die (mysql_error() . "\n");
}
This seems to work when the first query passes, but if the first query fails it goes to the or die and returns the mysql_error() text and the echo "first query failed"; line in the conditional is never reached.
Ideally id like to be able to alert the user with the mysql_error text but without or dieing, so I can run more code in the conditional.
Any help with explanations of behavior is greatly appreciated.
Thanks.
p.s.
I'm a beginner... I'm not sure if Im using the return true; properly in the function
You're always returning true in the function - you need to also return false if you're checking it in an if() statement.
function myFunction($qtext) {
// run the query
$sql = mysql_query($qtext);
// see if there was a result (or whatever you're checking)
if(mysql_num_rows($sql) > 0) {
// do some more stuff
return true;
} else {
return false;
}
}
Also, you really should learn mysqli or POD instead of mysql, as mysql is depreciated. I also recommend you don't use die() unless you're testing. Build an error handling function instead - it's actually quite easy and will handle errors gracefully instead of abruptly killing the script and annoying your users. You also don't want to print error messages directly to your browser because it can compromise your site's security. :)
Just an FYI: I use a database class and run my queries like this. It's fast and clean.
if($db->get_results("SELECT email FROM users WHERE email='".$db->escape($email)."'")) {
return true;
} else{
return false;
}
To prevent "or die" from happening, replace it with return false:
function myFunction($qtext)
{
$result = mysql_query($qtext);
if ($result === false)
{
return false;
}
//do some more stuff
return true;
}
that way your check later on will work and condition will fire. You don't have to use "or die", that is reserved for the cases where you want to halt all execution.
die() kills the script instantly. That function will never return any value if you call die() inside it, you will never be able to perform other queries. Only the destructors of instanced object are still ran after a die() call, and with several restrictions.
If you want to be able to continue doing stuff after a query fails, you must never call die(). Instead, just check if mysql_query() returned FALSE as Tim suggested. Note the === operator, its important to a proper error check here.
If you still want to print the error like die() would, use print() or echo instead.

how to transform a function from mysql into mysqli

hello i would like to transform a mysql-function into a mysqli version. this function is for checking if an user exists or not. so i'm new to functions and even to mysqli. thats why i'm having problems while transforming it.
the mysql-version is:
function a($uname){
return (mysql_result(mysql_query("SELECT COUNT (`a`) FROM `table_1` WHERE `a`='$uname'"), 0) == 1) ? true : false;
}
the mysqli-version i thought would be:
function a($uname){
return (mysqli_num_rows(mysqli->query("SELECT COUNT (`a`) FROM `table_1` WHERE `a`='$uname'"), 0) == 1) ? true : false;
}
i know that there is no mysql_result anymore. i decided to use mysqli_num_rows. but this function does not work and i have no clue why. error_reporting is enabled but when calling the page, i will get a blank page with no error messages?!
so if there is someone who could help me out i really would appreciate.
thanks alot.
You need a helper function to put all dirty mysqli internals behind the scenes.
Like safemysql. It can mimic mysql_result as well:
function a($uname){
global $db; // with mysqi you have to connect once and then use this connection
return (bool)$db->getOne("SELECT COUNT (1) FROM table_1 WHERE a=?s"), $uname);
}
and can solve dozens of similar issues.
Freely from the documentation:
mysqli->query returns either a mysqli_result object for queries, which actually return some results, 'false' for failed queries and 'true' for all other queries (if successful).
You will not know anything about the result of your query, unless you check the result more thoroughly.
Try something like this: (This assumes that the connection has been successfully established, and that $uname has been properly escaped.)
function a($uname) {
$found = false;
$result = mysqli->query("SELECT `a` FROM `table_1` WHERE `a`='$uname'");
if($result) {
//We used a 'SELECT' query and the query was successful. That means, we now have a mysqli_result object.
$found = ($result->num_rows == 1); //Determines, if something was actually found or not.
$result->close(); //Frees some ressources. Not necessary, but doesn't hurt either.
} else { //The query failed, as such we have nothing to evaluate.
die("Queryerror: ".mysqli->error);
}
return $found;
}
I changed the query parameter from 'COUNT' to 'a', because otherwise 'num_rows' will ALWAYS return 1, even if the actual count is '0'. This way, it returns the number of matched rows, essentially return '0' for 'no match' or '1' for 'match'.

$stmt->execute() : How to know if db insert was successful?

With the following piece of code, how do i know that anything was inserted in to the db?
if ($stmt = $connection->prepare("insert into table (blah) values (?)")) {
$stmt->bind_param("s", $blah);
$stmt->execute();
$stmt->close();
}
I had thought adding the following line would have worked but apparently not.
if($stmt->affected_rows==-1){$updateAdded="N"; echo "failed";}
And then use the $updatedAdded="N" to then skip other pieces of code further down the page that are dependent on the above insert being successful.
Any ideas?
The execute() method returns a boolean ... so just do this :
if ($stmt->execute()) {
// it worked
} else {
// it didn't
}
Update: since 2022 and beyond, a failed query will throw an error Exception. So you won't have to write any code to "skip other pieces of code further down the page" - it will be skipped automatically. Therefore you shouldn't add any conditions and just write the code right away:
$stmt = $connection->prepare("insert into table (blah) values (?)");
$stmt->bind_param("s", $blah);
$stmt->execute();
If you need to do something in case of success, then just do it right away, like
echo "success";
You will see it only if the query was successful. Otherwise it will be the error message.
Check the return value of $stmt->execute()
if(!$stmt->execute()) echo $stmt->error;
Note that line of code does perform the execute() command so use it in place of your current $stmt->execute() not after it.
Starting on PHP/8.1.0, the default setting is to throw exceptions on error, so you don't need to do anything special. Your global exception handler will take care of it, or you can try/catch for specific handling.
For older versions, you can check the manual pages of whatever function you are using:
prepare() - returns a statement object or FALSE if an error occurred.
bind_param() - Returns TRUE on success or FALSE on failure.
execute() - Returns TRUE on success or FALSE on failure.
close() - Returns TRUE on success or FALSE on failure.
In practice, though, this gets annoying and it's error prone. It's better to configure mysqli to throw exceptions on error and get rid of all specific error handling except for the few occasions where an error is expected (e.g., a tentative insert that might violate a unique constraint):
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
Default value used to be MYSQLI_REPORT_OFF. On PHP/8.1.0 it changed to MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT.
You can check the returned value after the execute :
if ($stmt->execute()) {
// ok :-)
$count = $stmt->rowCount();
echo count . ' rows updated properly!';
} else {
// KO :-(
print_r($stmt->errorInfo());
}
if you mean that you want to know the number of affected rows you can use rowCount on the pdo statement
$stmt->rowCount();
after execute;
if you are talking about error handling I think the best option is to set the errmode to throwing exteptions and wrap everything in a try/catch block
try
{
//----
}
catch(PDOException $e)
{
echo $e->getMessage();
}
Other way:
if ($stmt->error){
echo "Error";
}
else{
echo "Ok";
}

Categories