checking if SQL query was excuted in PDO [duplicate] - php

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().

Related

PDO rowCount and fetchColumn both not returning correct result [duplicate]

This question already has answers here:
Row count with PDO
(21 answers)
Closed 6 years ago.
I've tried various things to get this short bit of code to work. What it does is it connects to the database via PDO and then selects all rows that match a post variable. If there is more than 0 rows, update the licensekey rows to be "used" and echo true.
I have tried both rowcount and fetchcolumn and count(*) for sql, and none of shown any differences. In MySQL itself, I have used a valid licensekey and it indeed returns one row.
<?php
if(isset($_POST['licensekey'])) {
try {
$db = new PDO("mysql:host=localhost;dbname=validation", "test", "test");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
die($e->getMessage());
}
$search = ("SELECT * FROM validated WHERE activationkey=:lk AND used='0'");
$result = $db->prepare($search);
$result->bindParam(":lk", $_POST['licensekey']);
$result->execute();
if($result->rowCount() > 0) {
$used = ("UPDATE validated SET used='1' WHERE validated.activationkey=:lk");
$result2 = $db->prepare($used);
$result2->bindParam(":lk", $_POST['licensekey']);
$result2->execute();
echo "true";
} else {
echo "false";
}
$db = null;
} else {
exit();
}
?>
Every time it will return false no matter what.
What seems to be the issue here?
Actually you can't see how many records selected in DB with rowCount function. As i read in PHP Documentation many of select queries doesn't return how many rows affected by query with rowCount method. Check it for more information : http://php.net/manual/en/pdostatement.rowcount.php
As doc says you can use fetchColumn method.

How to escape during PDO query statement in php? [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
(Edit:Guys, Before jumping to any conclusions, I'm asking how do you escape a query variable from the Example#2 from php.net website. I tried lot of ways but they all gave me errors. If you can please read that Example and post your version of that exact Example#2. Also please read about why they have that example there.)
I was searching for a reliable 'row:count' method to use with PHP PDO across multiple database types, and came across below code from php.net
http://php.net/manual/en/pdostatement.rowcount.php (See Example:#2)
It says to do a row count to see if an entry exists in a database using a SELECT statement, the error proof method is to use PDO::query() instead of PDOStatement::fetchColumn().
My question is I know how to bind and execute with PDO, but I don't know how to assign a user submitted variable($username) to this $sql statement and escape it successfully?
Is it possible to bind parameters to this $sql mehod using PDO?
try{
$conn = new PDO($dsn, $db_username, $db_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->db = $conn;
} catch(PDOException $e){
echo 'Error:'.$e;
}
public function usernameExists($username){
//Check db for a match.
$sql = "SELECT * FROM users WHERE username = '".$username."'";
$results = $this->db->query($sql);
if($results->fetchColumn() > 0){
//Matching username found in the db
return true;
}else{
//No matching username in db
return false;
}
}
You're looking for bindValue. With it, you can use a placeholder when writing your query, then pass the user's input afterward.
For example:
public function usernameExists($username){
//$result = $this->db->query('SELECT * FROM users WHERE username = ');
//Check db for a match.
$sql = "SELECT * FROM users WHERE username = :username";
$s = $conn->prepare($sql);
$s->bindValue(':username',$username);
$s->execute();
$results = $s->fetchAll();
if(count($results) > 0){
//Matching username found in the db
return true;
}else{
//No matching username in db
return false;
}
For more info, see the PHP manual.
You're going to want to use a parameterized query like this:
<?php
$value = "whatever";
$stmt = $dbh->prepare("SELECT * FROM TABLE_NAME where column_name = ?");
if ($stmt->execute(array($value))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
?>
If you really wanted to quote+escape the string, then that's possible too. It even looks somewhat more legible with complex variable interpolation than your original string patching:
$sql = "SELECT * FROM users WHERE username = {$this->db->quote($username)}";
// ->quote itself adds ↑ 'quotes' around
Now of course: don't do that. Use a placeholder, and pass it per ->execute([$var]); instead. Strive for consistency.

PDO equivalent of mysql_num_rows or mssql_num_rows [duplicate]

This question already has answers here:
Row count with PDO
(21 answers)
Closed 2 years ago.
I know this question has been asked before but it seems like the solutions have been specific to the problem presented.
I have a codebase with hundreds of instances where mssql_num_rows is used.
Code example:
$db->execute($sql);
if ($db->getRowsAffected() > 0) {
$total = $db->fetch();
In db class:
$this->rowsaffected = mssql_num_rows($this->query_result);
I can't create generic SELECT count(*) FROM table queries as I have too many specific select statements.
I could run a preg_replace to remove everything between SELECT and FROM and then replace with a COUNT(*) and run a second query but this assumes all queries are setup a certain way.
I could fetchAll first then count() the results but that means upgrading all instances of the if statements.
So what is the best all around replacement to a *_num_rows function if people are updating their code to PDO. Not something that solves a specific problem, but something that replaces the functionality of *_num_rows. If that's not possible what allowed it to be possible before?
If you want to count the rows you can do this with PDO:
$sql = 'select * from users';
$data = $conn->query($sql);
$rows = $data->fetchAll();
$num_rows = count($rows);
There is no way to directly count rows when using a SELECT statement with PDO as stated in the docs.
PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
Only do a row count if you absolutely need the count, otherwise you can verify that the query worked with other methods. You should also not use this method if you expect to be returning thousands of rows from a table, instead, use the COUNT() function in a query for just performing the count.
So with everyone's help this is what I built.
function getRowsAffected() {
$rawStatement = explode(" ", $this->query);
$statement = strtoupper($rawStatement[0]);
if ($statement == 'SELECT' || $statement == 'SHOW') {
$countQuery = preg_replace('/(SELECT|SHOW)(.*)FROM/i', "SELECT count(*) FROM", $this->query);
$countsth = $this->pdo->prepare($countQuery);
if ($countsth->execute()) {
$this->rowsaffected = $countsth->fetchColumn();
} else {
$this->rowsaffected = 0;
}
}
return $this->rowsaffected;
}
$this->rowsaffected is already being updated in the execute phase if the statement is an INSERT, UPDATE, or DELETE with $sth->rowCount() so I only needed to run this second query on SELECT and SHOWS.
if ($statement == 'INSERT' || $statement == 'UPDATE' || $statement == 'DELETE') {
$this->rowsaffected = $this->sth->rowCount();
}
I feel bad though, because just as I mentioned in my question, that I was looking for an overall solution I seem to have stumbled onto a specific solution that works for me since the code already asks for the number of rows using a function. If the code was doing this:
if (mysql_num_rows($result) > 0) {
then this solution would still create work updating all instances to use that custom function.

MySQLI Prepared Statement: num_rows & fetch_assoc

Below is some poorly written and heavily misunderstood PHP code with no error checking. To be honest, I'm struggling a little getting my head around the maze of PHP->MySQLi functions! Could someone please provide an example of how one would use prepared statements to collect results in an associative array whilst also getting a row count from $stmt? The code below is what I'm playing around with. I think the bit that's throwing me off is using $stmt values after store_result and then trying to collect an assoc array, and I'm not too sure why...
$mysqli = mysqli_connect($config['host'], $config['user'], $config['pass'], $config['db']);
$stmt = $mysqli->prepare("SELECT * FROM licences WHERE generated = ?");
$stmt->bind_param('i', $core['id']);
$result = $stmt->execute();
$stmt->store_result();
if ($stmt->num_rows >= "1") {
while($data = $result->fetch_assoc()){
//Loop through results here $data[]
}
}else{
echo "0 records found";
}
I feel a little cheeky just asking for code, but its a working demonstration of my circumstances that I feel I need to finally understand what's actually going on. Thanks a million!
I searched for a long time but never found documentation needed to respond correctly, but I did my research.
$stmt->get_result() replace $stmt->store_result() for this purpose.
So, If we see
$stmt_result = $stmt->get_result();
var_dump($stmt_result);
we get
object(mysqli_result)[3]
public 'current_field' => int 0
public 'field_count' => int 10
public 'lengths' => null
public 'num_rows' => int 8 #That we need!
public 'type' => int 0
Therefore I propose the following generic solution. (I include the bug report I use)
#Prepare stmt or reports errors
($stmt = $mysqli->prepare($query)) or trigger_error($mysqli->error, E_USER_ERROR);
#Execute stmt or reports errors
$stmt->execute() or trigger_error($stmt->error, E_USER_ERROR);
#Save data or reports errors
($stmt_result = $stmt->get_result()) or trigger_error($stmt->error, E_USER_ERROR);
#Check if are rows in query
if ($stmt_result->num_rows>0) {
# Save in $row_data[] all columns of query
while($row_data = $stmt_result->fetch_assoc()) {
# Action to do
echo $row_data['my_db_column_name_or_ALIAS'];
}
} else {
# No data actions
echo 'No data here :(';
}
$stmt->close();
$result = $stmt->execute(); /* function returns a bool value */
reference : http://php.net/manual/en/mysqli-stmt.execute.php
so its just sufficient to write $stmt->execute(); for the query execution.
The basic idea is to follow the following sequence :
1. make a connection. (now while using sqli or PDO method you make connection and connect with database in a single step)
2. prepare the query template
3. bind the the parameters with the variable
4. (set the values for the variable if not set or if you wish to change the values) and then Execute your query.
5. Now fetch your data and do your work.
6. Close the connection.
/*STEP 1*/
$mysqli = mysqli_connect($servername,$usrname,$pswd,$dbname);
/*STEP 2*/
$stmt = $mysqli->prepare("SELECT * FROM licences WHERE generated = ?");
/*Prepares the SQL query, and returns a statement handle to be used for further operations on the statement.*/
//mysqli_prepare() returns a statement object(of class mysqli_stmt) or FALSE if an error occurred.
/* STEP 3*/
$stmt->bind_param('i', $core['id']);//Binds variables to a prepared statement as parameters
/* STEP 4*/
$result = $stmt->execute();//Executes a prepared Query
/* IF you wish to count the no. of rows only then you will require the following 2 lines */
$stmt->store_result();//Transfers a result set from a prepared statement
$count=$stmt->num_rows;
/*STEP 5*/
//The best way is to bind result, its easy and sleek
while($data = $stmt->fetch()) //use fetch() fetch_assoc() is not a member of mysqli_stmt class
{ //DO what you wish
//$data is an array, one can access the contents like $data['attributeName']
}
One must call mysqli_stmt_store_result() for (SELECT, SHOW, DESCRIBE, EXPLAIN), if one wants to buffer the complete result set by the client, so that the subsequent mysqli_stmt_fetch() call returns buffered data.
It is unnecessary to call mysqli_stmt_store_result() for other queries, but if you do, it will not harm or cause any notable performance in all cases.
--reference: php.net/manual/en/mysqli-stmt.store-result.php
and http://www.w3schools.com/php/php_mysql_prepared_statements.asp
One must look up the above reference who are facing issue regarding this,
My answer may not be perfect, people are welcome to improve my answer...
If you would like to collect mysqli results into an associative array in PHP you can use fetch_all() method. Of course before you try to fetch the rows, you need to get the result with get_result(). execute() does not return any useful values.
For example:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli($config['host'], $config['user'], $config['pass'], $config['db']);
$mysqli->set_charset('utf8mb4'); // Don't forget to set the charset!
$stmt = $mysqli->prepare("SELECT * FROM licences WHERE generated = ?");
$stmt->bind_param('i', $core['id']);
$stmt->execute(); // This doesn't return any useful value
$result = $stmt->get_result();
$data = $result->fetch_all(MYSQLI_ASSOC);
if ($data) {
foreach ($data as $row) {
//Loop through results here
}
} else {
echo "0 records found";
}
I am not sure why would you need num_rows, you can always use the array itself to check if there are any rows. An empty array is false-ish in PHP.
Your problem here is that to do a fetch->assoc(), you need to get first a result set from a prepared statement using:
http://php.net/manual/en/mysqli-stmt.get-result.php
And guess what: this function only works if you are using MySQL native driver, or "mysqlnd". If you are not using it, you'll get the "Fatal error" message.
You can try this using the mysqli_stmt function get_result() which you can use to fetch an associated array. Note get_result returns an object of type mysqli_result.
$stmt->execute();
$result = $stmt->get_result(); //$result is of type mysqli_result
$num_rows = $result->num_rows; //count number of rows in the result
// the '=' in the if statement is intentional, it will return true on success or false if it fails.
if ($result_array = $result->fetch_assoc(MYSQLI_ASSOC)) {
//loop through the result_array fetching rows.
// $ rows is an array populated with all the rows with an associative array with column names as the key
for($j=0;$j<$num_rows;$j++)
$rows[$j]=$result->fetch_row();
var_dump($rows);
}
else{
echo 'Failed to retrieve rows';
}

MySQL IN() to work with PDO query [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP PDO: Can I bind an array to an IN() condition?
I have only made websites with PHP and MySQL for a hobby, my whole life I've always used unprepared statements until I decided to try PDO queries last night. I've successfuly gotten them all to work except when I use IN(). For Example when i do this:
$stmt3 = $dbConnection->prepare("SELECT * FROM member_search WHERE zip IN(:zip_codes_in_distance)");
$stmt3->execute(array(':zip_codes_in_distance' => $zip_codes_in_distance ));
foreach ($stmt3 as $user_list) {
//do cool stuff here
}
This returns this error:
Syntax error or access violation: 1064
After googling it, I've tried with no success a few of the solutions like using query() instead of execute()
This only happens when I use IN()
the $zip_codes_in_distance are zipcodes in this format '07110', '07109', '07050'
What am I doing wrong?
Couldn't get this to work correctly using PDO, so I used MySQLi instead.
Establish Database Connection in a separate file:
$Connect = new mysqli($host, DB_Username, DB_password, DB_Name);
Ran the Query like this:
include 'DbConnectFIle.php';
$zips = "07110, 07109";
$sql = "SELECT * FROM table WHERE zip IN(".$zips.") ";
$result = $Connect->query($sql);
while($row = $result->fetch_assoc()){
$MemberName = $row['first_name'];
}
$Connect->close();
echo $MemberName;
Tried for four hours using PDO, MySQLi was the only way I could get it to work.
I used this tutorial: http://codular.com/php-mysqli

Categories