0

I'm in the process of migrating from mySQL based php to PDO. I'm working an if statement. Basically, I want to query a value from the database and check if anything gets returned.

With mySQL I would have done this:

//Query the entered data to see if it matches 
$myQuery  = "SELECT * FROM $tbl_name WHERE myData ='$MyData'";
$myResult = mysql_query($myQuery);

// If statement
if( mysql_num_rows($myResult) >=1 ) {
$result .= "The data matched and SQL query was successful";
}

With PDO I have this so far, although it's not working yet:

//Query the entered data to see if it matches
$myQuery  = "SELECT myData FROM table_name WHERE myData = '$myData'";
$myResult = $db->single($myQuery);

// If statement
if($myResult == 1) {
$result .= "The data matched and PDO query was successful";
}

Although, from what I've seen you don't need to separate the query and the result with PDO and could combine both the query and result into a single statement.

7 Answers 7

1
$myQuery = $db->prepare("SELECT myData FROM table_name WHERE myData = ?");
$myQuery->execute(array($myData));
$myResult->rowCount($myQuery);

// If statement
if($myResult == 1) {
$result .= "The data matched and SQL query was successful";
}
Sign up to request clarification or add additional context in comments.

Comments

1

In PDO you would do it like this:

$data_exists = $dbh->prepare('SELECT 1 
                              FROM `table_name` 
                              WHERE `myData` = ?');

$data_exists->execute(array($myData));

if ($data_exists->rowCount() == 1) {
   $result .= 'The data matched and PDO query was successful';
}

Comments

1

To answer your question you could use PDO's function rowCount().

if ($myResult->rowCount() > 0) {
    $result .= 'The data matched and PDO query was successful'; 
}

But notice that your PDO query is not safe. It is still vulnerable for MySQL injection since you directly insert a variable into your query. Use PDO's function bindParam() or bindValue() instead.

Comments

1

Although, from what I've seen you don't need to separate the query and the result with PDO and could combine both the query and result into a single statement.

It does allow it the way you shouldn't use PDO anyway. but nevertheless, your single function is not PDO and I doubt it will allow you any num rows. But you don't need that number anyway.

So, to make things straight

  1. Your single() function ought to have support for prepared statements.
  2. Having result from this function, you need no num rows at all

Here it goes

public function single($myQuery, $params = NULL, $style = PDO::FETCH_ASSOC)
{
    $stmt = $this->pdo->prepare($myQuery);
    $stmt->execute($params);
    return $stmt->fetch($style);
}

$myQuery  = "SELECT myData FROM table_name WHERE myData = ?";
$myResult = $db->single($myQuery, [$myData]);
if($myResult) {
    $result .= "The data matched and PDO query was successful";
}

if you don't need the result itself, then you can shorten a bit

$myQuery  = "SELECT 1 FROM table_name WHERE myData = ?";
if($db->single($myQuery, [$myData])) {
    $result .= "The data matched and PDO query was successful";
}

Comments

0

Ok. Thank you everyone for your answers. After taking them into consideration and doing some testing, I'd like share some findings with you.

In regards to issue at hand, which is setting up an if statement when checking database values with PDO I've noticed the a few differences. This may be obvious to some of you, but for someone coming from mysql (like me) it's not.

After doing some testing I found that I couldn't query a string with PDO as you would with mysql. Furthermore, in mysql you are able to set the string value prior to querying it in the database.

From what I can see, PDO will only query and return arrays. So you can't simply insert a string value and check for it.

In regards my question, I found that using that:

  1. My querying PDO syntax was incorrect.

  2. When it was correct, I was only able to query an array which returns an array.

Anyway this is what i did:

// Get's the entire column called "ColumnName"
$getColumn = $db->column("SELECT columName FROM table_name ");

// Check if the returned array contains a string.
$myString = "matchThisString";
if (in_array($myString, $getColumn)) {
  echo "A Match was found";
}
else {
  echo "No match was found";
}

I would recommend reading the following:

http://www.php.net/manual/en/pdostatement.fetch.php

http://www.php.net/manual/en/language.types.boolean.php

http://www.php.net/manual/en/language.types.array.php

Comments

-1

All answers suggesting to use rowCount() are wrong, rowCount() returns a non zero value only in operations that Affect rows, not selected rows, or at least as sated in PHP manual: PDO::Statement it's not guarantied.

PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object. 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.

More Text From The Manual

Example #2 Counting rows returned by a SELECT statement

For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.

At least I know that I had tons of problems with it.

One other way is to use:

$rows = stmt->fetchAll(PDO::FETCH_ASSOC);

if (count($rows))
{
     //Do something here
}
else
{
     //Do something else here.
}

The above chunk of code is good if you expect small data sets returned. If we're talking about huge data sets, then you're better of executing 2 queries, one with a COUNT in it with the same conditions as your select statement and then the SELECT statement like this:

$sql = "SELECT COUNT(*) FROM $tbl_name WHERE myData ='$MyData";
$count = $db->query($sql)->fetch();

if ($count[0] > 0)
{
    $myQuery  = "SELECT * FROM $tbl_name WHERE myData ='$MyData'";
    //.... Continue your code here since now you know for sure that your 
    //query will return rows....
    //.....
}
else
{
    //handle the case that no data were returned.
}

The code chunks above are just for demonstration, so you can understand what and how to do. I can't guarantee that this is the best way to do it, it's just the way I do it. Cheers.

Also a better way to do your thing is to use Prepared Statements as someone or some suggested. That has nothing to do with the way you're gonna deal with your problem here, it's just a safer practice in general since prepared statements prevent SQL Injection if not completely then to a really good degree (not sure about it).

3 Comments

Not true at all. This is the de facto method I use to return a row count when using PDO with MySQL and it works 100% of the time.
You're arguing with the manual? Mkay, I just put my 5 cents out there... And apparently you didn't even read the complete answer... or went to the manual to see the same text there as well... The fact that it worked for you doesn't mean that it'll work for everyone. I've seen this problem in many questions already.
All it took was a bit of googling - Like this one: stackoverflow.com/questions/883365/row-count-with-pdo and this one stackoverflow.com/questions/6041886/…
-1

You can do something like this :

$sql = "SELECT * FROM animals";
$stmt = $dbh->query($sql);
$result_count = $stmt->fetch(PDO::FETCH_ASSOC);

if($result_count == 1) 
{
   $result .= "The data matched and PDO query was successful";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.