我想添加一些功能到我的烹飪書,但我想不出一種包括我點擊編輯的ID的方式。php編輯記錄,如何包含當前編號
該表被稱爲「廚師」,是3列; -id爲AUTO_INCREMENT - 姓名 - 國家
然後,我有我在哪裏顯示廚師名單上的index.php名單:
<?php
$chefs = get_chefs();
?>
<h3>Chefs' list</h3>
<ul>
<?php foreach ($chefs as $chef) {
echo '<li>' . $chef['name'] . ' from ' . $chef['country'] . '<a class="toLink" href="edit_chef.php?id=' . $chef['id'] . '" title="edit chef">Edit chef</a>' . '</li>';
} ?>
</ul>
在功能PHP中,我有一個get_chefs()功能和find_chef_by_id($ ID)功能:
function get_chefs() {
include'db_connection.php';
try {
return $conn->query("SELECT * FROM chefs");
} catch (PDOException $e) {
echo 'Error:' . $e->getMessage() . "<br />";
return array();
}
return true;
}
function find_chef_by_id($id = ':chef_id') {
include 'db_connection.php';
$sql = 'SELECT * FROM chefs WHERE id=:chef_id';
try {
$results = $conn->prepare($sql);
$results->bindParam(':chef_id', $chef_id, PDO::PARAM_INT);
$results->execute();
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage() . '<br />';
return array();
}
return $results->fetchAll(PDO::FETCH_ASSOC);
}
要處理一個廚師的版本,我創建了一個名爲edit_chef.php:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$country = filter_input(INPUT_POST, 'country', FILTER_SANITIZE_STRING);
if(empty($name)) {
$error_message = "Chef's name can not be empty";
} elseif (empty($country)) {
$error_message = "Country can not be empty";
}else {
if(edit_chef($name, $country)) {
header('Location: index.php');
exit;
} else {
$error_message = "Could not update chef";
}
}
}
include 'includes/header.php';?>
<div class="col-container">
<h1>Edit chef</h1>
<?php
if (isset($error_message)) {
echo '<p class="message">' . $error_message . '</p>';
}
$chefs = get_chefs();
foreach ($chefs as $chef) {
$id = find_chef_by_id($chef["id"]);
?>
<form method="POST" action="edit_chef.php?chef=<?php echo urldecode($id); ?>">
<div>
<label for="name" class="required">Name</label>
<input name="name" type="text" value="<?php echo htmlentities($chef["name"]); ?>" />
</div>
<div>
<label for="country" class="required">Country</label>
<input name="country" type="text" value="<?php echo htmlentities($chef["country"]); ?>" />
</div>
<button class="submit" type="submit" name="submit">Submit</button>
</form>
</div>
但目前,我不知道是不是因爲我不應該使用foreach循環,或者我的$ id值不是find_chef_by_id($ chef [「id」]),當我點擊編輯廚師時,它會轉到正確的地址「http://localhost/cooking_book/edit_chef.php?id=1」,但對於每位廚師來說,這不僅僅是我單擊的那個廚師。
我在做什麼錯?
謝謝
如果您的'find_chef_by_id'函數bindParam調用的是$ id,而不是$ chef_id ? –
其實你是對的,我已經修好了,但是,它根本沒有任何改變,但是,當我點擊編輯廚師出現一個表格,每個人都在dable –
也你不應該需要'foreach ($ chefs as $ chef){'在您的edit_chef.php –