0

In the following snippet I understand that mysqli_fetch_row only works with an index of columns (0, 1, 2 etc), not the column name.

But I consider using column numbers/ordering bad practice (what if the order changes?).

How do I return a single row, then use the column name to get the data?

  $query = "Select * from users where UserEmail = '" . $UserEmail . "' LIMIT 1";

  $result = mysqli_query($connection, $query);

  $num_rows = mysqli_num_rows($result);
  $row = mysqli_fetch_row($result);

  $arr = $result->fetch_assoc();
  $log->lwrite('Works / value: ' . $row[0]);
  $log->lwrite('Does not work / value: ' . $arr['userID']);
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
11teenth
  • 1,853
  • 1
  • 15
  • 28
  • Use a `while` loop and and assign a variable to each column you want to reference. – Funk Forty Niner May 05 '17 at 01:59
  • But 'Limit 1' guarantees I only get one row...maybe that's where my mental model doesn't match reality:) – 11teenth May 05 '17 at 02:06
  • Yeah, that'd do it alright ;-) You can use an offset though LIMIT 1, 10 type of thing – Funk Forty Niner May 05 '17 at 02:06
  • ? So I need to do a loop even though there is one row? – 11teenth May 05 '17 at 02:07
  • No, not really but theoretically you can if you want to reference a certain row though. – Funk Forty Niner May 05 '17 at 02:08
  • Thank you for taking a look...but your answer still has me in the zone of confusion...:) I've looked at a lot of examples...this should be dead easy. Can you share a code snippet or a link? – 11teenth May 05 '17 at 02:10
  • welcome. Well there's the manual http://php.net/manual/en/mysqli-result.fetch-assoc.php and this Q&A on Stack [Understanding fetch_assoc()](http://stackoverflow.com/q/39267773/1415724) and [Mysqli fetch_assoc vs fetch_array](http://stackoverflow.com/q/21361184/1415724) which I hope will better answer your question. – Funk Forty Niner May 05 '17 at 02:16

1 Answers1

0

It doesn't work because fetch_row moves result's pointer to second row. And there is no second row because you have LIMIT in your query.

It is enough to just remove first fetch.

$query = "Select * from users where UserEmail = '" . $UserEmail . "' LIMIT 1";

$result = mysqli_query($connection, $query);

$arr = mysqli_fetch_assoc($result);
$log->lwrite('Does work now / value: ' . $arr['userID']);

Also mixing object oriented style with procedural style is considered bad practice. I used the second one here.

BartBiczBoży
  • 2,512
  • 2
  • 24
  • 33
  • Many thanks! I didn't realize my use of $row = mysqli_fetch_row($result); was interfering with what should be a simple syntax (to pull a specific field/column). – 11teenth May 05 '17 at 11:44