mysqli_query遇到问题,返回NULL,但该查询在phpmyadmin中有效

时间:2019-07-13 16:09:11

标签: php mysql

当用户从iOS应用发送“登录”命令时,我正试图从数据库中检索信息。 为了测试此功能,我将手动启动php页面(例如http://www.testdatabase.com/LoginFunctions.php)并以编程方式强制使用用户名。

问题是mysqli_query返回NULL值。如果我使用“ or die(mysql_error()”),则什么也不会发生。即使我使用mysqli_num_rows返回1,但是$ result仍然为空。 因此,当执行mysql_fetch_assoc时,程序崩溃而没有显示任何错误。 任何想法?谢谢

<?php
    // Create connection
    $con=mysqli_connect("localhost","super","super","testdb");

    // Check connection
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $action = "login";
    $username = "Peperoncino";
    $response = array();

    if ($action == "login")
    {
        $query = "SELECT psw AS pswrd,id FROM Activities WHERE nome = 'Peperoncino' LIMIT 1";

        if ($result = mysqli_query($con, $query))
        {
            $values = mysql_fetch_assoc($result);
            $password = $values['pswrd'];
            $response["password"] = $password;
            $response["message"] = "Get information from db";
        }
        else
        {
            echo "err";
        }

        echo json_encode($response);
    }

    // Close connections
    mysqli_close($con);
?>

1 个答案:

答案 0 :(得分:0)

您正在使用不建议使用的mysql_fetch函数。请使用新的函数

<?php
    // Create connection
    $con=mysqli_connect("localhost","super","super","testdb");

    // Check connection
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $action = "login";
    $username = "Peperoncino";
    $response = array();

    if ($action == "login")
    {
        $query = "SELECT psw AS pswrd,id FROM Activities WHERE nome = 'Peperoncino' LIMIT 1";

        if ($result = mysqli_query($con, $query))
        {
            $values = mysqli_fetch_assoc($result);
            $password = $values['pswrd'];
            $response["password"] = $password;
            $response["message"] = "Get information from db";
        }
        else
        {
            echo  mysqli_error($conn);  
        }

        echo json_encode($response);
    }

    // Close connections
    mysqli_close($con);
?>