How to bind an arbitrary number of values to a prepared statement in mysqli?

后端 未结 1 641
春和景丽
春和景丽 2020-11-28 16:03

I would really like for someone to take a little time and look over my code. I\'m parsing some news content and I can insert the initial parse into my database which contai

相关标签:
1条回答
  • 2020-11-28 16:54

    This is exactly the scenario where mysqli is really awkward. To bind multiple params, you have to pass them all as a variable-length argument list to mysql->bind_param(), but the tricky part is that you have to bind them by reference. References in PHP can be pretty confusing.

    Here's an rough example (though I have not tested this exact code):

    $stmt = $mysqli->prepare("INSERT IGNORE INTO test_news 
        (article, link, text_cont) VALUES (?,?,?)");
    foreach ($reverse as &$value) {
      $params[] = &$value;
    }
    array_unshift(str_repeat('s', count($params)));
    call_user_func_array(array($stmt, 'bind_param'), $params);
    

    I find it much easier to use PDO when I want to write a general-purpose function to bind parameters to SQL. No binding is necessary, just pass an array of values to the PDOStatement::execute() method.

    $stmt = $pdo->prepare("INSERT IGNORE INTO test_news 
        (article, link, text_cont) VALUES (?,?,?)");
    $stmt->execute($reverse);
    

    Update: if you need $items to contain multiple rows of data, I'd do it this way:

    First, when building $items, make it an array of arrays, instead of concatenating the values together:

    foreach ($main->find('a') as $m){
        $items[] = array($m->plaintext, $m->href, $text_content);
    }
    

    Then prepare an INSERT statement that inserts one row, and loop over $items executing the prepared statement once for each tuple:

    $stmt = $pdo->prepare("INSERT INTO test_news 
        (article, link, text_cont) VALUES (?,?,?)");
    foreach ($items as $tuple) {
        $stmt->execute($tuple);
    }
    

    I don't know why you were using array_reverse() at all, and I don't know why you were using INSERT IGNORE, so I left those out.

    0 讨论(0)
提交回复
热议问题