Php 无法将字符串发送到插入查询中

Php 无法将字符串发送到插入查询中,php,mysql,sql,json,Php,Mysql,Sql,Json,我有json作为输入 $page = file_get_contents('http://example.com/products.html'); $items = json_decode($page, true); 如果我把echo$放在页面上;我得到的信息是这样的 { "productlist":[ { "id":"1", "cat":"milk", "prod_name":"happy milk", "img_url":"http://example.com/milk.jpg"}, {

我有json作为输入

$page = file_get_contents('http://example.com/products.html');
$items = json_decode($page, true);
如果我把echo$放在页面上;我得到的信息是这样的

{
"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数据库中

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());
}
我用DB填充了表格-我有两行产品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 

有人知道如何通过变量将字符串值发送到insert查询中吗?

这不起作用,因为
cat
是一个
string
字段,需要在引号之间
“…”
。试试这个:

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());

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

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

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


mysqli\u查询($link,“插入表(id,cat)值($id,.mysql\u real\u escape\u string($cat)。”)或死(mysql\u error())

由于您已经使用了MySQLi,所以可以使用准备好的语句来抵御可能的SQL注入攻击。这也将为您节省单报价问题。