MySQLi第二个查询不起作用

时间:2016-07-22 23:05:49

标签: php mysql mysqli

我试图在一个php页面内使用两次查询时遇到MySQLi和PHP的问题。问题是第一个查询工作完美但第二个查询不起作用。第一个查询设置会话,但第二个不设置。这是我的代码(我也连接到db文件,表单和其他文件)..

$connection = new mysqli($server,$username,$password,$database);

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

if($select1 = $connection->query("SELECT * FROM users WHERE username = '$username'")) {
    $counter1 = $select1->num_rows;
    if($counter1 != 0) {
        $_SESSION["accesserror"] = "Error: <em>That username is already used by other member.</em>";
    }
}
else if($select2 = $connection->query("SELECT * FROM users WHERE user_email = '$email'")) {
    $counter2 = $select2->num_rows;
    if($counter2 != 0) {
        $_SESSION["accesserror"] = "Eror: <em>That E-Mail is already used by other member.</em>";
    }
}

1 个答案:

答案 0 :(得分:0)

替换else if

else if($select2 = $connection->query("SELECT * ...

使用if

if($select2 = $connection->query("SELECT * ...

代码的问题在于,只要第一个查询成功运行,执行就永远不会进入else if(即使第一个查询没有返回结果,它仍然成功运行)。为了始终检查这两个条件,您需要将这两个条件分开if

PS:运行一个查询会更高效,您应该永远直接在查询中插入用户提供的值,例如$username;这是为了避免SQL注入。你的代码非常脆弱。这是一个更安全,更有效的版本:

$username = mysqli_escape_string($_POST['username']);
$email = mysqli_escape_string($_POST['email']);
$sql = "SELECT * FROM users WHERE username='$username' OR email='$email'";
if($select = $connection->query($sql) && $select->num_rows) {
    while($row = $select->fetch_assoc()){
        if($row['username']===$username){/* add the "username taken" error */}
        if($row['email']===$email){/*add the "email taken" error */}
    }
}elseif($select===false){
    //Todo: handle server error. probably a badly formed query
    //error details in $connection->error
}else{
    // OK to register
}