我有一个使用的功能:
require_once("connect.php");
function get_username($uid){
$stmt = $pdo->prepare("SELECT username FROM users WHERE uid= ?");
try {
$stmt->execute(array($uid));
} catch (PDOException $e) {
echo $e -> getMessage(); exit;
}
$row = $stmt->fetch();
return($row['username']);
}
$id = 1;
echo get_username($id);
但它说:
Call to a member function prepare() on a non-object
我有点困惑这意味着我错了,我想知道是不是因为我在函数中使用它?
编辑:
我的连接脚本¬
$dsn = 'mysql:dbname=test_db;host=127.0.0.1';
$user = 'test_user';
$password = 'test_pass';
try {
$pdo = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
error_reporting(E_ALL);
session_start();