如何返回mysqli_query的结果,以便我可以在另一个函数中使用它? [重复]

时间:2021-07-14 15:44:49

This question already has an answer here:

这个问题在这里已有答案:

I am trying to return the user's id number from the database but I can't figure out how to return the result of the query. I used to use mysql_result() so what would I need to do now that I'm using mysqli?

我试图从数据库返回用户的ID号,但我无法弄清楚如何返回查询的结果。我以前使用mysql_result()所以我现在需要做什么才能使用mysqli?

function user_id_from_username($username){
$query = mysqli_query($conn, "SELECT `user_id` FROM `users` WHERE `username` = '$username'");

return (what?);
}

2 个解决方案

#1


0  

check this http://php.net/manual/en/mysqli.query.php for myqli_query usage. and this http://www.php.net/manual/en/class.mysqli-result.php on how to get the values from the result.

检查此http://php.net/manual/en/mysqli.query.php以获取myqli_query用法。以及http://www.php.net/manual/en/class.mysqli-result.php关于如何从结果中获取值。

#2


0  

You haven't reaped one of the main benefits of moving from mysql to mysqli, which is using prepared statements to parameterize your queries and protect yourself from injection.

你还没有从mysql迁移到mysqli的主要好处之一,mysqli使用预准备语句来参数化你的查询并保护自己不被注入。

$query = mysqli_prepare($conn, "SELECT user_id FROM `users` WHERE username = ?");
mysqli_stmt_bind_param($query, "s", $username);
mysqli_stmt_execute($query);
mysqli_stmt_bind_result($query, $userid);
mysqli_stmt_fetch($query);
//$userid is now user_id

#1


0  

check this http://php.net/manual/en/mysqli.query.php for myqli_query usage. and this http://www.php.net/manual/en/class.mysqli-result.php on how to get the values from the result.

检查此http://php.net/manual/en/mysqli.query.php以获取myqli_query用法。以及http://www.php.net/manual/en/class.mysqli-result.php关于如何从结果中获取值。

#2


0  

You haven't reaped one of the main benefits of moving from mysql to mysqli, which is using prepared statements to parameterize your queries and protect yourself from injection.

你还没有从mysql迁移到mysqli的主要好处之一,mysqli使用预准备语句来参数化你的查询并保护自己不被注入。

$query = mysqli_prepare($conn, "SELECT user_id FROM `users` WHERE username = ?");
mysqli_stmt_bind_param($query, "s", $username);
mysqli_stmt_execute($query);
mysqli_stmt_bind_result($query, $userid);
mysqli_stmt_fetch($query);
//$userid is now user_id