获取多行,但只更新一个PHP

时间:2015-04-06 03:22:34

标签: php mysql

获取多行时,如何仅更新一行?我迷失了如何做到这一点。我可以获取一行,更新并且它可以工作。但是,我被困在了多行。

下面是我的代码

FETCH PHP:         

//loop through for results
while($row = mysqli_fetch_array($data)){
    echo "<tr><td>"   
    . $row['title']."<input type='hidden' value='".$row['title']."' name='title'>"
    . "</td><td>"
    . $row['author'] 
    . "</td><td>"
    . $row['summary'] 
    . "</td><td>"
    . $row['isbn']
    . "</td><td>"
    . "<img src='books/".$row['image']."' width='100%'/>" 
    . "</td><td>"
    . "$<input type='text' value='".$row['price']."' size='8' class='pricetoright' name='price'>"
    . "</td><td>"
    . "<button type='submit' class='btn btn-default btngreen' name='update'>Update</button>"    
    . "</td><td>"
    . "<button type='submit' class='btn btn-default btnred' name='delete'>Delete</button>"    
    . "</td></tr>";
}

更新PHP:

// Check Connection
if(!($db = mysqli_connect($server, $user, $password, $database))) {
    die('SQL ERROR: Connection failed: '.mysqli_error($db));
} 

$price = floatval($_POST["price"]);
$title = $_REQUEST["title"];

// SQL to update a record
$query = "UPDATE books SET price = '$price' WHERE title = '$title'";

if (mysqli_query($db, $query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($db);
}

mysqli_close($db);

2 个答案:

答案 0 :(得分:0)

为每行使用表单标记。最好使用唯一ID来更新行而不是标题。所以要隐藏id的输入。

答案 1 :(得分:0)

您希望在代码中添加foreach()语句。虽然您的代码有点不清楚,但这里有一个可能的例子:

foreach($_POST as $k=>$v){

 if($k === "title"){
    $title = $_POST["title"];
 }

 if($k === "price"){
    $price = floatval($_POST["price"]);
 }




// SQL to update a record
$query = "UPDATE books SET price = '$price' WHERE title = '$title'";

   if (mysqli_query($db, $query)) {
        echo "Record updated successfully";
   } else {
        echo "Error updating record: " . mysqli_error($db);
   }

}