简体   繁体   中英

recommended way of fetching results in database [OOP-PHP & MySQLi]

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM