如何处理插入到mysql表中的三个数组?

时间:2019-06-28 09:27:43

标签: mysql pdo

我正在尝试使用参数绑定的pdo prepare语句将三个不同的数组插入到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;

}

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

1 个答案:

答案 0 :(得分:1)

我倾向于不使用bzr break-lock,而只是将参数添加到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