我有一个转换为JSON的html表,并通过AJAX发送给PHP。 我已经解码了JSON对象,现在有一个PHP数组。 我想将这个数组或其内容插入到MySQL数据库中。
我对一些方法感到困惑。 什么是防止SQL注入的理想方法? 我看到一些看起来像这样的方法;
foreach ($array as $key => $value)
{
$price = $array["price"][$key];
...................................
}
这似乎不起作用,或者至少我不能让php打印或回显$ price是什么。
我试过这个:
foreach ($array as $key => $value)
{
$price = $value["price"];
...................................
}
我可以使用echo或print_r来显示值。
第一个问题是:在将这些值插入MySQ方面,$ key的目的是什么? 第二个是:为什么第一个没有返回预期结果,就像第二个代码片段那样? echo应显示$ price的值? 最后,假设两种方法都有效,这样的插入语句对于实际将数据推送到MySQL是正确的吗?
$sql = mysql_query("insert into Daily_Requests values ('','$price','$item','$etc...','$etc....')");
此致
修改
这是我的JSON:
[{"Price":"5000","Manufacturer":"Newton","Model":"84x26x10 43u","Model_info":"Newton 84x26x10 43u","Type":"Rack","Height_in":"83.97637795","Height_mm":"2133","Width_in":"25.98425197","Width_mm":"660","Description":"Newton 84x26x10 43u","Depth_in":"10","Depth_mm":"254","Mount_Type":"Floor Mount","Rack_UNITS":"43","Rack_INSIDE_HEIGHT_mm":"1911","Rack_INSIDE_WIDTH_mm":"584","Rack_INSIDE_DEPTH_mm":"","ASSET_TYPE":"Rack","Phases":"","Status":"","Date":"2017-01-11","Submitted":"","Image File / Web Info":"","Site":"Orlando"}]
答案 0 :(得分:1)
进入循环后
foreach ($array as $key => $value) {
#loop entered here after open
#each value of the array is accessible
#end loop here before close
}
将$key
作为整数的数组的索引值,将$value
作为保存该索引处的值的实际变量。循环内的$array
与外循环相同。 $value
表示该数组的切片。
将数据加载到新变量$price = $value["price"]
后,它将在循环结束时可用,并在重新循环时重置为新值。
因此,循环外的SQL语句将包含最后保存的值 $阵列。
答案 1 :(得分:0)
如果您对如何访问或循环数组元素有疑问,请使用var_dump
可视化其结构。
我看到你有一个对象数组,我知道每个对象都是一行。所以:
foreach($array as $object) {
//Here you have each object in $object
//$object is {"Price":"5000","Manufacturer":"Newton",...}
//Lets build the query to insert this row. I'm gonna do this with a query string as you're already using mysql_query, but as suggested you should migrate to PDO.
$query='';
foreach($object as $key=>$value) {
//To answer your $key question, here $key are Price, Manufacturer, Model, etc and $value are the correspondig values for each key
if($query) $query.=','; //add the comma if it's not the fist var
$query.='`'.mysql_real_escape_string($key).'`=\' '.mysql_real_escape_string($value).'\'';
}
$query='insert into Daily_Requests set '.$query;
mysql_query($query);
}