Balderick Posted August 21, 2016 Share Posted August 21, 2016 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 More sharing options...
Ingolme Posted August 21, 2016 Share Posted August 21, 2016 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 More sharing options...
Balderick Posted August 21, 2016 Author Share Posted August 21, 2016 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 More sharing options...
justsomeguy Posted August 22, 2016 Share Posted August 22, 2016 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 More sharing options...
Ingolme Posted August 22, 2016 Share Posted August 22, 2016 Something I overlooked. Yes, $con must be passed into the function for it to work. Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now