This question already has answers here:
checking if SQL query was excuted in PDO [duplicate]
(2 answers)
Closed 9 years ago.
I would like to know how to check if the insert statement is executed or not.
my current code of checking it is this:
$query = $conn->prepare("INSERT INTO editlog VALUES('',:whoadd,:doing,NOW())");
$query-> execute(array(':whoadd' => $whoadd,':doing' => $doing));
if ($query->rowCount() > 0) {
// insert statement have been executed
}
else
{
// something went wrong
}
is there a better way than using $query->rowCount() > 0 ? I have heard that rowCount() itself runs a query to mysql database..so, what is a good alternative?
As Mark Parnell suggested, wrapping the execute call in an if statement does the trick. It might prove useful later on to set some attributes of your database object, too:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Causing PDO to throw exceptions (PDOException) in case a query fails. You can set these attributes by passing an array as fourth parameter to the constructor:
$pdo = new PDO('mysql:dbname=foobar;host=127.0.0.1','your','pass',
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ'));
For example, here's a full list of all attributes that can be specified.
Check the return value of the execute call:
if ($query->execute(array(':whoadd' => $whoadd,':doing' => $doing))) {
// insert statment have been excuted
}
else
{
// something went wrong
}
PDOStatement::execute() itself will return true on success or false on failure.
Related
This question already has answers here:
Getting raw SQL query string from PDO prepared statements
(16 answers)
Why does this PDO statement silently fail?
(2 answers)
Closed last month.
I'm trying to come up with a way to control what happends if some UPDATE/INSERTS into a BD fail.
private $db;
public function __construct() {
$dsn = 'mysql:dbname=BDNAME;host=localhost';
$this->db = new PDO($dsn, 'USEER', 'PASSWORD', array('charset' => 'utf8'));
}
public function createnewthingtodo($what,$where,$when,$how,$done){
$sql= "INSERT INTO TODOLIST (what,where,when,how,done) VALUES (:what, :where, :when, :how, :done)";
$st = $this->db->prepare ($sql);
$st->bindValue(':what',$what);
$st->bindValue(':where',$where);
$st->bindValue(':when',$when);
$st->bindValue(':how',$how);
$st->bindValue(':done',$done);
if($st->execute()){
return true;
}else{
return false;
}
}
This example is returning always false, if i delete the last "if" and put the execution part just below the last binvalue, it works just fine, but then i end up with no error handling, any ideas on how can i achieve this? Thanks for your time.
This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 6 years ago.
Here is my prepared statement
$stmt = $db->prepare("UPDATE user SET :property=:value WHERE `id`=:id");
$stmt->execute([':property' => $property, ':value' => $value]);
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
How can I quickly verify that the query has gone through successfully?
I was thinking maybe an if() around the execute part?
Try this
if($stmt->rowCount() > 0){
echo 'SUCCESS';
}else{
echo 'ERROR';
}
All you need to do is test the returned $stmt like this.
Remember both the prepare and the execute can fail and should be checked
$stmt = $db->prepare("UPDATE user SET :property=:value WHERE `id`=:id");
if ( $stmt == false ) {
print_r($db->errorInfo());
exit;
}
$stmt->execute([':property' => $property, ':value' => $value]);
if ( $stmt == false ) {
print_r($db->errorInfo());
exit;
}
This query will definitely fail
Now I look closer, you have a huge syntax error in the query. You cannot parameterise column or table names.
You also pave 3 parameters and only 2 values
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
Why would num_rows ever return null? It should always return a number representing the exact number of rows in the result set.
The following code returns null for num_rows:
<?php
include_once 'includes/psl-config.php'; // host, user, password, database
$db = new PDO('mysql:host='.HOST.';dbname='.DATABASE.';charset=utf8', USER, PASSWORD,
array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
if ($res = $db->query("select 'Hello world!'")){
if (is_null($res)){
echo "Result is null<br>";
}
if (is_null($res->num_rows)){
echo "Num rows is null<br>";
} else {
echo "Rows returned: ".$res->num_rows."<br>";
}
while ($row = $res->fetch_row){
echo "Text returned = $row[0]<br>";
}
echo "Done";
} else {
echo "SQL error";
}
The resulting page displays "Num_rows is null".
This is so simple, I must be missing something!
The manual says num_rows always returns an int.
I use mysqli query, which stores the results by default. I don't need to use store_result.
Result is not null.
Since you are using PDO and not MySQLi, num_rows is not applicable. That being said, in general, I have found rowCount() is reliable when it comes to MySQL, however, as it states in the manual you should not rely on the rowCount() regarding SELECT statements:
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.
The recommendation is to use a COUNT() sql statement instead for greatest reliability across database platforms:
$db->query("SELECT COUNT(*) FROM table_name");
You are using PDO. So it should be
$res->rowCount()
instead of
$res->num_rows
This question already has answers here:
How do I check db query returned results using PHP's PDO
(3 answers)
Closed 9 years ago.
in mysql_query we can check if the query was executed or not by doing this:
$query = $yourdbconnection->fetch_array(mysql_query("SELECT * FROM tbl_name"));
if ($query){ // query is working }
else { // query is not working }
in PDO, I am doing something like this:
$query = $yourdbconnection->query("SELECT * FROM tbl_name");
$fetchquery = $query->fetchAll();
if ($fetchquery) { // query is working}
else { // query not working}
Is my code effective? what exactly the if statement doing? Is it doing the same thing that mysql_query was doing? How can I check if the query is returning 0 rows or not?
[EDIT]
I have found those solutions as a workaround to the problem
using $stmt->fetch()
prepare($sql);
$stmt->execute();
if ($data = $stmt->fetch()) {
do {
echo $data['model'] . '<br>';
} while ($data = $stmt->fetch());
} else {
echo 'Empty Query';}
?>
adding another query to count the number of rows see this answer
However, I am still looking for better solutions
To see if your query was executed, I would suggest setting your PDO in exception mode like Your Common Sense suggested. You can do it like this:
$dbh = new PDO('mysql:host=localhost;dbname=db', 'user', 'pass');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Concerning the best way to check if a query returned values or not in PDO, I suggest just doing a SELECT COUNT(*) FROM table query, like this:
<?php
$query = $dbh->query('SELECT COUNT(*) FROM table');
if ($query->fetchColumn() != 0) {
/* Query has result(s) */
$query = $dbh->query('SELECT * FROM table');
/* ... */
} else {
/* Query has no results */
}
?>
Let me know if you have any other questions.
there are 2 questions in your post.
1) what is the best way to check if the query returned values or not in PDO?
check returned values
2) how to check if SQL query was excuted in PDO
set PDO in exception mode as described in the tag wiki
By the way, for the "SELECT * FROM tbl_name" query you may wish to use fetchAll() instead of fetch().
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 6 years ago.
I am just trying out PDO and I get this error, Fatal error: Call to a member function fetch() on a non-object, but isn't it already on the $this->db object?
class shoutbox {
private $db;
function __construct($dbname, $username, $password, $host = "localhost" )
{ # db conections
try {
$this->db = new PDO("mysql:host=".$hostname.";dbname=".$dbname, $username, $password);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
function getShouts()
{
$sql_shouts = $this->db->query('SELECT shoutid, message, pmuserid, ipadress, time FROM shouts WHERE pmuserid == 0');
return $sql_shouts->fetch(PDO::FETCH_OBJ);
}
}
Look carefully at the documentation for PDO::query, particularly the "Return Values" section:
PDO::query() returns a PDOStatement
object, or FALSE on failure.
The important bit is "FALSE on failure". FALSE is not an object, so calling ->fetch() is bad news.
The error is probably due to your use of "==" comparison operator. In SQL, it's just "=".
You should test that the $sql_shouts is not false, and then do something smart with the error, if there was one:
<?PHP
$sql_shouts = $this->db->query('...');
if ($sql_shouts === false){
$errorInfo = $this->db->errorInfo();
//log the error or take some other smart action
}
return $sql_shouts->fetch(PDO::FETCH_OBJ);
I would say that your query is not executing due to incorrect syntax. You should really check PDO's errorinfo static function to see if the query errored out or not.
Here is a potential correct SQL statement:
$sql_shouts = $this->db->query('SELECT shoutid, message, pmuserid, ipadress, `time` FROM shouts WHERE pmuserid = 0');
I believe Time is a reserved word in MySQL I would recommend using a different name but encasing it in backticks will alleviate that issue. 1 equal sign is used for mysql, not two. But yea, look into the errorinfo function to determine if your query failed due to a syntax error and handle it gracefully.
It happens when the table doesn't exist also. make sure it actually exists, and isn't just a holder in the database due to hard drive errors.
When that happens I suggest you recreate the database/table.
I got this error message due to a silly mistake with brackets. It was nested inside an if statement and just didn't see it.
db_query("SELECT thing FROM table WHERE var=:var", array(":var" => $var)->fetchField());
It took me a while to work out that I didn't close the db_query bracket in the right place. Maybe it helps someone else staring at this wondering wth. Correct:
db_query("SELECT thing FROM table WHERE var=:var", array(":var" => $var))->fetchField();