Is it possible to combine a prepared mysqli statement with multiple inserts?

I am well versed in the old php mysql extension.

I am working on my first script that uses the mysqli extension.

I am going to insert a large number of rows into a table that are generated dynamically.

Can I use a prepared statement to insert several rows into a table without prior notice of the number of new rows that will be inserted each time?

$stmt   = $mysqli->prepare("INSERT INTO `activity` (`id`, `name`, `type`) VALUES ?, ?, ?;");

If this is not possible, it will be more efficient:

  • prepared statement, one line at a time
  • unprepared statement, ~ 50 lines at a time

    // prepared statement
    
    $stmt   = $mysqli->prepare("INSERT INTO `activity` (`id`, `name`, `type`) VALUES (?, ?, ?)");
    
    for($i=0;$i<$limit;$i++)
    
    {
    
        $stmt->bind_param('iss', $id[$i], $name[$i], $type[$i]);
    
        $stmt->execute();
    
    }
    
    
    // non-prepared statement
    
    $query  = "INSERT INTO `activity` (`id`, `name`, `type`) VALUES ";
    
    for($i=0;$i<$limit;$i++)
    
    {
    
        $query  .= "\n(".$mysqli->real_escape_string($id[$i]), $mysqli->real_escape_string($name[$i]), $mysqli->real_escape_string($type[$i])."),";
    
    }
    
    $query  = substr($query, 0, -1).';';
    

PHP v.5.3.8

MySQL v. 5.1.60

+3
source share
1 answer
$stmt = $mysqli->stmt_init();

if($stmt->prepare("INSERT INTO `activity` (`id`, `name`, `type`) VALUES (?, ?, ?)"))
{
   $stmt->bind_param('iss', $_id, $_name, $_type);
   for($i=0;$i<$limit;$i++)
   {
      $_id = $id[$i];
      $_name = $name[$i];
      $_type = $type[$i];
      $stmt->execute();
   }

}

gotta do it for you!

+2
source

All Articles