Reputation: 2533
I'm trying to check if the content of the variable $host exists in the ID column of my database. Afterwards I want it to assign the corresponding value to $exists, if the entry is in the database or not.
For some reason this part of my script is always returning the same result, regardless if $host is contained in the database or not. Please help :)
$query = mysqli_query($conn, "SELECT 'ID' FROM 'servers' WHERE 'ID' = '$host'");
if (empty($query)) {
$exists = "false";
}
else {
$exists = "true";
}
Upvotes: 0
Views: 6305
Reputation: 73241
This line
$query = mysqli_query($conn, "SELECT 'ID' FROM 'servers' WHERE 'ID' = '$host'");
needs to be like this:
$query = mysqli_query($conn, "SELECT `ID` FROM `servers` WHERE `ID` = '$host'");
Right now, you are selecting ID as a string, so you need to put table and column names in `` and you put strings (or variables containing strings in ' ' )
and then do
$count = $conn -> num_rows($query);
if ($count < 1 ) {
$exists = "false";
}
else
{
$exists = "true";
}
to actually check the number of rows containing $host
's value
Also, you should at least use
$host = mysqli_real_escape_string($conn, $host);
before using a variable in a query to avoid mysql injection, but better use prepared statements. There are some links in the comments to your question which will help you with that.
Sidenote:
Having used or die(mysqli_error($conn))
to mysqli_query()
would have signaled the error.
Upvotes: 3
Reputation:
$query = mysqli_query($conn, "SELECT ID FROM servers WHERE ID = '".$host."'");
if (empty($query)) {
$exists = "false";
}
else {
$exists = "true";
}
Upvotes: 1