-5

I have the code below and was hoping someone could clarify what the highlighted/commented/obvious lines was doing please

$result = mysqli_query($db, "SELECT * FROM `tblName` WHERE `id`='" . mysqli_real_escape_string($db, $_GET['id']) . "' LIMIT 0, 1");
$row = mysqli_fetch_assoc($result);
foreach($row as $name => $value) {  // THIS ONE I NEED HELP WITH
    ...
}

Does it basically say "for each column..." - this is where I get stuck

16
  • Hardly simple terms! Let's assume I need to explain it to my mother or child.... or at least a colleague who understands databases but not PHP Commented Dec 27, 2016 at 20:31
  • 1
    @JeremyHarris that hardly is going to help OP. "This question concerns how it works under the bonnet" OP is not looking for that Commented Dec 27, 2016 at 20:31
  • 1
    You're right, it basically says "in the row of data returned, take each column as $name and it's value as $value". Commented Dec 27, 2016 at 20:32
  • 2
    Read the documentation. It always helps. Commented Dec 27, 2016 at 20:34
  • 1
    @pee2pee I have a massive answer written, but the question was closed (in fairness I started that close vote). Maybe it will help: pastebin.com/f5hXdgD4 Commented Dec 27, 2016 at 21:05

1 Answer 1

2

It's a foreach loop. So it can be translated to...

for every object in the $row variable, assign that object to the new variable $name, with its corresponding value as $value

That will loop N times, where N is the number of rows returned. Each time the loop is iterated, the $name and $value variables are re-initialized to the new row's contents.

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

4 Comments

Just wanted to be sure it included the column names rather than just records
Yes. That's what adding the => does.
Will accept this as answer as soon as I can
That's not at all "what the => does", $name will contain the row's numeric index in the result set, and $value will contain the row itself. Whether or not the row includes the column names depends entirely on which fetch function is called. In this case calling fetch_assoc is what gets the column names as keys in the $row array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.