1

I'm writing some data off my MySQL database into an array using columns with php like this:

    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $row->id = $row["ID"];
            $row->product = $row["product"];
            $row->aantal = $row["Aantal"];
            $row->price = $row["Price"];
            $od[] = $row;
    }
    } else {
       echo "0 results";
    }

now later I have to use the $row->id and $row->product of the different columns seperatly to get some more data out of another table in MySQL. I've been trying to accomplish this:

$to = 0;
foreach($od as $odt)
{
    $odb= $odt[$to]["ID"];
    $sql = "SELECT `Name` FROM `detail` WHERE `ID` = '$odb'";
    $to++;

But this doesn't seem to work, I've tried dozen of others but can't seem to get this thing right...

Any solutions or remarks?

EDIT: Array ( [0] => Array ( [ID] => 3 [product] => 10 [Aantal] => 1 [Price] => 3 ) [1] => Array ( [ID] => 4 [product] => 13 [Aantal] => 1 [Price] => 3 ) [2] => Array ( [ID] => 5 [product] => 3 [Aantal] => 3 [Price] => 4 ) )

3
  • you have unnecessarily overwritten your array into an object, and you don't need a foreach if you're going to point to the first element directly. and that $to is also unneeded, you just made your foreach loop more complicated Commented Apr 20, 2015 at 13:05
  • Abhik answer should get it working, however you should look into SQL joins. dev.mysql.com/doc/refman/5.0/en/join.html Commented Apr 20, 2015 at 13:06
  • I am familiar with SQL joins but I don't understand how they can be of help to this matter? I will still have to check the matching id's to get the required data out of my db and to do so I have to get these values out of that array Commented Apr 20, 2015 at 13:27

1 Answer 1

3

You are doing it wrong, you are saving object in an array and trying the get the data with array, it should be as

foreach($od as $key=>$odt)
{
    $odb= $odt->id;
    $sql = "SELECT `Name` FROM `detail` WHERE `ID` = '$odb'";
}
Sign up to request clarification or add additional context in comments.

10 Comments

I'm getting: Trying to get property of non-object
Check print_r($od) if there are some data in the array before doing the loop. more over you are using the same variable name row inside the first loop, if you want this way choose some other name $row_data = new stdClass ; and store like $row_data->id = $row["ID"]
There is data in the array
if you want this way choose some other name $row_data = new stdClass ; and store like $row_data->id = $row["ID"]
Do a print_r of the final array and share it to the question.
|

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.