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 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?