嘗試以下操作:
// Show all products
$q = mysqli_query($con, "SELECT `id` FROM `products`");
if(mysqli_num_rows($q) > 0) { // Check if there are results
while($row = mysqli_fetch_assoc($q)) {
echo '<p>Product A | <a href="product.php?id='.$row['id'].'">Add to Cart</a></p>';
}
}
在product.php
function productExists($id) {
if(!empty($id)) {
$q = mysqli_query($con, "SELECT `id` FROM `products` WHERE `id` = $id");
if(mysqli_num_rows($q) > 0) {
return true;
} else {
return false;
}
} else {
return false;
}
}
function productData($id) {
if(!empty($id)) {
$q = mysqli_query($con, "SELECT `id`, `product_name`, `product_price`, `product_quantity`, `product_image` FROM `products` WHERE `id` = $id");
if(mysqli_num_rows($q) > 0) {
$data = array(); // Store data
while($row = mysqli_fetch_assoc($q)) {
$data[] = $row;
}
if(!empty($data)) { // Make sure all data is gathered before proceeding
return $data;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
if(!empty($_GET['id'])) { // empty does the same as isset() but also checks if the value is not empty
$id = (int)mysqli_real_escape_string($con, $_GET['id']);
if(productExists($id)) {
$data = productData($id);
echo 'Product: '.$data['product_name']; // Etc.
} else {
echo 'Product doesn\'t exists';
}
}
當調整一些的T他的代碼你也可以得到其他列
而你確切的問題是? – SuperDJ
我編輯了這個問題。 PLZ檢查 – gosulove
我認爲你的意思是你不完全知道如何從數據庫中獲得ID? – SuperDJ