Jump to content

query to check existance of a record


Balderick
 Share

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 ?

Link to comment
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();
}
Link to comment
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?

Link to comment
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.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...