简体   繁体   中英

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 ie price if I enter it eg

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.

请尝试以下查询,

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM