开发者

shopping cart: need to output ordered items

The other page that is the index page shows the catalog of the pizzashop. Each pizza is a hyperlink that passes the id to this page. The core of my question is in the code that starts with the foreach loop. I would like to simply read out of the database based on the SELECT query at h开发者_开发技巧and. I know it is weird to put the query IN the loop but for now it is the only way I figured out how to loop through all the ids that are in the SESSION array. I tried many things to output the return that the query is supposed to give, I fiddled around with the mysqli_stmt thing, all giving me numerous types of errors.

<?php
session_start();
require 'pizza_sc_fns.php';
require 'header.php';

@$pizzaId = $_GET['pizza_id'];



if (!isset($_SESSION['order']))
{
    $_SESSION['order'] = array();
    $_SESSION['items'] = 0;
    $_SESSION['totalprice'] = 0.00;
}
if (isset ($_SESSION['order'][$pizzaId]))
{
    echo $_SESSION['order'][$pizzaId]++;
    echo "\$_SESSION['order'][\$pizzaId] is SET \n";
}
else 
{
    echo $_SESSION['order'][$pizzaId] = 1;
}

$conn = connect2db();

foreach ($_SESSION['order'] as $pizzaItem)
{
    $query = "SELECT pizza_name FROM pizzas WHERE pizza_id = $pizzaItem";
    $res = @$conn->query($query);
    echo $res->fetch_assoc(); 
    echo "<hr />";

    //$query = mysqli_prepare($conn, "SELECT * FROM pizzas WHERE pizza_id=$pizzaItem");
    //echo var_dump($query)."<br />";
    //$stmt_exec = mysqli_stmt_fetch($query);
    //print $pizzaItem."<br />";
}


?>

<a href="logout.php"> Destroy session >> </a>


You are going to need to use a loop but you don't need to run the query for every iteration. You can use the in clause.

Your code would be something like

$query = 'Select pizza_name from pizzas where id in (';

foreach($_SESSION['order'] as $pizza_id) {
    $query.= mysql_real_escape_string($pizza_id).', ';
}
$query= substr($query, 0, -2); //Get rid of the trailing comma and space
$query .= ')';

And you can run the query.

I would recommend that you use prepared statements though I'm not sure how to use them for an in statement.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜