0

私はphpの初心者で、たくさん検索していますが、答えが見つかりません。

アンケートの設定について少しチュートリアルを行いました。製品名が表示され、賛成ボタンがあります。ここで、各アイテムの投票の合計を追加したいだけです。私は 1 つの return 関数しか使用できないと考えましたが、2 つの return 関数を使用して投票も表示したいと考えています。2 次元配列を使用する必要があると考えていますが、これをコードに適用する方法がわかりません。誰かがここで私を助けることができます:)?

事前にたくさんありがとう

コード:

(バックハンド)

   <?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>
4

1 に答える 1

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
}
于 2012-12-22T14:47:14.960 に答える