【问题标题】:Same mysqli query but different result while using with php与 php 一起使用时,相同的 mysqli 查询但结果不同
【发布时间】:2015-10-31 03:16:44
【问题描述】:

我有两个 php 脚本来访问我的数据库表中的数据。

index.php

<?php
require "init.php";
$name = "Jack";
$user_query = "SELECT * FROM employee WHERE employeeName like '$name';";
$result = mysqli_query($con,$user_query);

$data = array();

$no_of_rows = mysqli_num_rows($result);


if($no_of_rows > 0)
{
    $data["error"] = TRUE;
    $data["message"] = "User Found";
    echo json_encode($data);
}

else
{
    $data["error"] = FALSE;
    $data["message"] = "User Not Found";
    echo json_encode($data);

}
?>

如果我回显$no_of_rows,我会得到1,这是正确的,因为我只有一行对应于名字Jack。

这是从同一个表中访问相同数据的另一种方法:

test.php

<?php

require "userTester.php";
$name = "Jack";


$mUser = new UserCheck();

$testResult = $mUser -> userPresent($name);

$data = array();

if($testResult == true)
{
    $data["error"] = TRUE;
    $data["message"] = "User Found";
    echo json_encode($data);
}

else
{
    $data["error"] = FALSE;
    $data["message"] = "User Not Found";
    echo json_encode($data);
}

?>

userTester.php

<?php
require "init.php";

class UserCheck
{

    function userPresent($name)
    {
        echo "Name = " .$name;
        $my_query = "SELECT * FROM employee WHERE employeeName like '$name';";
        $result = mysqli_query($con,$my_query);

        echo json_encode($result);

        $num_of_rows = mysqli_num_rows($result);

        echo "Rows = " .$num_of_rows;

        if($num_of_rows > 0)
        {
            return true;
        }

        else
        {
            return false;
        }

    }

}
?>

在这种情况下,$num_of_rows 始终返回 0。实际上sql查询输出始终为null。

我在这两种情况下都使用相同的数据库表。我不明白怎么了。

注意:-init.php 用于建立与数据库的连接,它工作正常。

【问题讨论】:

  • 高度高度 HIGHLY 建议不要使用字符串连接创建 SQL 查询。稍后您将面临各种 SQL 注入问题。改为创建参数化查询。
  • 你不需要在那里使用LIKE= 可以。 LIKE(通常)表现更差。
  • 当您期望 0 到多个结果时,您使用 LIKE。我还希望看到某种通配符,即LIKE 'Jack%',它将找到Jack BlackJack the Ripper。如果您知道要查找的列是唯一的,请使用 = 而不是 like
  • @RiggsFolly :- 感谢您的评论 .. 但我不明白为什么它在第一种情况下运行而不是在第二种方法中运行!!!
  • 嗯,这取决于你没有向我们展示的很多东西。此外,如果您为 eack mysql 命令添加一些错误检查代码,您可能会在错误时发现一段代码中的某些内容,但您没有检查它

标签: php mysql mysqli


【解决方案1】:

您未能在方法中传递 $con 变量。

您必须更改方法签名以同时传入名称变量和连接变量。

您没有得到任何结果,因为它没有数据库连接。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-28
    • 1970-01-01
    • 2023-03-15
    • 2015-01-01
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    • 2019-07-25
    相关资源
    最近更新 更多