Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/256.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何对类似的值执行简单的mysqli查询?_Php_Mysqli - Fatal编程技术网

Php 如何对类似的值执行简单的mysqli查询?

Php 如何对类似的值执行简单的mysqli查询?,php,mysqli,Php,Mysqli,我只是在寻找一个基本的查询,使用mysqli来搜索表中的特定值。例如如果表中存在“a”,则回显“已存在”。 请帮助我,因为我仍在学习如何摆脱不推荐的代码 $mysqli = new mysqli('localhost', 'root', 'pass', 'agents'); $result = $mysqli->query('select * from project'); if ($result) { $check = array(); while ($row = $r

我只是在寻找一个基本的查询,使用mysqli来搜索表中的特定值。例如如果表中存在“a”,则回显“已存在”。 请帮助我,因为我仍在学习如何摆脱不推荐的代码

$mysqli = new mysqli('localhost', 'root', 'pass', 'agents');
$result = $mysqli->query('select * from project');
if ($result) 
{
    $check = array();
    while ($row = $result->fetch_assoc()) 
    {
       $check[] = $row['projectname'];
    }
}
$a = 'a';
if ($a = $check) 
{
    echo "<script type='text/jscript'>
        alert('already exists.')
        </script>";
}

数据库旨在使用WHERE子句为您进行搜索。当您可以让数据库为您执行操作时,就不需要读取整个表

$result = $mysqli->query("SELECT COUNT(*) AS found FROM project WHERE projectname = '$a'");
$row = $result->fetch_assoc();
if ($row['found'] > 0) {
    echo "<script type='text/jscript'>alert('already exists.')</script>";
}

代码中有一个逻辑错误。您尝试将数组$check与字符串$a进行比较。试着这样做:

$mysqli = new mysqli('localhost', 'root', 'pass', 'agents');

$result = $mysqli->query('select * from project');
if ($result) {
    $check = array();
    while ($row = $result->fetch_assoc()) {
        $projectname = $row['projectname'];
        if($projectname == 'a')
        {
            echo "<script type='text/jscript'>alert('already exists.')</script>";
            break;
        }
        $check[] = $row['projectname'];
    } 
    print_r($check);
}
else
{
    echo "<script type='text/jscript'>alert('mysqli error')</script>";
}
此代码将检查表中的每个projectname,并在projectname='a'存在时显示警报


另外,如果您想以非常好的方式与数据库联系,请阅读关于PDO驱动程序的内容

为什么不使用where子句??使用ifin_数组$a,$check['column name']
$mysqli = new mysqli('localhost', 'root', 'pass', 'agents');

$result = $mysqli->query('select * from project');
if ($result) {
    $check = array();
    while ($row = $result->fetch_assoc()) {
        $projectname = $row['projectname'];
        if($projectname == 'a')
        {
            echo "<script type='text/jscript'>alert('already exists.')</script>";
            break;
        }
        $check[] = $row['projectname'];
    } 
    print_r($check);
}
else
{
    echo "<script type='text/jscript'>alert('mysqli error')</script>";
}