Does testing a PDO query in an if statement also run it? - php

I was checking up how to test for query success, and saw this method:
if($db->query(...)){
//It was successful!
} else {
//Something went wrong
}
But does this only check if the query would run successfully, or does it run the query and then return true/false? I'm assuming it is indeed run, but this brings me to the main question:
Can I test if a query was successful in this way, and at the same time store the result set in a variable, like so?
if ($result = $db->query(...)){
//something
}
Otherwise I'd have to run the same query once inside the if statement and then to store the results in a variable..
But yeah, basically, that's all I'm wondering. Thanks for all friendly help. :)

Functions and methods don't behave differently within a specific context.
If $bd->query() runs the query the behavior won't change if it's in a if statement.
So, yes it does run the query
you could try something like this to test your query
$result = $db->query();
if (is_null($result)) {
var_dump($result);
}

If you are looking to validate a query before running it then you can try preparing it first like this:
$prepare = $db->prepare($sql);
// check if SQL compiled
if($prepare)
{
// execute the SQL
$execute = $prepare->execute();
}

Related

sql update not changing data in DB

I made a simple update query using PDO in PHP :
$pdos = connect_db();
$pdos->beginTransaction();
try {
$query = "UPDATE `myo`.`question` SET `intitule` = 'Question azeerrr' WHERE `question`.`id` = 1";
$pdo = $pdos->prepare($query);
$pdo->execute();
return $pdo->rowCount();
catch (Exception $e) { print_r ($e); exit (); }
Which doesnt seem to work (the data is not changed in the database) even though i get no error message and even receive "1" from rowCount() meaning the update was successful.
And also, if i copy and paste this query in PHPmyadmin and run it, it works and the row is modified,
Could it be something about rights to execute an UPDATE from my website and not beeing the same as when you are logged into PHPmyadmin?
EDIT :
FIXED : thanks for you help : PDO::commit(); was needed to close my PDO::beginTransaction();
As you begin a transaction with $pdos->beginTransaction(); I'm pretty sure that you need commit it using $pdos->commit();
See the documentation for more information.
If you are using PDO's transaction, you must commit your changes to apply the modifications in your database.
See PDO::commit() function.
Even if you update a record with new values or with existing values, MySql always returns 1 in both the cases....

PHP prevent die before executing full code

I have code as below where I am redirecting the user at the end but sometimes it seems that the output variable is not getting set or insert query is not getting executed . So is there any way I can wait for all the operations to be completed before the die statement is executed.
Thanks
$diff=levenshtein(strtolower($str1),strtolower($str2));
if($diff<=2)
{
$output="ok";
}
else
{
$output="Not ok";
}
$query="INSERT INTO `table` (`sn`, `output`) VALUES (NULL,'$output')";
$result=mysqli_query($con,$query);
header('Location: http://www.domain.com/');
die;
There may be several reasons why it doesn't work.
The first one and most obvious is that is enough to have only one simple warning on your page (variable X is not set) and this will broke your header() command. It would say that headers have been already set.
The second problem is that sometimes the server is so busy answering other request and your $con variable will be a Boolean false instead of a reliable database connector, therefore your query could fail because of this too.
I encountered both situations in real life and I solved them by ensuring that every variable is set before use it and by checking if the query was executed successfully.
You can check if a variable is set by using this code:
if (!isset($variable)) $variable = "set me here";
You can check if your query was succesfully executed by adding this:
if (!$result) {
//do something here in case your query failed
}

Why I am getting the Error "Commands out of sync; you can't run this command now"

The Documentation of the Error Mentioned in the Title Says
If you get Commands out of sync; you can't run this command now in
your client code, you are calling client functions in the wrong order.
This can happen, for example, if you are using mysql_use_result() and
try to execute a new query before you have called mysql_free_result().
It can also happen if you try to execute two queries that return data
without calling mysql_use_result() or mysql_store_result() in between.
From here: http://dev.mysql.com/doc/refman/5.0/en/commands-out-of-sync.html
But In First Query I am not fetching any data from mysql database, I am just inserting. And In second Query I am getting the data from database.
Here is My code
$connection = mysqli_connect("localhost","username","password","tbl_msgs");
if(mysqli_connect_errno($connection))
{
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
$query = "INSERT INTO users (total_comments, total_views)
VALUES ({$total_comments}, {$total_views});";
$query .= "INSERT INTO msgs (notifications) VALUES ({$notifications})";
mysqli_multi_query($connection,$query);
Upto this Step every thing is fine. But When I execute the following query It gives the Error
$select_query = "SELECT * FROM msgs WHERE msg_id = {$msg_id}";
$result_set = mysqli_query($connection,$select_query);
if(!$result_set) {
die(mysqli_error($connection));
}
Here it gives the Error Commands out of sync; you can't run this command now. I can't understand this situation
Note: There is any Problem in the Query, I have executed the same query directly to PHPMyAdmin and it works fine.
There are result set pending from the query:
mysqli_multi_query($connection,$query);
You need to use/store result before you can proceed with next query after:
Since you look like you don't really care about the first result set, do this after the multi query..
do
{
$result = mysqli_store_result($connection);
mysqli_free_result($result);
}while(mysqli_next_result());
Another alternative is to close the connection and starts it again..
mysqli_close($connection);
$connection = mysqli_connect("localhost","username","password","tbl_msgs");
It all depends on your requirements.

displaying errors if mysql_query not successful

I created a debug function to email me the mysql error and query executed if a query is not successful.
I call it like this:
mysql_query($sql) or $this->debug->dbErrors($sql);
And the function is:
function dbErrors($sql = ''){
if($this->doDebug)
echo mysql_error()."<br/>".$sql;
else
#mail(hidden_email,$_SERVER['HTTP_HOST'].' Mysql Error','A error occured in '.$_SERVER['HTTP_HOST'].':<br/>'.mysql_error().'<br/>'.$sql);
}
The problem is that i'm receiving emails even when the query executes fine (at least the data is inserted and everything works out ok)
What i doing anything wrong?
Thanks
That 'or' construct may be causing issue, I would do something like:
$result = mysql_query($sql);
if (!$result) {
$this->debug->dbErrors($sql);
}
This way you are doing an explicit check to see if $result is a boolean false (query is invalid), or a resource (query is valid). The point is to only call on $this->debug->dbErrors() if there indeed is an issue, otherwise the way your code is written, every query will be emailed.
or something simple like:
mysql_query($sql) or die(dbErrors($sql));

PDO Unbuffered queries

I'm trying to get into PDO details. So I coded this:
$cn = getConnection();
// get table sequence
$comando = "call p_generate_seq('bitacora')";
$id = getValue($cn, $comando);
//$comando = 'INSERT INTO dsa_bitacora (id, estado, fch_creacion) VALUES (?, ?, ?)';
$comando = 'INSERT INTO dsa_bitacora (id, estado, fch_creacion) VALUES (:id, :estado, :fch_creacion)';
$parametros = array (
':id'=> (int)$id,
':estado'=>1,
':fch_creacion'=>date('Y-m-d H:i:s')
);
execWithParameters($cn, $comando, $parametros);
my getValue function works fine, and I get the next sequence for the table. But when I get into execWithParameters, i get this exception:
PDOException: SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute. in D:\Servidor\xampp_1_7_1\htdocs\bitacora\func_db.php on line 77
I tried to modify the connection attributes but it doesn't work.
These are my core db functions:
function getConnection() {
try {
$cn = new PDO("mysql:host=$host;dbname=$bd", $usuario, $clave, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
));
$cn->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
return $cn;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
function getValue($cn, $comando) {
$resul = $cn->query($comando);
if (!$resul) return null;
while($res = $resul->fetch()) {
$retorno = $res[0][0];
break;
}
return $retorno;
}
function execWithParameters($cn, $comando, $parametros) {
$q = $cn->prepare($comando);
$q->execute($parametros);
if ($q->errorInfo() != null) {
$e = $q->errorInfo();
echo $e[0].':'.$e[1].':'.$e[2];
}
}
Somebody who can shed a light for this? PD. Please do not suggest doing autonumeric id, cause i am porting from another system.
The issue is that mysql only allows for one outstanding cursor at a given time. By using the fetch() method and not consuming all the pending data, you are leaving a cursor open.
The recommended approach is to consume all the data using the fetchAll() method.
An alternative is to use the closeCursor() method.
If you change this function, I think you will be happier:
<?php
function getValue($cn, $comando) {
$resul = $cn->query($comando);
if (!$resul) return null;
foreach ($resul->fetchAll() as $res) {
$retorno = $res[0];
break;
}
return $retorno;
}
?>
I don't think PDOStatement::closeCursor() would work if you're not doing a query that returns data (i.e. an UPDATE, INSERT, etc).
A better solution is to simply unset() your PDOStatement object after calling PDOStatement::execute():
$stmt = $pdo->prepare('UPDATE users SET active = 1');
$stmt->execute();
unset($stmt);
The problem seems to be---I'm not too familiar with PDO--- that after your getValue call returns, the query is still bound to the connection (You only ever ask for the first value, yet the connection returns several, or expects to do so).
Perhaps getValue can be fixed by adding
$resul->closeCursor();
before the return.
Otherwise, if queries to getValue will always return a single (or few enough) value, it seems that using fetchAll will be preferred.
I just spend 15 minutes googling all around the internet, and viewed at least 5 different Stackoverflow questions, some who claimed my bug apparently arose from the wrong version of PHP, wrong version of MySQL library or any other magical black-box stuff...
I changed all my code into using "fetchAll" and I even called closeCursor() and unset() on the query object after each and every query. I was honestly getting desperate! I also tried the MYSQL_ATTR_USE_BUFFERED_QUERY flag, but it did not work.
FINALLY I threw everything out the window and looked at the PHP error, and tracked the line of code where it happened.
SELECT AVG((original_bytes-new_bytes)/original_bytes) as saving
FROM (SELECT original_bytes, new_bytes FROM jobs ORDER BY id DESC LIMIT 100) AS t1
Anyway, the problem happened because my original_bytes and new_bytes both where unsigned bigints, and that meant that if I ever had a job where the new_bytes where actually LARGER than the original_bytes, then I would have a nasty MySQL "out of range" error. And that just happened randomly after running my minification service for a little while.
Why the hell I got this weird MySQL error instead of just giving me the plain error, is beyond me! It actually showed up in SQLBuddy (lightweight PHPMyAdmin) when I ran the raw query.
I had PDO exceptions on, so it should have just given me the MySQL error.
Never mind, the bottom line is:
If you ever get this error, be sure to check that your raw MySQL is actually correct and STILL working!!!
A friend of mine had very much the same problem with the xampp 1.7.1 build. After replacing xampp/php/* by the 5.2.9-2 php.net build and copying all necessary files to xampp/apache/bin it worked fine.
If you're using XAMPP 1.7.1, you just need to upgrade to 1.7.2.

Categories