Jump to content
Sign in to follow this  
Balderick

query to check existance of a record

Recommended Posts

How to find a record in a table?

 

I now use :

     $sql = "SELECT col1 FROM table WHERE col1 = '$var' " ;
     if ($stmt = $conn->prepare($sql)) {
 
 
    $stmt->execute();
    $stmt->bind_result($var);
    
    
    
    while ($stmt->fetch()) {
        
            echo $var;
            echo ' : this variable exists <br>';
        
       }



    $stmt->close();

     }

to fetch $var.

 

But this actually results in an echo of the input.

 

The goal is not necessarily echoing it, but determining whether it exists or not and report that its not existing

 

So is it possible with other query to determine if $var exists and then use that as TRUE ?

Share this post


Link to post
Share on other sites

This is a misuse of prepared statements, don't ever put a variable inside a query string.

 

This code will do what you're asking

// Returns true if it exists, false otherwise
function value_exists($var) {
  $stmt = $con->prepare('SELECT 1 FROM table WHERE col1 = ? LIMIT 1');
  $stme->execute(array($var));
  return !!$stmt->fetch();
}

Share this post


Link to post
Share on other sites

 

This is a misuse of prepared statements, don't ever put a variable inside a query string.

 

This code will do what you're asking

// Returns true if it exists, false otherwise
function value_exists($var) {
  $stmt = $con->prepare('SELECT 1 FROM table WHERE col1 = ? LIMIT 1');
  $stme->execute(array($var));
  return !!$stmt->fetch();
}

 

Hi Ingolme

 

I wondered how to use the part with ? and LIMT but couldnt find a solution.

 

But your solutions seems to be wrong to for me too. Are there errors in it you think?

Share this post


Link to post
Share on other sites

If you're using mysqli you can read about prepared statements here:

 

http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

 

If you're using PDO, they talk about it here:

 

http://php.net/manual/en/pdo.prepared-statements.php

 

The issue with the code above is that it's trying to use a variable ($con) that isn't defined. Ideally that variable should also be passed to the function.

Share this post


Link to post
Share on other sites

Something I overlooked. Yes, $con must be passed into the function for it to work.

Share this post


Link to post
Share on other sites

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.   Paste as plain text instead

  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.

Loading...
Sign in to follow this  

×
×
  • Create New...