1

我试图弄清楚如何更新特定数据库行中的数据,而不是删除然后再次插入另一个查询。有谁知道我该怎么做?

main.php 内容

<body>

<h1>Introduction Box</h1>
<form action="edit.php" method="post">
Title: <input type="text" name="introtitle">
Description: <textarea name="introdescription"></textarea>
<input type="submit">
</form>

</body>

edit.php 内容(现在这只添加表单中的条目)

<?php
// Connnection to MySQL
$connection = mysqli_connect("");

// Check Connection and Display If Error

if (mysqli_connect_errno($connection)) {
  echo "Failed to connect to MySQL: " . mysqli_conncet_error();
}

$introduction="INSERT INTO Introduction (Title, Description)
VALUES ('$_POST[introtitle]','$_POST[introdescription]')";

if (!mysqli_query($connection, $introduction) or die(mysql_error()))
  {
  die('Error: ' . mysqli_error($connection));
  }
echo "Record has been updated.";

mysqli_close($connection);

?>

任何帮助将不胜感激!

4

4 回答 4

2

html表单代码看起来像

<h1>Introduction Box</h1>
<form action="edit.php" method="post">
Title: <input type="text" name="introtitle">
Description: <textarea name="introdescription"></textarea>
<input type="hidden" name="id" value="<?php echo $current_edit_id;?>">
<input type="submit">
</form>

</body>

php 脚本代码看起来像

<?php
// Connnection to MySQL
$connection = mysqli_connect("");

$current_edit_id = $_POST['current_edit_id'];

// Check Connection and Display If Error

if (mysqli_connect_errno($connection)) {
  echo "Failed to connect to MySQL: " . mysqli_conncet_error();
}

$introduction="UPDATE Introduction SET Title='value', Description='value' WHERE ID='$current_edit_id'";

if (!mysqli_query($connection, $introduction) or die(mysql_error()))
  {
  die('Error: ' . mysqli_error($connection));
  }
echo "Record has been updated.";

mysqli_close($connection);

?>

希望这对你有帮助。

于 2013-07-26T02:39:11.160 回答
1

在编辑表单中,您需要一个带有 ID 的隐藏字段。“标题”是 ID,还是有单独的 ID 列?

在 SQL 中,根据 ID 或 TITLE 是您的键,您需要:

update INTRODUCTION set TITLE=?, DESCRIPTION=? where ID=?
update INTRODUCTION set TITLE=?, DESCRIPTION=? where TITLE=?  -- set new title, WHERE previous title

如果您坚持使用未准备好的语句(易受 SQL 注入攻击),请确保过滤或清理进入 SQL 语句的值。请参阅:最好的 PHP 输入清理功能是什么?

UPDATE Introduction SET Title='value', Description='value' WHERE ID=id

从 Web 到 SQL 的未过滤值允许攻击者轻松破解或破坏您的数据库。

于 2013-07-26T02:36:03.087 回答
1

有两个选项,您可以使用“DUPLICATE KEY UPDATE”子句,并在记录已经存在时获取您想要更新的内容

INSERT INTO `table`
    (`col1`,`col2`)
SELECT * FROM table
ON DUPLICATE KEY UPDATE col1 = 'value';

第二个选项是使用 REPLACE。对于这个,只需将 INSERT 替换为 REPLACE,它应该可以正常工作:

REPLACE INTO Introduction (Title, Description)
VALUES ('$_POST[introtitle]','$_POST[introdescription]')

http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html

http://dev.mysql.com/doc/refman/5.0/en/replace.html

于 2013-07-26T02:36:45.290 回答
0

查询语法是mysql_query("UPDATE tablename SET column='value' WHERE CONDITION")

于 2013-07-26T02:36:55.317 回答