简体   繁体   English

PHP从具有多维数组的值更新表

[英]PHP updating table from values with multidimensional array

My php code is 我的PHP代码是

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"); mysqli_query($ con,“更新TABLE 1设置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"); 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. $cols[$i][4]是一个数组,当我回显它时,它给出正确的值,但是当对update语句应用相同的值时,它不接受它。

请尝试以下查询,

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 ). 考虑到要插入到SQL语句(多维数组)中的变量的复杂性,不能像简单变量( $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. 我还建议尽可能在表名中避免使用空格和关键字,这样可以减少SQL错误的机会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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