我有一个数组,我想插入mysql数据库。
Array ( [posts] => Array ( [0] =>
Array ( [channel_id] => 18560 [category_id] => 41 [channel_name] => Bohemian FC 1 - 1 Chelsea [channel_image] => IMG-20190416-WA0087.jpg [channel_url] => nourl [channel_description] => [channel_type] => URL [video_id] => [category_name] => Last day Matches ) [1] =>
Array ( [channel_id] => 18559 [category_id] => 41 [channel_name] => Nigeria 2 - 1 South Africa [channel_image] => IMG-20190416-WA0087.jpg [channel_url] => nourl [channel_description] => [channel_type] => URL [video_id] => [category_name] => Last day Matches ) ) )
Array ( ) Array ( ) Array ( ) Array ( )
insert.php
foreach($array as $row) //Extract the Array Values by using Foreach Loop
{
$query .= "INSERT INTO tbl_channel(category_id,channel_name, channel_image,channel_url,channel_description,channel_type,video_id) VALUES ('".$row["category_id"]."', '".$row["channel_name"]."', '".$row["channel_image"]."', '".$row["channel_url"]."', '".$row["channel_description"]."', '".$row["channel_type"]."', '".$row["video_id"]."'); "; // Make Multiple Insert Query
table_data .= '<tr></tr>';
}
if(mysqli_query($connect, $query)) //Run Mutliple Insert Query
{
echo '<h3>Imported Data</h3><br />';
}
我无法在MySQL表中插入值。我遇到错误Illegal string offset 'category_id'
,我的代码有什么错误(对不起的语言不好)
答案 0 :(得分:1)
在构建查询字符串的循环中,添加快速检查以查看是否存在正确的数组元素,如果存在则仅将其添加到查询字符串中。
if (isset($row['category_id'])) {
// add the row to the query string
}
然后,如@Qirel所说,您不能运行多个查询,因此需要调用mysqli_multi_query()
。
正如@Qirel指出的那样,这种事情是使用准备好的语句的理想场所。在循环之前准备查询,然后在循环内部使用不同的参数值调用查询。它增加了针对漏洞的安全级别,并且可能会提高性能。