2

我有一个这样的表 userx:

id----------text---------num          
1-----------foo-----------0  
2-----------bar-----------0  
3-----------widget--------0  
4-----------widget--------0  
5-----------widget--------0  
6-----------widget--------0  
7-----------widget--------0  
8-----------widget--------0

我有一个这样的数组:

$numeros = array(30, 50, 60, 70, 90, 110, 130, 150);

所以我想做一个查询,从 $numeros 获取每个结果并更新到我的列(从 id=1 开始)“num”,如下所示:

id----------text--------------num          
1-----------foo--------------30  
2-----------bar--------------50  
3-----------widget-----------60  
4-----------widget-----------70  
5-----------widget-----------90  
6-----------widget-----------110  
7-----------widget-----------130  
8-----------widget-----------150 

是否可以为此更新单个更新(或循环内的多个)查询?如何?

4

2 回答 2

0

你可以尝试这样的事情:

$query = "UPDATE userx SET num=? WHERE id=?";
for($j = 0, $j < sizeof(numeros); $j++)
{
    $index = $j+1;        
    $stmt = $db->prepare($query);
    $stmt->bind_param('ii', $numeros[$j], $index);
    $stmt->execute();
}

所以虽然它在技术上不是一个查询,但你只写一次

于 2013-03-25T19:56:05.890 回答
0

您可以尝试使用一个函数通过 for 循环调用另一个函数来更新每个元素。IE

#CODE TO CONNECT TO Mysql database
#then call function to update these column elements
updateColumns();
function updateColumns(){
    $query = "SELECT column FROM table";
    $result = mysql_query($query);

    if(!$result){
        echo "Error message you want.</br>";
        echo mysql_error();
    }
    else{
        $count = mysql_num_rows($result);
        if($count){
            # There are rows. now check if there is a match
            while($row=mysql_fetch_array($result)){
                #cycle through each row of the $result column
                foreach($row as $key => $value){
                    if($key){
                        updateThisColumnsValue($value);
                    }
                }
            }
        }
    }
}
function updateThisColumnsValue($value){
    $query = "UPDATE table SET columnToCHange='newValue' WHERE referenceColumnName = '$value'";
    $result = mysql_query($query);
    if(!result){
        error message
    }# that should be it. 
}

另外这里是 sql 更新函数w3school.sql的链接, 希望对您有所帮助。

于 2016-03-19T23:09:33.147 回答