返回多个变量php

时间:2012-12-22 14:38:46

标签: php database survey

我是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>

1 个答案:

答案 0 :(得分: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
}