简体   繁体   English

PHP和MYSQL通过链接更新行

[英]PHP and MYSQL with updating a row by link

Hey guys, I am working on a webpage and I don't know why I can't update a value from my database and display it. 大家好,我正在开发一个网页,但我不知道为什么我无法从数据库中更新值并显示它。

This is my code for the PHP page to display the link. 这是我的PHP页面显示链接的代码。 When clicked it will call another PHP program to do the update and then be redisplayed in the display PHP program. 单击后,它将调用另一个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>';
}

And in my update program I have this code that will perform the update in my database and then send the new value to be redisplayed. 在我的更新程序中,我有这段代码,它将在数据库中执行更新,然后发送要重新显示的新值。

$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");

I can't find my error. 我找不到我的错误。

Your code is currently at great risk for two reasons. 当前,您的代码面临很大风险,原因有两个。 First of all, the classic SQL Injection problem , and second never use GET to change things . 首先,是经典的SQL注入问题 ,其次, 从不使用GET来更改事物 In addition, your code violates DRY quite a bit. 另外,您的代码相当违反DRY。

Try this rewrite: 试试这个重写:

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>';

And: 和:

// 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");

Note that you should really use 0 and 1 for boolean values, not n and y . 请注意,对于布尔值,您应该真正使用01 ,而不是ny If you do this, you can replace the deleted=IF(...) piece with deleted=1-deleted to toggle. 如果执行此操作,则可以将deleted=IF(...)替换为deleted=1-deleted以进行切换。

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

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