【发布时间】: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。这也可以为您节省单引号问题。