如何更新表

时间:2016-05-21 19:29:12

标签: php mysql

我有书桌和类别表。我还有一个下拉列表,其中包含类别表中生成的数据。我希望用户更改books表中的类别,例如从5到9.在我的下拉列表中,我将值分配给类别ID。如何从下拉列表中获取类别ID的值,并使用新的类别ID

更新book表
+------------+---------+----------------+
| Books                                 |
+------------+---------+----------------+
| bookID     | bName   |categoryID (FK) |
+------------+---------+----------------+
|          1 |some text|5               |
|          2 |some text|9               |
+------------+---------+----------------+

+------------+---------+
|       category       |
+------------+---------+
| categoryID |cat name |
+------------+---------+
|          5 |fiction  |
|          9 |history  |
+------------+---------+

1 个答案:

答案 0 :(得分:2)

实现此目标的最佳方法是在PHP中使用扩展来操作数据库。其中两个效果很好的是PDO和MySQLi(请注意旧的扩展,PHP的mysql已弃用且不应使用)。

您需要的基本工作流程是生成表单,并在用户提交后获取$ _POST数据并通过PHP将其发送到您的数据库以更新您的表,类似于(但不完全是) :

// Establish a connection to your database with MySQLi using the correct
// hostname, username, password, and database name
$connection = new mysqli($hostname, $username, $password, $database);

// Check if the connection works
if($connection->connect_errno) {
    die("Unable to connect to database");
}

// Retrieve the new id from your form
$new_id = $_POST['new_id'];

// Set the MySQL query to run which will update your table
// Below where it says "table" use your table's name
$query = "UPDATE table SET categoryID = '$new_id' WHERE bookID = '$bookID'";

// Execute the query
$connection->query($query);

// Close the connection to the database
$connection->close();

如果您不熟悉使用PHP来操作数据库,PHP手册中有关于如何完成所有这些操作的惊人文档here