2016-05-21 97 views
-1

我有書本表和類別表。我也有從類別表中生成的數據下拉列表。我希望用戶將書籍表中的類別從5更改爲9.在我的下拉列表中,我將值賦給了類別ID。我怎樣才能從下拉列表中的類ID的價值,並與新的類別ID如何更新表中的外鍵值

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

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

回答

2

更新書籍表來完成,這是通過使用PHP中的擴展來操作數據庫的最佳方式。其中兩個工作得很好的是PDO和MySQLi(注意較老的擴展,MySQL的PHP​​已棄用,不應使用)。

這樣做的基本工作流程,你會想會生成表單,並在從用戶提交採取$ _ 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

驚人的文檔