session_start();
$username = $_SESSION['username'];
$db = new PDO("mysql:host=".DBHOST.";charset=utf8mb4;dbname=".DBNAME,
DBUSER, DBPASS);
function keygrabber($username) { //You need to pass a variable into this
function
global $db; //Gain access to the $db variable, which is out of scope due to
being inside of a function
$stmt = $db->prepare("SELECT * FROM keys WHERE username='$username'");
//Prepare the query
$stmt->execute(); //Execute the query
$results = $stmt->fetchAll(PDO::FETCH_ASSOC); //Fetch the query results
var_dump($results); //Dump the results
}
keygrabber($username);
因此,如果我将username='$username';
更改为username='myactualusername';
,则它可以工作,即没有任何错误或其他任何显示。
我基本上是在尝试从与用户名匹配的键中获取所有数据。将来我会将其更改为userID,但现在变量不起作用,因此无法进行升级。
感谢您的帮助
答案 0 :(得分:4)
尝试这样
$stmt = $db->prepare("SELECT * FROM keys WHERE username='$username'");
希望这是有道理的。
答案 1 :(得分:1)
您不应在SQL中使用php var(可能会出现sqlinjection风险),而应使用准备好的语句和参数绑定
确保$ username包含有效值,然后
$stmt = $db->prepare("SELECT * FROM keys WHERE username=:username");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->execute();
答案 2 :(得分:0)
尝试一下
prepare(“ SELECT * FROM keys WHERE username =?”);
$ stmt-> execute([$ username]);
$ rows = $ stmt-> fetchAll();