如何处理三个数组插入mysql表? [重复]

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

我正在尝试使用参数绑定的 pdo 准备语句将三个不同的数组插入到 sql 表中。我的代码如下所示:

try {

    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {

    throw new \PDOException($e->getMessage(), (int)$e-getCode());
}

$count = $_POST['count'];
$first = $_POST['first'];
$last = $_POST['last'];

// $serial_no is the first array being defined as follows:
$serial_no = array_map(function($n) { return sprintf('0%05d', $n);}, range($first, $last));

// $identifier is the second array being defined as follows:

$i = 0;
$identifier = array();

while ($i++ < $count) {
    $identifier[] = rand(1000, 9999) . "-" . rand(1000, 9999) . "-" . rand(1000, 9999). "-" .rand(1000, 9999);
}

// $win_value is the third array being defined as follows:

$n = 0;
$win_value = array();

while ($n++ < $count) {
    $win_value[] = ceil(rand(10,80)/10)*10;
}


$stmt = $pdo->prepare("INSERT INTO tickets (serial_no, identifier, win_value) VALUES (?, ?, ?)");

try{
    $pdo->beginTransaction();
    foreach (array_keys($serial_no) as $key) 
    {
        $statement->bind_param($serial_no[$key], $identifier[$key], $win_value[$key]);
        $statement->execute();
    }
    $pdo->commit();

    header("Location: msg.php");

}catch (Exception $e) {

    $pdo->rollback();
    throw $e;

}

但是,这些值不会使用此逻辑插入到表中。任何帮助将不胜感激。谢谢。

php mysql pdo
1个回答
1
投票

我倾向于不使用

bind_params
,而只是将参数添加到
execute
调用中:

$statement->execute([$serial_no[$key], $identifier[$key], $win_value[$key]])

您可能还想检查一下

count($serial_no) === $count

您遇到错误了吗?

您的

foreach
也可以是
foreach($serial_no AS $key=>$value)
您将忽略
$value
,但这样
$key
就已经为您填充,无需调用
array_keys

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.