2012-12-22 128 views
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&amp;id=<?php echo $id; ?>">Up</a> 
       </p> 
       <?php 

      } 

      ?> 
     </div> 
    </body> 
</html> 

回答

2

可以返回使用作为数组

多个值
while (($row=mysql_fetch_assoc($result)) !== false) 
{ 
    $products[$row['product_id']] = $row['product_name']; 
    $votes[$row['product_id']] = $row['product_votes']; 
} 
return array('products'=>$products, 'votes'=>$votes); 
} 

在视图:

$productDetails = fetch_products(); 
foreach ($productDetails['products'] as $id => $products){ 
?> 
<p> 
    <?php echo $products; ?> 
    <a href="?vote=up&amp;id=<?php echo $id; ?>">Up</a> 
    <?php echo 'Total Votes : '.$productDetails['votes'][$id] 
</p> 
<?php 
} 
+0

谢谢!那我该如何回应这个数组呢?我用了下面的代码,但当然这不起作用,因为它不是我以前的代码中的数组。 '\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

+0

你必须改变你的循环。我已经更新了代码 –

+0

,谢谢!这是伟大的:)让我的一天! – klipperdeklip