lacyeex lacyeex - 3 months ago 20
MySQL Question

INSERT into database using multidimensional array PHP

I got array like this :

Array
(
[0] => Array
(
[0] => A
[1] => 1
[2] => Too High
)
[1] => Array
(
[0] => AB
[1] => 7
[2] => OK
)
[2] => Array
(
[0] => B
[1] => 10
[2] => Too High
)
)


I'm trying to insert array above into my db using this code, i want to do it without column name, because the column could be changed anytime (user can add new field into table), array lengths is same with the amount of fields :

if(is_array($FINALRESULT)) {
$queryi = "INSERT INTO tempresult VALUES ";

$value = array();
for ($i = 0; $i < 4; ++$i) {
for ($j=0; $j < 3; $j++) {
$value[] = mysql_real_escape_string("($FINALRESULT[$j])");
}
}
$queryi .= implode(',', $value);

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


But i got notice like these :


Notice: Array to string conversion in C:\xampp\htdocs\Livestockmapping(edit)\dsssawprocess.php on line 104
Unknown column 'Array' in 'field list'

Answer

You can try this one:

$FINALRESULT = [
    ['A', 1, 'Too High'],
    ['AB', 7, 'OK'],
    ['B', 10, 'Too High'],
];

$all_values = [];
$query = "INSERT INTO tempresult VALUES ";

foreach($FINALRESULT as $key) {
    $row_values = [];
    foreach($key as $s_key => $s_value) {
        $row_values[] = '"'.$s_value.'"';
    }
    $all_values[] = '('.implode(',', $row_values).')';
}

//Implode all rows
$query .= implode(',', $all_values);

echo $query;

Result:

INSERT INTO tempresult VALUES ("A","1","Too High"), ("AB","7","OK"), ("B","10","Too High")

Also use PDO and prepared statements to avoid SQL injection.

In your code you need $FINALRESULT[$i][$j] because it's a 2 level array.

Comments