PHP和MYSQL逐行更新

时间:2013-03-11 22:58:34

标签: php mysql

嘿伙计们,我正在网页上工作,我不知道为什么我无法更新数据库中的值并显示它。

这是我的PHP页面代码,用于显示链接。单击时,它将调用另一个PHP程序进行更新,然后在显示PHP程序中重新显示。

echo "<td class='text pad center'>".$row['deleted']."&nbsp;&nbsp;</td>";
if ( $row['deleted'] == 'y' ) {
    echo '<td class="text center"><a href="delete.php?id='.$row["id"].'">Restore</a>;&nbsp;&nbsp;</td>';
} else {
    echo '<td class="text center"><a href="delete.php?id='.$row["id"].'">Delete</a>;&nbsp;&nbsp;</td>';
}

在我的更新程序中,我有这个代码,它将在我的数据库中执行更新,然后发送新值以重新显示。

$id=$_GET['id'];

$sql_query = "SELECT * FROM tablename WHERE id = '$id'";
//Run our sql query
$result = mysqli_query($link, $sql_query) or die('select query failed'. mysqli_error($link));

while ($row = mysqli_fetch_assoc($result)) {
    if ( $row['deleted'] == 'y' ) {
        $change = "UPDATE inventory SET DELETED = 'n' WHERE id = '$id'";
    } else {
        $change = "UPDATE inventory SET DELETED = 'y' WHERE id = '$id'";
    }
    echo "$change";
    mysqli_query($link, $change) or die('select query failed'. mysqli_error($link));
}

//Free resultset (optional)
mysqli_free_result($result);

//Close the MySQL Link
mysqli_close($link);

header("Location: display.php");

我找不到我的错误。

1 个答案:

答案 0 :(得分:1)

由于两个原因,您的代码目前风险很大。首先,经典SQL Injection problem和第二never use GET to change things。此外,您的代码违反了DRY。

尝试重写:

echo "<td class='text pad center'>".$row['deleted']."&nbsp;&nbsp;</td>";
echo '<td class="text center"><a href="delete.php?id='.$row["id"].'">'.($row['deleted']=='y'?'Restore':'Delete').'</a>;&nbsp;&nbsp;</td>';

// IMPORTANT: Make sure you didn't forget to connect!
$id=mysqli_real_escape_string($link,$_GET['id']);
mysqli_query($link,"UPDATE tablename SET deleted=IF(deleted='y','n','y') WHERE id='$id'")
    or die('update query failed'. mysqli_error($link));
header("Location: display.php");

请注意,您应该使用01作为布尔值,而不是ny。如果您这样做,可以将deleted=IF(...)件替换为deleted=1-deleted以切换。