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 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器