Reputation: 6320
Following is a typical OOP way to Connect and Retrive data from MySQL database using MySQLi and PHP. Now I am a little bit confused on using the pure PHP arrays at this example:
Can some one please let me know if the $result
is array or not? I mean in
$result = $mysqli_coonect->query($sql);
if so how come we didn't use the array()
function or []
to create it?!
same thing happening with $row
at:
$row = $result->fetch_assoc()
I am asking this because in order to load $row;
to $results[]
at $results[] = $row;
we declared the $results
as an array explicitly before the while()
how come we are not doing this for other or vice versa?!
<?php
$mysqli_coonect = new mysqli($host_name, $user_name, $pass_word, $database_name, $port);
$sql = "SELECT * FROM books WHERE id <= 10";
$result = $mysqli_coonect->query($sql);
if (($result) && ($result->num_rows > 0))
{
$results = array();
while ($row = $result->fetch_assoc())
{
$results[] = $row;
}
$result->free();
}
$mysqli_coonect->close();
Upvotes: 2
Views: 92
Reputation: 517
Always refer to the PHP documentation. It's great and you can easily find what you want.
http://php.net/manual/en/mysqli.query.php states that a query will return mixed
in this case meaning either false
if the query failed or mysqli_result
object of the query was successful.
Getting down to business
$result = $mysqli->query($query)
returns a mysqli_result
object. This means that $result
is now an object.fetch_assoc
from our newly created $result
(mysqli_result) object and store the results of the method in the variable $row
(which if the method is successful will be an array). If you look at what fetch_assoc
returns (http://php.net/manual/en/mysqli-result.fetch-assoc.php) you see that it returns an array
.Upvotes: 3