这是我的相关代码:
<?php
require("common.php");
$userID = $_SESSION['user']['id'];
echo $userID;
if(!empty($_POST))
{
if(empty($_POST['bio']))
{
die("Please enter your Bio.");
}
if(empty($_POST['location']))
{
die("Please enter your location");
}
$query = 'UPDATE users
SET usertype = 1
WHERE id="$userID"';
$query_params = array(
':bio' => $_POST['bio'],
':location' => $_POST['location'],
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
// header("Location: myprofile.php");
}
?>
我正在尝试在提交表单时将字段用户类型更新为 1,其中 ID 与当前 session 的 ID 匹配,如变量 $userID 中设置的那样。当代码运行时,它没有提供任何错误,但在查询中使用 PHP 变量似乎不起作用,该字段没有更新。
我尝试了不同的引号,我可以在多个 if 语句中访问变量,但不能在查询中访问。另外,我为此使用 PDO。感谢您的帮助!
最佳答案
您在查询中使用了错误的引号。将它们更改为:
$query = "UPDATE users
SET usertype = 1
WHERE id='$userID'";
当您想将变量传递给字符串而不连接它时,使用引号。 MYSQL 需要撇号才能将值理解为字符串。
这就是您出错的地方:您在查询中使用了引号 "
。
由于您已经在使用 PDO,所以我认为仅将用户 ID 作为参数传递没有任何问题:
$query = 'UPDATE users
SET usertype = 1
WHERE id=:userid';
$query_params = array(
':bio' => $_POST['bio'], //I think you will need to add those
':location' => $_POST['location'], //parameters to the string or it will fail
':userid' => $userID
);
当然,您可以使用带有撇号的 PHP 字符串,但是您需要对 mysql 查询的撇号进行转义,并连接变量,如下所示:
$query = 'UPDATE users
SET usertype = 1
WHERE id=\''.$userID.'\'';
关于php - 如何在 SQL 查询中使用 session 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35305041/