如何在SQL查询中使用会话变量?

康纳·麦克劳德

这是我的相关代码:

<?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与当前会话的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.'\'';

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章