无法从sql数据库获得结果

时间:2016-10-04 00:57:52

标签: php mysql

我是php的新手,我正在尝试创建一个登录系统。这是我的代码

<?php

    $con=mysqli_connect("XXXXXXX","XXXXXXXX","XXXXXXXXX","XXXXXXXXXX");

    if (!$con)
        {
        echo "failed to connect";
        }

    $username = $_POST['username'];
    $password = $_POST['password'];

    $sql = "SELECT userID FROM users WHERE username = $username and password =          $password;";

    if (!$sql) {
        echo 'query invalid'.mysql_error();
        }

    $result = mysql_query($sql);

    echo "$result";

    $row = mysqli_fetch_array($sql, MYSQLI_ASSOC);

    $active = $row['active'];

    $count = mysqli_num_rows($result);

    mysql_close($con);

?>

我确信连接没有问题。但是我的结果没有显示,也没有错误信息。以前我有一个IF语句,如果结果返回,它会执行进一步的操作。由于我想弄清楚发生了什么,我只是删除了那一部分。有人请帮忙。非常感谢

2 个答案:

答案 0 :(得分:1)

你错过了变量周围的单引号,而且你还在使用与mysqli混合的mysql,这将无效。

$sql = "SELECT userID FROM users WHERE username = '$username' and password = '$password';";
$result = mysqli_query($con, $sql);

$row = mysqli_fetch_assoc($sql); // same as fetch_array with MYSQLI_ASSOC

$active = $row['active'];

$count = mysqli_num_rows($result);

最后你不需要mysql_close,但如果你想使用它,那就mysqli_close($con); 请记住,这是不安全的。

使用此功能过滤用户输入:

$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);

Read this以确保您的代码符合安全标准。

答案 1 :(得分:0)

我推荐这个。

$sql = "SELECT userID FROM users 
WHERE username = " ._sql($username) ." and password = " ._sql($password);

// generate sql safe string function 

function _sql($txt) { 
    if ($txt === null || $txt === "") 
      return "NULL"; 
    if (substr($txt, 0, 2) == "##") 
      return substr($txt, 2); 
    //$txt = str_replace("'", "''", $txt); 
    $txt = mysql_real_escape_string($txt); 
    return "'" . $txt . "'"; 
}