How to Insert Array of Data into MySQL Using PHP

Insert array into MySQL database with PHP

You can not insert an array directly to MySQL as MySQL doesn't understand PHP data types. MySQL only understands SQL. So to insert an array into a MySQL database you have to convert it to a SQL statement. This can be done manually or by a library. The output should be an INSERT statement.

Update for PHP7

Since PHP 5.5 mysql_real_escape_string has been deprecated and as of PHP7 it has been removed. See: php.net's documentation on the new procedure.


Original answer:

Here is a standard MySQL insert statement.

INSERT INTO TABLE1(COLUMN1, COLUMN2, ....) VALUES (VALUE1, VALUE2..)

If you have a table with name fbdata with the columns which are presented in the keys of your array you can insert with this small snippet. Here is how your array is converted to this statement.

$columns = implode(", ",array_keys($insData));
$link = mysqli_connect($url, $user, $pass,$db);
$escaped_values = array_map(array($link, 'real_escape_string'), array_values($insData));

$values = implode("', '", $escaped_values);
$sql = "INSERT INTO `fbdata`($columns) VALUES ('$values')";

Using PHP to insert array into MySQL database?

  • To iterate over array you have to use foreach operator.
  • To perform multiple inserts you have to use prepared statements

So despite what in all other hastily written answers said, the code should be

$stmt = $con->prepare("INSERT INTO `table` (`id`, `name`, `status`) VALUES (?,?,?)");
$stmt->bind_param("sss", $id, $name, $status);
foreach ($data as $row)
{
$id = $row['id'];
$name = $row['name'];
$status = $row['status'];
$stmt->execute();
}

How to insert array of data into mysql using php

I would avoid to do a query for each entry.

if(is_array($EMailArr)){

$sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) values ";

$valuesArr = array();
foreach($EMailArr as $row){

$R_ID = (int) $row['R_ID'];
$email = mysql_real_escape_string( $row['email'] );
$name = mysql_real_escape_string( $row['name'] );

$valuesArr[] = "('$R_ID', '$email', '$name')";
}

$sql .= implode(',', $valuesArr);

mysql_query($sql) or exit(mysql_error());
}

Insert array value into MySQL by PHP

You are looping incorrectly currently your insert will execute 9 times. Whereas you want it to execute three times.

Example of current execution:

http://sandbox.onlinephpfunctions.com/code/ef1821fb0fe7dcc96a3f48e9ec8453
8cdfb5db62

You need to use the key to pair up both array values, you could do that with a for loop or by using the key in the foreach, http://php.net/manual/en/control-structures.foreach.php.

<?php
$reponse = array (1, 0 ,0);
$chimp = array (1, 0, 0);
foreach ($reponse as $key => $value) {
$values= mysql_real_escape_string($value);
$valuesch= mysql_real_escape_string($chimp[$key]);
$query = mysql_query("INSERT INTO reponses (nom_reponse,id_question,id_categorie,correct2) VALUES ('$values','$last_id','$categorie','$valuesch')")
or die(mysql_error());
}
}

I don't know where $last_id or $categorie are coming from so make sure those values are correct.

Here's how the loop will process now. http://sandbox.onlinephpfunctions.com/code/1b8af87984c348a326a64e2d453ddcdf17b65b5f

I didn't touch the SQL, looks right to me presuming your column names are correct.

Insert php array into mysql table

Corrected code:

$matstring=implode("','",$matrix[1]);

mysql_query("INSERT INTO Australia (Price, Company, Days, Weight) VALUES ('$matstring')");

(i.e. delete the second line from original code and put double quotes around the argument of mysql_query)

Appreciate user1847757's help - as s/he pointed out, $matstring itself was correct, but the single quotes inside of VALUES(' ') were being joined to the single quotes added to $matstring in the 2nd line of my original code, resulting in VALUES(''65.70','Coles','34 days','14'')

Thanks all for your help & suggestions

Insert array values into mysql through loop

Every time you iterate in the foreach you're overwritting the $sql variable. Since you're performing the query after the for loop, only the last item of the array it's being inserted into the DB.

To solve it you should put the query inside the for loop:

foreach ($arr as $value) {
$sql = "INSERT INTO videos (username, src, type, position)
VALUES ('admin', '".$value."', 'vide', '0')";

if ($conn->query($sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}

However you must take care with SQL Injection, I recommend you to take a look at PDO. http://php.net/manual/en/ref.pdo-mysql.php

Let me transform this into a PDO example:

$sql = "INSERT INTO videos (username, src, type, position ) VALUES ('admin', :value, 'vide', '0')";
if ($stmt = $PDO->prepare($sql)) {
foreach($arr as $value) {
$binds['value'] = $value;
if ($stmt->execute($binds)) {
echo "Row inserted successfully"
}
}
}

$PDO would be the variable where the conexion is stored.

how to insert to two different array in mysql database?

In this case you can use 2nd foreach for second array like

foreach($student as $value){
foreach($marks as $singlemarks){

$sql = "INSERT INTO `academic` ('student', `mark`) VALUES ('$value','$singlemarks')";

if(mysqli_query($conn, $sql)){
echo "Insert mark for student ".$value." complete<br>";
} else {
echo "Error: " . mysqli_error($conn);
}
}
}

and you can also convert array in json for store multi array in database
like json_encode($array) and same as you can decode when you want to use it

PHP not inserting array into MySQL database

There is an error in your SQL. or die(mysql_error()) does not belong there.

I suspect that you mean to write:

$sql="insert into `movies` values(NULL,'$title','$year','$format','$type','$genre','$desc','$actors','$imi','$imr','$pos','$comments','$price')";
$result=mysqli_query($con,$sql) or die(mysqli_error());

But note that your script is vulnerable to SQL injection attacks

Please read up on prepared statements. Your code will become something like this:

// create a statement with placeholders for variables
$statement = mysqli_prepare($con, "insert into `movies` values(NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

// bind the variables to the placeholders
// note: I do not know what datatypes you're expecting, so have assumed strings.
// modify the 'ssssssssssss' as required
mysqli_stmt_bind_param($statement, 'ssssssssssss', $title, $year, $format, $type, $genre, $desc, $actors, $imi, $imr, $pos, $comments, $price);

// execute the statement or show error (on production environment
// consider logging instead of displaying errors
mysqli_stmt_execute($statement) or die(mysqli_error());

// clean up the statement
mysqli_stmt_close($statement);


Related Topics



Leave a reply



Submit