我已经搜索了,但没有,我找到了帮助我的代码:
function getData($con, $table) {
$stmt = $con->query('SELECT * FROM ' . $table);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
function getDataByUsername($con, $table, $username) {
$stmt = $con->query('SELECT * FROM ' . $table . ' WHERE `username` = "' . $username . '";');
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
getData函数工作正常,但是当我使用getDataByUsername时出现此错误:
Fatal error: Call to a member function fetchAll() on a non-object in /home/moe/www/status/inc/functions.php on line 12
第12行就是这个:
return $stmt->fetchAll(PDO::FETCH_ASSOC);
感谢您的帮助,moro
答案 0 :(得分:1)
因为它是pdo,为什么不绑定变量?
function getDataByUsername($con, $table, $username) {
$stmt = $con->prepare('SELECT * FROM ' . $table . ' WHERE `username` = ?');
$stmt->execute( array($username) );
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
答案 1 :(得分:0)
更改
$con->query('SELECT * FROM ' . $table . ' WHERE `username` = "' . $username . '";');
要
$con->query("SELECT * FROM `" . $table . "` WHERE `username` = `" . $username . `";");
额外字符称为" tick",可以在TAB键上方找到。
更好:
$con->query("SELECT * FROM {$table} WHERE `username` = {$username};");
没有最后测试,但你可以用这种方式内联变量。
当然要记住@Jon的言论。
答案 2 :(得分:-2)
喜欢:
$stmt = $con->query('SELECT * FROM ' . $table . ' WHERE `username` = "' . $username . '"');