Question

I have a pretty large insert statement something like

INSERT INTO multimedia (filename, regex, flag) VALUES (('adsfavr.jpg', '<div id="title">', 0), (...), (...));

How do I prepare the query for MySQL.It's too long to do it manually. It includes double quotes so I can't use the php function mysql_real_escape_string()

Was it helpful?

Solution

Why do you want to insert all records with a single statement? You could use a prepared statement: INSERT INTO multimedia (filename, regex, flag) VALUES (?, ?, ?);

and a for-loop to insert the records one by one.

I'm not a PHP programmer, but the code could look like this (parts taken from http://php.net/manual/en/pdo.prepared-statements.php):

$stmt = $dbh->prepare("INSERT INTO multimedia (filename, regex, flag) VALUES (:filename, :regex, :flag)");
$stmt->bindParam(':filename', $filename);
$stmt->bindParam(':regex', $regex);
$stmt->bindParam(':flag', $flag);

for ( $i = 1; $i <= ...; $i++) {
    $filename = ...
    $regex = ...
    $flag = ...

    $stmt->execute();
}

Using a prepared statement, the DBMS only compiles the SQL once, as it would with your SQL statement. To get sure that either all or no records are inserted (if you need such an assertion anyway), use a transaction.

Further, this would also solve your escaping problem, since you don't need to put the values in a string. The string for a prepared statement only defines the SQL "template".

OTHER TIPS

if your data stored in a comma separated file, you can use LOAD DATA INFILE query

A sample of this data could help.

you can try this way to execute multiple inserts in a single query...

$sql = "INSERT INTO users (name, age)
  VALUES
  ('Helen', 24),
  ('Katrina', 21),
  ('Samia', 22)";

mysql_query( $sql);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top