Jump to content

help: checking before doing query in php with mysql


don11

Recommended Posts

Hello,

I have a problem. I run this query:

$query = "SELECT column1 FROM table WHERE column2='$kk'"; $which = $link1; 
mysql_query($query,$which);
some codes....

It is displaying all data correct but  only when $kk exists in column2 and when $kk does not exist, it display blank page.

So, i want to do a check before running above query to make sure that $kk exists in column2. How to check it before running query?

Link to comment
Share on other sites

You can't check without executing the query. The problem is likely that your not checking the results.

 

$query = "SELECT column1 FROM table WHERE column2='$kk'"; $which = $link1; 
if ($result = mysql_query($query)) {
  if (mysql_num_rows($result)) {
    // it is safe to use $result as it contains data
  } else {
    // no result where found
  }
} else {
  // query failed.
}

 

This is the basic syntax for ALL select queries.

Link to comment
Share on other sites

...

This is the basic syntax for ALL select queries.

That's a bit of a strong statement, perticularly with the capitalisation of ALL.  I dissagree, partly:

The first if is not, in my opinion, the best way of handeling an execution error - use of a try would, I think, be better.

Personal prefference on my part sees that I never nest variables within an SQL string, but break the string and add the variable with dot connectors.  Just because I have come across a fair few occasions whre people (myself included at the start) have tried to nest a variable within a single quoted string.

oh yeah....and I personaly have never build a query with "$which = $link1;" in it  :P .

 

Good template though - could be well worth starting a sticky with simple templates like this in it for a quick refference (though you may have to restrict posting in it to admins/mods so tubes like me don't ruin it :) )

 

 

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.