sachin_ware
sachin_ware

Reputation: 1561

PHP updating table from values with multidimensional array

My php code is

for($i=1;$i<$rows;$i++)
{
    $flag=0;
   $result = mysqli_query($con,"SELECT id FROM `TABLE 1` ");
   while($row = mysqli_fetch_array($result))
   {
     //echo $row['id']."<br>";
     echo $cols[$i][0];
     if($row['id']==$cols[$i][0])//id exists in database=> update
     {
        echo"<br> ".$cols[$i][4];
        mysqli_query($con,"UPDATE `TABLE 1` SET `price`=$cols[$i][4]  WHERE `id`=07");
        //echo $cols[$i][0];
        $flag=1;
     }
    }
    if($flag==0)//Add new record in to database
    {
       //code for insert
    } 
}

It does not update the price

mysqli_query($con,"UPDATE TABLE 1 SET price=$cols[$i][4] WHERE id=07");

It update the value i.e. price if I enter it e.g.

mysqli_query($con,"UPDATE TABLE 1 SET price=100 WHERE id=07");

$cols[$i][4] Is an array and it gives the correct value when I echo it, but when the same value is applied for the update statement it does not take it.

Upvotes: 0

Views: 772

Answers (2)

doublesharp
doublesharp

Reputation: 27599

Given the complexity of the variable you are inserting into your SQL statement - a multidimensional array - you can't just include it in the string like you would a simple variable ($var[0][1] vs $var). Either concatenate the string with . or surround the variable with curly braces { and }.

// using concatenation
$sql = "UPDATE `TABLE 1` SET price=".$cols[$i][4]." WHERE `id`=07";
// using curly braces
$sql = "UPDATE `TABLE 1` SET price={$cols[$i][4]} WHERE `id`=07";
mysqli_query( $con, $sql );

I would also recommend avoiding spaces and keywords in your table names if possible, it reduces the chances of errors in your SQL.

Upvotes: 1

Jimesh Gajera
Jimesh Gajera

Reputation: 612

Try below query,

mysqli_query($con,"UPDATE `TABLE 1` SET `price`= '".$cols[$i][4]."'  WHERE `id`=07");

Upvotes: 0

Related Questions