【问题标题】:cannot send the string into INSERT query无法将字符串发送到 INSERT 查询
【发布时间】:2013-10-12 11:44:40
【问题描述】:

我有 json 作为输入

$page = file_get_contents('http://example.com/products.html');
$items = json_decode($page, true);

如果我把 echo $page;我就是这样的

{
"productlist":[
{
"id":"1",
"cat":"milk",
"prod_name":"happy milk",
"img_url":"http://example.com/milk.jpg"},
{
"id":"2",
"cat":"bread",
"prod_name":"black bread",
"img_url":"http://example.com/bread.jpg"},

然后,我想把它放到 MySQL DB 中

foreach($items['productlist'] as $item) {
$id = $item['id'];
$cat = $item['cat'];
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, $cat)")  or die(mysql_error());
}

在这个阶段我什么也得不到。如果我将代码修改为

foreach($items['productlist'] as $item) {
$id = $item['id'];
mysqli_query($link, "INSERT INTO table (id) VALUES ($id)")  or die(mysql_error());
}

我在数据库中填满了表格 - 我有两行带有产品 ID。好的,我想在表中插入 $cat = food

foreach($items['productlist'] as $item) {
$id = $item['id'];
$cat = 'food';
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, $cat)")  or die(mysql_error());
}

但这不起作用,我得到空结果。但是如果我将查询修改为

foreach($items['productlist'] as $item) {
$id = $item['id'];
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, 'food')")  or die(mysql_error());
}

我得到了我寻找的结果 - 表中的行,填充了 id 和 cat

id   cat
1    food
2    food 

有谁知道如何通过变量将字符串值发送到插入查询中?

【问题讨论】:

  • 您可以使用准备好的语句来应对可能的 SQL 注入攻击,因为您已经使用了 MySQLi。这也可以为您节省单引号问题。

标签: php mysql sql json


【解决方案1】:

这不起作用,因为catString 字段,需要在引号'...' 之间。试试这个:

mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, '$cat')")  or die(mysql_error());

或者这个:

mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, ".$cat.")")  or die(mysql_error());

【讨论】:

    【解决方案2】:

    首先,我建议您学习如何使用准备好的语句,因为您在代码之外获取字符串(它可能包含一些 mysql 注入)。

    要回答您的问题,您需要在要放入查询的变量周围加上引号,因为它是一个字符串,以便 mysql 可以正确解释它

    mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, '$cat')")  or die(mysql_error());
    

    【讨论】:

      【解决方案3】:

      试试这个

      mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, ".mysql_real_escape_string($cat).")") or die(mysql_error());

      【讨论】:

        猜你喜欢
        • 2018-12-22
        • 2014-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多