开发者

reading from table in a loop

with the code below i let people fill in how many pizza's they want and then pass the chosen pizza ids through the url using get.

<?php // some code that connects to database ?>
<table>

        <form method="get" action="oder_process.php">
                <?php
                while (list($pizzaId, $pizzaName, $pizzaNumber, $pizzaPrice) = mysql_fetch_row($resultaat))
                        {

                            echo        "<t开发者_开发问答r>
                                        <td>".$pizzaName."</td>
                                        <td>".$pizzaNumber."</td>
                                        <td>".$pizzaPrice."</td> 
                                        <td> <input type='text' name='pizzas[$pizzaId]'                   value='$qty' size='3' /></td>
                                        </tr>";
                        }
                mysql_close($db);        
                ?>
            <input type="submit" value="Bestel!" />
        </form>
    </table>

Now displaying the pizza id with the amount filled in works just fine. But then I also want to read other columns like pizza name or description from the database. However what i'm doing below doesn't do it. Any ideas?

part of the order_process.php file:

echo "Your order: <br />";


            foreach ($_GET['pizzas'] as $pizzaId => $qty)    
            {
                if ($qty > 0)
                echo $pizzaId." ".$qty."<br />";
                $pizzaSql = mysql_query("SELECT * FROM pizzas where pizza_id =       $pizzaId");
                while ($row = mysql_fetch_assoc($pizzaSql))
                {
                    echo $row['pizza_name'];
                }
            }


why foreach()? can't you just ...

if ( is_numeric( $_GET['pizzaid'] ) ) {
    $pizzaSql = sprintf("SELECT * FROM orders WHERE pizza_id=%d",$_GET['pizzaid']);
    $pizzaQuery = mysql_query($pizzaSql);
    $numPizzas = mysql_num_rows( $pizzaQuery );
    while ( $order = mysql_fetch_array($pizzaQuery,MYSQL_ASSOC) ) {
        if ( $numPizzas > 0 ) {
            echo $orderVariables;
        } else {
            echo 'Error: no order exists for that ID thingy';
        }
    }
}

i added some minor validation that assumes the pizza/order id is a numeric value. i don't trust anything that comes into a script from the $_GET array without some serious data validation first


can you try chucking in a test to make sure the query worked as expected

$pizzaSql = mysql_query("SELECT * FROM pizzas where pizza_id = $pizzaId");

if (mysql_error()) {
   die(mysql_error());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜