Peter Peter - 3 years ago 77
PHP Question

Inserting data from array to mysql

I'm having issues inserting array values into mysql. I have an array $list which holds 30 items. I'd like to insert each value in the array to a new row in the column 'title' in my database.

I've checked the php manual and it seems array_walk would be the best choice here. Here is the code which creates the array and tries to add it to the database (at the moment it creates 30 empty rows). The array does contain the 30 items.

$nodelist = $xpath->query("//span[@class='mp-listing-title']");

$list = array();

$i = 0;

foreach ($nodelist as $n) {
if ($i >=5 && $i <=35) {
$value = $n->nodeValue;
$list[] = $value;
}
$i++;
}

function sql() {

global $table_id;
global $array_walk;

$sql = "INSERT INTO $table_id (title) VALUES ('$array_walk')";
}

$array_walk = array_walk($list, 'sql' );


To my understanding the $array_walk variable should apply function sql() to each value in $list but it is not writing anything to the mysql database. Can anyone shed some light on what I'm doing wrong? Any help is much appreciated!

Answer Source

Try this code:

$nodelist = $xpath->query("//span[@class='mp-listing-title']");
$list = array();
$i = 0;
foreach ($nodelist as $n) {
    if ($i >=5 && $i <=35) {
        $value = $n->nodeValue;
        $list[] = $value;
    }
    $i++;
}

$db = mysqli_connect(<your db details here>);

foreach ($list as $item) {
    mysqli_query($db, "INSERT INTO $table_id (title) VALUES ('$item')");

EDIT 1. You must execute query
EDIT 2. Use foreach for listing array
EDIT 3. Use mysqli_connect to connect database

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download