简体   繁体   English

PHP-MySQLi预准备语句

[英]PHP - MySQLi Prepared Statements

$name = $_GET['user'];
if(isset($_GET['user']) && strlen($_GET['user'])>0) {
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db);
    $stmt = $mysqli->prepare("SELECT username FROM users WHERE username=?");
    $stmt->bind_param('s', $name);
    $stmt->execute();
    while($stmt->fetch()) {
        if($stmt->num_rows == 0) {
            header("Location: home?errormsg=notfound");
            exit();
        }
    }
    $stmt->store_result();
    $stmt->close();
}
$mysqli->close();

So, the above code checks if $_GET['name'] exists in the database, and if it doesn't, to redirect to home?errormsg=notfound but it redirects the usernames which exists in the database to the link 'home?errormsg=notfound' as well. 因此,上面的代码检查$ _GET ['name']是否存在于数据库中,如果不存在,则重定向到home?errormsg = notfound,但它将数据库中存在的用户名重定向到链接“ home”。 errormsg = notfound”。 Can you suggest a way to solve this problem? 您能提出解决此问题的方法吗?

You have to call $stmt->store_result() before $stmt->num_rows . 您必须在$stmt->num_rows之前调用$stmt->store_result()

And your $stmt->fetch() is not necessary, because you don't use the selected data. 而且您不需要$stmt->fetch() ,因为您不使用所选数据。

If you call store_result() after num_rows it won't work. 如果您在num_rows之后调用store_result() ,它将不起作用。

Part of comment from manual page : 手册页的部分评论:

If you do not use mysqli_stmt_store_result( ), and immediatley call this function after executing a prepared statement, this function will usually return 0 as it has no way to know how many rows are in the result set as the result set is not saved in memory yet. 如果您不使用mysqli_stmt_store_result(),并且在执行准备好的语句后立即调用此函数,则该函数通常将返回0,因为它无法知道结果集中有多少行,因为结果集未保存在内存中然而。

So your code should look like this: 因此,您的代码应如下所示:

$name = $_GET['user'];
if(isset($_GET['user']) && strlen($_GET['user'])>0) {
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db);
    $stmt = $mysqli->prepare("SELECT username FROM users WHERE username=?");
    $stmt->bind_param('s', $name);
    $stmt->execute();
    $stmt->store_result();
    if($stmt->num_rows == 0) {
        header("Location: home?errormsg=notfound");
        exit();
    }
    $stmt->close();
}
$mysqli->close();

I have not tried this but maybe it helps. 我没有尝试过,但也许有帮助。

You are calling $stmt->store_result(); 您正在调用$stmt->store_result(); after $stmt->num_rows $stmt->num_rows
Please try moving $stmt->store_result(); 请尝试移动$stmt->store_result(); before $stmt->num_rows $stmt->num_rows之前

Example. 例。 you can see here 你可以在这里看到

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM