dongzhashou0116 2017-07-07 06:09
浏览 93
已采纳

如何使用php变量在MySQL查询的WHERE条件中使用变量? [重复]

This question already has an answer here:

I'm using PHP session variable to track character ID's between two tables, characters and character_data_store.

The session ID definitely has the correct ID as I have had to print its value before it goes into the mySQL query.

For testing I selected a user I knew had a rapsheet and used

$usersql = "SELECT * 
 FROM character_data_store 
 WHERE character_data_store.`key` = 'RapSheet' 
 AND character_data_store.character_id = '216'";

Obviously I can't use this for all users as I need to confirm the right one has been selected so thats where the session variable comes in.

I've tried using:

$correctPlayer = $_SESSION['selpid'];
echo $correctPlayer; #confirm it's the right id and then remove

$usersql = "SELECT * 
  FROM character_data_store 
  WHERE character_data_store.'key' = 'RapSheet' 
  AND character_data_store.character_id = '$correctPlayer'";

I did some searching on SO and I found that int's need to have double quotes around them not single quotes, I tried that and had no luck but someone else suggested putting the session ID in exactly which I tried next:

$usersql = "SELECT * 
  FROM character_data_store 
  WHERE character_data_store.'key' = 'RapSheet' 
  AND character_data_store.character_id = {$_SESSION['selpid']}";

Each time I do this I get mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given which SO tells me is because this operation results to false, I assume because it's not accepting the playerID from selpid or $correctPlayer?

It definitely works with the testing user where the playerID is inserted directly into the query. But I can't think of a way to do that since I need to match the playerID from table "characters" where the search is done against their first and last name and then pull the rapsheet data against the same playerID in table "character_data_store".

How do I use a variable in the WHERE condition of a MySQL query using a php variable?

</div>
  • 写回答

2条回答 默认 最新

  • drh37116 2017-07-07 07:41
    关注

    You have obvious error in your code. You are missing quotes in {$_SESSION['selpid']} and you are using quotes in column name. Your query should be

    $usersql = "SELECT * FROM character_data_store WHERE character_data_store.`key` = 'RapSheet' AND character_data_store.character_id = '{$_SESSION['selpid']}'";
    

    You should not use quotes in column name, instead use backquotes(`) if you really need. I recommend prepared statements.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题