0
我是一個PHP新手,搜索了很多,但無法找到答案。返回多個變量php
我做了一個關於設置調查的小教程。它顯示產品名稱並有一個upvote按鈕。現在我只想添加每個項目的總票數。我想我只能使用一個返回函數,但我想使用兩個返回函數來顯示投票。我想我需要使用二維數組,但不知道如何在代碼中應用此代碼。有人可以幫我在這裏:)?
預先感謝很多
的代碼:
(反手)
<?php
// Fetches an array of all of the products in the table.
function fetch_products(){
$sql = "SELECT
`product_id`,
`product_name`,
`product_votes`
FROM `products`
ORDER BY `product_votes` DESC";
$result = mysql_query($sql);
$products = array();
$votes = array();
while (($row=mysql_fetch_assoc($result)) !== false){
$products[$row['product_id']] = $row['product_name'];
$votes[$row['product_id']] = $row['product_votes'];
}
return $products;
}
function add_product_vote($product_id, $vote){
$product_id = (int)$product_id;
$sql = "UPDATE `products` SET `product_votes` = `product_votes` + 1 WHERE `product_id` = {$product_id}";
mysql_query($sql);
}
?>
在HTML:
<?php
include('core/init.inc.php');
if (isset($_GET['vote'], $_GET['id'])){
add_product_vote($_GET['id'], $_GET['vote']);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<div>
<?php
foreach (fetch_products() as $id => $products){
?>
<p>
<?php echo $products; ?>
<a href="?vote=up&id=<?php echo $id; ?>">Up</a>
</p>
<?php
}
?>
</div>
</body>
</html>
謝謝!那我該如何迴應這個數組呢?我用了下面的代碼,但當然這不起作用,因爲它不是我以前的代碼中的數組。 '\t \t \t <?PHP的 \t \t \t \t \t \t的foreach(fetch_products()作爲$ ID => $產品){ \t \t \t \t?> \t \t \t \t
\t \t \t \t \t <?php echo $ products; ?> \t \t \t \t \t Up \t \t \t \t
\t \t \t \t <?PHP的 \t \t \t \t \t \t \t} \t \t \t \t \t \t?>' – klipperdeklip你必須改變你的循環。我已經更新了代碼 –
,謝謝!這是偉大的:)讓我的一天! – klipperdeklip