使用PHP在二维数组中插入查询

时间:2018-12-18 03:38:42

标签: php mysql mysqli

我正在二维数组中进行此简单查询,我的问题是它不起作用,并且错误显示Array to string conversion。我尝试使用爆破功能,但也无法正常工作。希望你能帮助我。

Array( 
    [0] => Array ( 
        [0] => 04:56:27am 
        [1] => http://www.industrialknive.com/# 
        [2] => 200 
        [3] => 0 
    ) 
    [1] => Array ( 
        [0] => 04:56:28am 
        [1] => http://www.industrialknive.com/# 
        [2] => 200 
        [3] => 0 
    ) 
    [2] => Array ( 
        [0] => 04:56:30am 
        [1] => mailto:support@industrialknive.com 
        [2] => 301 
        [3] => 1 
    ) 
)

代码:

$last_id = $conn->insert_id;

for($i=0; $i < count($arrList); $i++){

    for($ii=0; $ii < count($arrList[$i]); $ii++){

        $sql = "INSERT INTO links (website, scanned_at, site_url, url_code, is_external ) VALUES ('$last_id', '$arrList[$i][$ii]', '$arrList[$i][$ii]', '$arrList[$i][$ii]', '$arrList[$i][$ii]')";

        if ($conn->query($sql) === FALSE) {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }

    }   

}

1 个答案:

答案 0 :(得分:2)

嗯,就是这样。有两点:1)PHP有一个foreach construct,因此您不需要使用老式的for循环。 2)通过使用字符串串联来构建查询,您可以自己SQL injections。 3)您为每个数组的每个元素运行一次查询。

自从我使用mysqli以来已经有一段时间了,但是类似的东西应该可以工作:

<?php
$last_id = $conn->insert_id;
$query = "INSERT INTO links (website, scanned_at, site_url, url_code, is_external ) VALUES (?, ?, ?, ?, ?)";
if ($stmt = $conn->prepare($query)) {
    foreach ($arrList as $arr) {
        $stmt->bind_param("isssi", $last_id, $arr[0], $arr[1], $arr[2], $arr[3]);
        if (!$stmt->execute()) {
            echo "Error executing: " . $sql . "<br>" . $stmt->error;
        }
    }
} else {
    echo "Error preparing: " . $sql . "<br>" . $conn->error;
}