Finding if a record exists?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

    I need to check if a phone number exists in a database. Using the
following SQL statement, what is the right way to code this in PHP?

$dbh = new PDO("sqlite:test.sqlite");
$sql = "SELECT 1 AS number FROM phones WHERE phones_tel='123'";
$row = $dbh->query($sql)->fetch();

    print "Not found";
    print "Found";

    print "Found";
    print "Not found";

    print "Not found";
    print "Found";

$dbh = null;

Thank you.

Re: Finding if a record exists?

Gilles Ganault a écrit :
Quoted text here. Click to load it

I would say:
$numrows = $dbh->query($sql)->numrows();
I suppose numrows exists as well as fetch, then it should be lighter not
to fetch the data but only ask how many were returned.
Then, $numrows is either a PDO error or an integer which you can check.



Re: Finding if a record exists?

On Tue, 25 Mar 2008 14:14:58 +0100, Guillaume
Quoted text here. Click to load it

Thanks for the tip, but numrows() doesn't exist in PDO, and roCount()
isn't reliable when used with SELECT:

"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."

So I guess the right way is to use "SELECT count(*).


Site Timeline