Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
708 views
in Technique[技术] by (71.8m points)

php - Is it possible to combine mysqli prepared 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 be inserting a large number of rows into a table that are being generated dynamically.

Is it possible to use a prepared statement to insert multiple rows into a table without previously knowing the number of new rows that will be inserted each time?

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

If that isn't possible, which would be more efficient:

  1. prepared statement, one row at a time
  2. non-prepared statement, ~50 rows 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  .= "
    (".$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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
$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();
   }

}

should do it for you!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...