1

i am already aware of what and how to use fetch_array, fetch_assoc, fetch_row, fetch_object, and fetch_all(MYSQLI_NUM or MYSQLI_ASSOC or MYSQLI_BOTH).

but i just discovered and experimented that this code below worked for me, without using any fetch_* objects.

$sqli = $db->query("SELECT * FROM `tblSample`;");

foreach($sqli as $out) {
    echo "val1 => ", $out['0'], "<br />val2 => ", $out['1'], "<br />val3 => ", $out['2'];
}

as you can see, i wasn't using any fetch_ objects or so and for some reason, by using the foreach loop, i was still able to fetch the results of the query.

i tried doing so with while loop as how it worked with the foreach loop, but to no avail.

so i just wanted to ask, since i know that some other professional developers out there might've already encountered this way.

IS THIS RECOMMENDED ?. given that there was no fetch_ objects used ?. thank you

0

2 Answers 2

2

http://php.net/manual/en/pdo.query.php

There's nothing necessarily wrong with doing it that way, but in virtually all the code I've seen/written fetch modes are specified.

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

1 Comment

so am i. and personally, i regularly used fetch_ objects when retrieving query results. but if there is technically nothing wrong with this syntax. then at some of codes, it maybe useful to just do it this way. thanks anyway mate
0

The 'query' and similarly 'execute' are methods related to PDO (PHP Data Objects) which provides methods to interact with databases (not only MySQL but others like SQL Server, Oracle, SQLite and others) therefore it is good idea to learn how to use those methods (query, execute and many there are many more, check our PHP documentation for PDO).

The good thing about PDO is that if you'd like to do another project with different database the interaction with it would be pretty much the same for you, not only that if your existing project was migrated to another DB you just need to modify the connection string in the PDO object and your code would be the same (isn't that great?) in conclusion there is nothing wrong with using MYSQL objects (MYSQLI_NUM or MYSQLI_ASSOC or MYSQLI_BOTH) if you know you are only interacting with MYSQL database, but using the PDO gives a better scalability.

Comments

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.