0
$sql = "SELECT * FROM myTable WHERE name = fred "; // THIS LINE SHOULD NOT BE CHANGED
$result = mysqli_query($conn,$sql);
for ($res = array (); $res = $result->fetch_assoc(); $charDB[array_shift($row)] = $res);

then for example the 2nd result returned (just an example), I want to echo onto the screen. So something like $res[1] to get the 2nd row only.

The problem is at the moment it is treating the number in [] as the primary key for the row in the DB rather than the returned result number. Basically, I want to treat each row that is returned by its position in the array rather than the primary key in the db.

How would I achieve something like this? I have tried using fetch_object, fetch_array & fetch_row but none of them did what I wanted. I think it's something pretty basic?

Please let me know if it didn't make sense.

0

1 Answer 1

1

When you are calling $charDB[array_shift($row)] = $res in your for expression...

You are telling php to shift an element off the beginning of the row and use that first element value as the key for each stored row. You don't want this.

To correct your method, you don't need to make any additional function calls (like array_values()), you just need to let php index the elements for you as you store resultset rows to your $res variable.

Use this and everything will be as you desire:

for($charDB=[]; $row=$result->fetch_assoc(); $charDB[]=$row);

Please take notice to the variable name changes I've made versus your original code.

p.s. I'll assume that fred is single-quote wrapped in the query of your actual project.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.