Help | Site Map
Connecting Tech Pros Worldwide
 
 
LinkBack Thread Tools
  #1  
Old March 25th, 2008, 01:55 PM
Gilles Ganault
Guest
 
Posts: n/a
Default Finding if a record exists?

Hello

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

//1.
if(!$row['number'])
print "Not found";
else
print "Found";

//2.
if(count($row))
print "Found";
else
print "Not found";

//3.
if(!$row[0])
print "Not found";
else
print "Found";

$dbh = null;

Thank you.
  #2  
Old March 25th, 2008, 02:25 PM
Guillaume
Guest
 
Posts: n/a
Default Re: Finding if a record exists?

Gilles Ganault a écrit :
Quote:
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();
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.

Regards,

--
Guillaume
  #3  
Old March 25th, 2008, 06:45 PM
Gilles Ganault
Guest
 
Posts: n/a
Default Re: Finding if a record exists?

On Tue, 25 Mar 2008 14:14:58 +0100, Guillaume
<ggrason@NOSPAM.gmail.com.INVALIDwrote:
Quote:
>I would say:
>$numrows = $dbh->query($sql)->numrows();
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(*).

Thanks.
 

Bookmarks

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are Off
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over network members.
Post your question now . . .
It's fast and it's free

Popular Articles