我遇到了mysqli和预备语句的问题。我刚刚开始学习mysqli一小时,我很难理解为什么我会收到这两个错误:
Notice: Undefined variable: mysqli in /opt/lampp/htdocs/lr/testingi.php on line 17
Fatal error: Call to a member function prepare() on a non-object in /opt/lampp/htdocs
/lr/testingi.php on line 17
我有一个包含数据库连接的文件。在这里。
$mysqli = new mysqli("localhost", "user", "password", "db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
这是重现错误的测试文件。
session_start();
require_once 'core/database/connect.php';
function user_id_from_username ($username) {
if ($stmt = $mysqli->prepare("SELECT `user_id` FROM `users` WHERE `username` = ?"))
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($user_id);
echo $user_id;
$stmt->close();
}
$username = 'Jason';
user_id_from_username ($username);
答案 0 :(得分:4)
您似乎没有将$mysqli
传递给user_id_from_username
函数。
2个快速选项:
<强> 1。全球
function user_id_from_username ($username) {
global $mysqli;
if ($stmt = $mysqli->prepare("SELECT `user_id` FROM `users` WHERE `username` = ?"))
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($user_id);
echo $user_id;
$stmt->close();
}
<强> 2。第二个参数
function user_id_from_username ($mysqli, $username) {//..}
user_id_from_username($mysqli, $username);