未声明的变量mysqli

时间:2012-09-01 05:39:53

标签: php oop mysqli

我遇到了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);  

1 个答案:

答案 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);