0

The following code shows the name of the customer in a line with all the items he/she has purchased in lines below the name line.

As you will see, in the items purchased line I also print the item's price which I get from the getPrice function.

And here's the problem, the first query, the customers query, retrieves several rows of data but as soon as I call the getPrice function I get just the first row.

If instead of calling the function I give price just a value, everything goes right.

Taking this into account, I have changed the getPrice function query, thinking it could be wrong but the problem persists .. the while loop prints just one row.

Any ideas on what is going wrong? What can I try? I’m stuck :(

Thanks !!

<?php

$query1  = "SELECT * FROM Customers"; //this retrieves several rows of data
$result1 = mysql_query($query1) or die(mysql_error());

$flag = -999;
while($row = mysql_fetch_array($result1))
{

    if ($row["id"] != $flag) 
    {

        $content .="<span>".$row["lastName"].", ".$row["Name"]." </span><br />";
        $flag = $row["id"];
    }

    $content .=("Item purchased: " .$row["item"]."Price: ".getPrice($row["ItemID"])."<br />");


    $content .="</br></br>";
}                


function getPrice ($itemID)
{

    $query2  = "SELECT Price FROM Items WHERE ItemID= '".$itemID."'";
    $result2 = mysql_query($query2) or die(mysql_error());

    if($row2 = mysql_fetch_array($result2))
    {
        return $row2[0];
    } 
}

echo $content;
?>
1
  • Please post the table structure and some sample records, preferably in form of CREATE TABLE ... and INSERT INTO ... sql statements. Commented Jun 26, 2013 at 10:55

2 Answers 2

0

use while instead of if in getPrice function

function getPrice ($itemID)
{
//Changed this line
$query2="SELECT Price FROM Items WHERE ItemID= '".$itemID."'";
$result2 = mysql_query($query2) or die(mysql_error());

while($row2 = mysql_fetch_array($result2))
{
    return $row2[0];
} 
}
Sign up to request clarification or add additional context in comments.

Comments

0
function getPrice ($itemID)
{
    //Changed this line
    $query2="SELECT Price FROM Items WHERE ItemID= '".$itemID."'";//;was missing
    $result2 = mysql_query($query2) or die(mysql_error());

    if($row2 = mysql_fetch_array($result2))
    {
        return $row2[0];
    } 
}

1 Comment

My error when copying the code, in my script is correct .. thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.