doumi4676 2013-11-08 23:30
浏览 37
已采纳

PHP中mysql查询字符串的奇怪行为

I'm toying around with mysql and PHP and hit a VERY strange problem:

After establishing a successful database connection I set two variables for the query:

$searchcolor = $_SESSION["color"];
$searchprice = $_POST["price"];

$query = "SELECT `toys`.`id` FROM `database`.`toys` WHERE `toys`.`color` = $searchcolor AND `toys`.`price` = $searchprice;";
$result = mysqli_query($link, $query);

echo $query;

This querys won't work. When echoing it, it reads the correct string, like:

SELECT `toys`.`id` FROM `database`.`toys` WHERE `toys`.`color` = brown AND `toys`.`price` = 1500;

This code, however, works just fine:

$searchcolor = $_SESSION["color"];
$searchprice = $_POST["price"];

$query = "SELECT `toys`.`id` FROM `database`.`toys` WHERE `toys`.`color` = $searchcolor AND `toys`.`price` = 1500;";
$result = mysqli_query($link, $query);

echo $query;

First I though the $searchprice wasn't getting it's content by the $_POST array correctly. But the echoed search query in the first example seems to be fine.

It also works when setting $searchprice = 1500; instead of getting the $_POST-value.

I tried casting it to integer and stuff, but that didn't worked.

Cheers and thanks for every hint on this!

(The code is shortened!)

Table structure of toys:

id int(10)
name varchar(10)
color varchar(10)
price int(20)

Edit:

Woah, just made an interesting discovery:

echo "-".$searchprice."-";

Gives -5-

if ($searchprice == 5){echo "1";}
if ($searchprice == "5"){echo "2";}

Gives.. nothing?!

var_dump($searchprice);

Gives string(14) "5"

Edit:

echo bin2hex($searchprice);

Gives 3c6e6f62723e353c2f6e6f62723e (?!)

Solution: I used a unicode character in the submitting form. That broke everything. Lesson: Avoid unicode.

  • 写回答

1条回答 默认 最新

  • douli2063 2013-11-08 23:37
    关注

    First of all you should read this: How can I prevent SQL injection in PHP?

    Try this:

    $q = mysqli_prepare($link, 'SELECT toys.id FROM toys WHERE toys.color = ? AND toys.price = ?');
    
    mysqli_stmt_bind_param($q, 'si', $searchcolor, $searchprice); //d for double
    
    $searchcolor = $_SESSION['color'];
    $searchprice = $_POST['price'];
    
    mysqli_stmt_execute($q);
    

    Before that you should connect properly with DB. I see that you used database in FROM.

    $link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么