Reputation: 27
So I am new to php and I am trying to check if a mysql table contains a variable which is set when a user does a search. If the table contains the variable (it's a string) then I want to be able to do different things depending on its existence.
I should also note that I am a novice with php development!
This is what I have so far;
$db = new mysqli('IP', 'username', 'password', 'database');
$result = $db->query("SELECT * FROM tablename WHERE ColumnName = $searchVar");
if(empty($result)){
//No result Found
}else{
//Found result
}
Upvotes: 1
Views: 1969
Reputation: 23892
Okay so your current query failed because your SQL string wasn't in quotes. It also could have failed once inputted into quotes if your PHP string had a single quote in it. This is how SQL injections occur, user input should never be passed directly into a SQL query. To separate these tasks there are prepared/parameterized queries.
Here's code I think should work for you but this is untested, based off manuals.
$db = new mysqli('IP', 'username', 'password', 'database');
$stmt = $db->prepare('SELECT * FROM tablename WHERE ColumnName = ?');
$stmt->bind_param('s', $searchVar);
$stmt->execute();
if($stmt->num_rows > 0) {
echo 'there are results';
} else {
echo 'there are no results';
}
Link to thread on preventing injections: How can I prevent SQL injection in PHP?
Upvotes: 1
Reputation: 469
You need to place single quotes around $searchVar
in the query.
$result = $db->query("SELECT * FROM tablename WHERE ColumnName = '$searchVar'");
Then, you must fetch the results of the query.
$result = $result->fetch_row();
Upvotes: 1