Jump to content

How to check to see if something exists, if not do this


msaz87

Recommended Posts

Hey All,

 

Just a quick question... I'm looking to complete an if/then statement in PHP by checking to see if there's an entry in a DB table.

 

Basically, I'm wondering how to go about making a query that says:

 

$query = " SELECT * FROM table WHERE col = '$whatimlookingfor' ";

 

So if there is no column in that table matching the variable, it would make $truefalse = '0', which could then be used later in the PHP if/then...

 

Hopefully that makes sense... any help or guidance is appreciated. Thanks!

Link to comment
Share on other sites

I do. You now may deduce I have a civilised QWERTY keyboard as opposed to barbaric QWERTZ or esoteric Dvorak layout. ;)

 

Fortunately PHP manual's search yields quite good results in this case.

 

I was able to deduce as much... this looks like it'll work perfectly -- thanks very much for all your help!

Link to comment
Share on other sites

Don't use that query to see if something exists and don't use the mysql_num_rows() method.

 

The query you've presented will return the data in all of the rows.  Let's say your average record is 500 bytes.

 

Now let's say your database contains 1,000 records that meet the criteria.  You'll be returning all 1,000 records at 500 bytes per record.

 

1) This is making the database do way more work than it has to.

2) Your sending excessive data through the connection between your application and the database (500,000 bytes in my example).

 

Use something like this:

 

<?php
$escaped_variable = mysql_real_escape_string( $_POST['some_input'] );
$count_stmt = "
    SELECT COUNT(*) AS `n`
    FROM `yourtable`
    WHERE `thecol`={$escaped_variable}
    ";

$q_handle = mysql_query( $count_stmt );
$count = 0;
if( $q_handle ) {
    $count_row = mysql_fetch_object( $q_handle );
    if( $count_row ) {
        $count = $count_row->n;
    }
}
echo "There are {$count} records matching the criteria.";
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.