1

What I am trying to do here is write a code to update my database automatically; for those derived attributes. Here is the part of the code where I try to grab all the rows in an array:

include("dbConnect.php");
$results = $mysqli->query("SELECT * from nw_order;");
if($results) 
    foreach($results as $hgh)
        $resultArray[] = $results->fetch_row();

else
    die("Query failed");

foreach($resultArray as $row) {
    foreach($row as $field)
        print $field." ";
    print "<br>";
}

The foreach grab only even numbered rows for some reason. Also, trying to substitute foreach with while gives me memory shortage error. I am so tired I will check in tomorrow. If you can help me out that will be awesome.

4
  • it's impossible to help you out without data Commented Jan 14, 2016 at 19:09
  • 1
    Why do you loop through the $results variable to fill up the $resultArray variable to loop through it again? Commented Jan 14, 2016 at 19:15
  • 1
    that's NOT how you fetch rows from a result. the foreach() grabs one row, then you simply throw away $hgh and fetch ANOTHER row with the fetch_row() call. if you insiste on foreach, then at least change it to foreach(...) { $resultArray[] = $hgh; } Commented Jan 14, 2016 at 19:16
  • Ok. That makes sense. I knew this was a bit off somehow. Commented Jan 15, 2016 at 4:02

1 Answer 1

1
include("dbConnect.php");
$results = $mysqli->query("SELECT * from nw_order;");
$rows = array();
if($results) {
  $rows = $results->fetch_all();
}

foreach($rows as $row) {
  foreach($row as $field) {
        echo $field." ";
  }
  echo "<br>";
}

But actually I'd rather neither "SELECT * " nor print all fields regardlessly. I find things more maintainable when they are more explicit.

Sign up to request clarification or add additional context in comments.

4 Comments

I'd suggest that if you clean/improve his code, do it completely. One should use brackets for every conditional or loop statement. Someday someone else mantains this code and in a hurry adds another line to the if($results)-block and wonders why its not working. And another post like this will be born :).
:D yes these posts keep being born all the time
Ok. Thank you. This looks nice
By the way, can you explain why using while($results) causes memory shortage?

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.