PHP 绑定数组用于 SQL 插入

问题描述 投票:0回答:2

尝试绑定数组(第一个数组绑定)以防止 SQL 注入

这是工作代码:

if (isset($_POST['checkbox_selected']))
{       
    $valuesArr = array(); 
    foreach ($_POST['checkbox_selected'] as $key => $value) {
        //Retrieve Array ID to find Row number for CSVOption Column
        $findrow = array_search_partial($attributeid, $value);
        //attribure value is assigned to attribute id on form submit 
        $attribute = $value;            
        $csv = $csvcolumn[$findrow];        
        $valuesArr[] = "('$userid', '$feed_id', '$attribute', '$csv')";         
    }
        
    $sql = "INSERT INTO map (user_id, feed_id, attribute_id, csvcolumn) values ";
    $sql .= implode(',', $valuesArr);
    mysqli_query($conn,$sql);
}

我无法绑定数组,尝试过:

$sql = "INSERT INTO map (user_id, feed_id, attribute_id, csvcolumn) VALUES (?, ?, ? ,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('iiii', implode(',', $valuesArr));
$stmt->execute();

echo implode(',', $valuesArr)
//('1', '1', '13', '9') //This is the the array which gets inserted into the SQL
//(user_id, feed_id, attribute_id, csvcolumn) //where these are the values assigned in the 1st statement 
php sql data-binding
2个回答
1
投票

你有两个问题:

  1. 您没有使用正确的绑定语法。
  2. 您正在尝试在单个准备好的语句中插入多行。
if (isset($_POST['checkbox_selected']))
{
    $sql = "INSERT INTO map (user_id, feed_id, attribute_id, csvcolumn) VALUES (?, ?, ?, ?);";
    // prepare only has to happen once
    $stmt = mysqli_prepare($conn,$sql);

    mysqli_begin_transaction($conn);
    try {
        foreach ($_POST['checkbox_selected'] as $key => $value) {
            $findrow = array_search_partial($attributeid, $value);
            $attribute = $value;            
            $csv = $csvcolumn[$findrow];
            
            $stmt->bindParam('iiii', $userid, $feed_id, $attribute, $csv);
            $stmt->execute();
        }
        mysqli_commit($conn);
    } catch(mysqli_sql_exception $e) {
        mysqli_rollback($conn); // immediately roll back changes
        throw $e; // re-throw exception
    }
}

尝试将多个

VALUES (), ...
打包到单个查询中获得的唯一好处是,它被包装到查询所在的 implicit 事务中。该方法的其他所有内容都是缺点。显式打开包装绑定/执行循环的事务可以获得相同的好处[错误回滚、IO 批处理],同时还可以利用准备好的语句的好处。 [单个简单查询解析、参数化等]


0
投票

而不是

$stmt->bind_param('iiii', implode(',', $valuesArr));

你可以使用

$stmt->bind_param('iiii', $userid, $feed_id, $attribute, $csv);

这条线

$valuesArr[] = "('$userid', '$feed_id', '$attribute', '$csv')";  

创建一个包含一个字符串的数组,并将所有字段连接起来,我不确定你是否打算这样做。内爆返回数组的第一个也是唯一的成员。

© www.soinside.com 2019 - 2024. All rights reserved.