user2376459
user2376459

Reputation: 43

Using two arrays with different keys in an mysql update query

I have a array like this

$outputs:
  269 => string '   SUN: 2.495' (length=13)
  510 => string '   SUN: 1.416' (length=13)

Another Array like this

$filenames:
  0 => string 'Hi35
' (length=5)
  1 => string 'He_41
' (length=6)

And to update the respective values i tried writing a code like

foreach($outputs as $key => $value){
    $sql = "UPDATE Store SET D='".$value."' WHERE `Index` = '".$filenames[$key]."'";
    mysql_query($sql);
}

But then there is no $filenames[$key] value, because the key value for $outputs starts with 269. This is only one case, the key value could be anything.

I also tried the other way around. i.e.

I combined both the array first

$arr3 = array_combine($outputs, $filenames);

And then tried to Put the combined array in SQL query like

foreach($arr3 as $key => $value){
    $sql = "UPDATE Store SET D='".$key."' WHERE `Index` = '".$value."'";
    mysql_query($sql);
}

BUT this dint work.. A help from your side will really be appreciated...

Upvotes: 0

Views: 355

Answers (2)

medina
medina

Reputation: 8159

Your code doesn't look good at all mate, but here is a hack for that:

$num_outputs = count($outputs);

$index = 0;
foreach($outputs as $key => $value) {
    $sql = "UPDATE Store SET D='".$value."' WHERE `Index` = '".$index."'";
    mysqli_query($sql);
    $index++;
}

Upvotes: 0

Fabio
Fabio

Reputation: 23490

You can do something like this

$outputs = array(
  '269' => 'SUN: 2.495',
  '510' => 'SUN: 1.416'
  );

$filenames = array(
  '0' => 'Hi35',
  '1' => 'He_41'
);

$array_complete = array_combine($filenames, $outputs);

foreach($array_complete as $key => $val)
{
    echo "UPDATE Store SET D='".$val."' WHERE `Index` = '".$key."'" . '<br>';
}

This will output

UPDATE Store SET D='SUN: 2.495' WHERE `Index` = 'Hi35'
UPDATE Store SET D='SUN: 1.416' WHERE `Index` = 'He_41'

Then I would like to remember you that mysql_ functions are deprecated so i would advise you to switch to mysqli or PDO

Upvotes: 1

Related Questions