Rob
Rob

Reputation: 409

Php insert/update multple row, using array and not a foreach

I’m wondering if this is possible, I’ve search and haven’t found anything so about to give up.

I’m looking to do the following for example, note i do not want to use a foreach as that converts it into single queries.

$a = (1,2,3);
$b = ('john','Rob','Stuffs');
$c = ('doe','roe','soe');

$sql = "update ppl set firstname = $b, lastname = $c where id = $a";

The same can be said for an insert.

$sql = "insert into ppl (firstname,lastname) value ($b,$c)";

The main reason I'm looking to do this is to optimise the db a bit. There are a lot of single queries that (if this method is possible) could be converted into 1 single query.

Thanks in advance.

Upvotes: 3

Views: 1405

Answers (2)

Deepika Janiyani
Deepika Janiyani

Reputation: 1477

For update you can do as follows

    $a = (1,2,3);
    $b = ('john','Rob','Stuffs');
    $c = ('doe','roe','soe');

    $i=0;
    foreach($b as $fname){
        if( !empty($b[$i]))
        {
            $sql = "update ppl set firstname = '".$b[$i]."', lastname = '".$c[$i]."' where id = $a[$i]";
        }
    $i++;
    }

and for insert you can try

    $i=0;
    $var = '';
    foreach($b as $fname){
        if( !empty($b[$i]))
        {
            $var .= "(".$a[$i].",'".$c[$i]."','".$b[$i]."') ";
        }
        $i++;
    }
    if(!empty($var)){
        $sql = "insert into ppl(id,firstname,lastname) values ".$var;
    }

Upvotes: 0

chadkouse
chadkouse

Reputation: 146

if (count($a) <= 0)
   return; // nothing to do

$sql = "INSERT INTO table (id, firstname, lastname) VALUES";
while (count($a) > 0)
{
   $id = array_shift($a);
   $fname = array_shift($b);
   $lname = array_shift($c);

   $sql .= sprintf("('%s', '%s', '%s'),", mysql_real_escape_string($id), mysql_real_escape_string($fname), mysql_real_escape_string($lname));
}
$sql = substr($sql, 0, -1); //remove last comma

$sql .= " ON DUPLICATE KEY UPDATE firstname=VALUES(fname), lastname=VALUES(lname)";

//run your sql

this will allow you to run all of them at once.

Upvotes: 4

Related Questions