简体   繁体   English

检查MySQL表中是否存在PHP变量

[英]Check if a PHP variable exists in a MySQL table

I'm trying to check if the content of the variable $host exists in the ID column of my database. 我正在尝试检查变量$ host的内容是否在数据库的ID列中。 Afterwards I want it to assign the corresponding value to $exists, if the entry is in the database or not. 之后,如果条目是否在数据库中,我希望它为$ exists分配相应的值。

For some reason this part of my script is always returning the same result, regardless if $host is contained in the database or not. 由于某种原因,无论$ host是否包含在数据库中,脚本的这一部分总是返回相同的结果。 Please help :) 请帮忙 :)

$query = mysqli_query($conn, "SELECT 'ID' FROM 'servers' WHERE 'ID' = '$host'");
if (empty($query)) {
        $exists = "false";
}
else {
        $exists = "true";
}

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 ' ' ) 现在,您正在选择ID作为字符串,因此需要将表名和列名放在``中,然后将字符串(或将包含字符串的变量放在''中)

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 实际检查包含$host值的行数

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. 在查询中使用变量以避免mysql注入之前,但最好使用准备好的语句。 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. 使用or die(mysqli_error($conn))mysqli_query()会表明错误。

$query = mysqli_query($conn, "SELECT ID FROM servers WHERE ID = '".$host."'");
if (empty($query)) {
        $exists = "false";
}
else {
        $exists = "true";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM