views:

53

answers:

2

In PHP I am having difficulty trying to extract row data from one SQL Query results. The service information I require is stored in an array called $SelectedItems. The Code below works as it should but Prints the Entire table with all rows. How would I get it to simply print the 1 row.

    $sql ="select blah blah"
    //Output result
    $result = mysql_query($sql);


    //Generate Information about Service or Product
    while($row = mysql_fetch_array($result))
      {
        if (in_array($row['Service_Name'], $SelectedItems)){
            print $row['Service_Description'];
            print $row['Service_Cost'];
        }
      };

I am pretty new to PHP and might be going about this in the wrong way please let me know if im being back to front lol.

The $SelectedItems are processed from $_POST Data and the required data is set into an array

//Finds Out which services have been selected
foreach (array_keys($_POST) as $key) {
$$key = $_POST[$key];
    if ($$key == "1"){
        print "$key is ${$key}<br />";
        $SelectedItems[] = $key;
    };
};
A: 

I see no faults in this code at glance (however I don't have an PHP interpreter in my head, thus I can't tell for sure).

Anyway, you have to start to debug your code with actual data.
Why not to output both $row['Service_Name'] and $SelectedItems? Better by using var_dump() function. It can be type casting issue or or missing data or anything. Watching the actual data with your own eyes always helps

Just side note on your second loop. It's odd and dangerous.
And should be just

foreach ($_POST as $key => $value) {
    if ($value == "1"){
        print "$key is $value<br />";
        $SelectedItems[] = $key;
    }
}
Col. Shrapnel
+2  A: 

Better to make the selection in your SQL query than in PHP:

$sql ="select blah blah
         from <table>
       where " Service_Name IN ('".implode("','",$SelectedItems)."');

OR

$sql ="select blah blah
         from <table>
       where " Service_Name = '".$SelectedItems[0]."');

That way, you're letting the database do what it does best, reducing the volumes of data being transferred between the database and PHP, and reducing the PHP code.

Mark Baker
good point though I'd throw in an array_map with mysql_real_escape string
Col. Shrapnel
I see from the OP's edit that the $SelectedItems values are definitely coming from user input; so yes, they should be escaped as well
Mark Baker
LOL that's epic fail. escaping has nothing to do with user input. but only with quotes you put around values.
Col. Shrapnel
Oops <blush> :-(
Mark Baker
Yes Worked a treat using your implode function advice. Also thank you for the "real_escape" advice that will come in handy Too !!
Yardstermister