Using Arrays in MySQLi And PHP - php

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();

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.
We then call the method 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.
We loop through our newly created $row array.

Related

How does PHP iterate over mysqli query results?

I'm learning to interact with a database in PHP. The code below works, but I do not understand how the loop iterates through $result.
<?php
require_once('./login.php');
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die("DIED: CONNECTION FAILED.");
$query= "SELECT * FROM table1";
$result = $conn->query($query);
if (!$result) die("DIED: QUERY FAILED.");
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$who = $row['WHO'];
$what = $row['WHAT'];
echo <<<_END
WHO: $who<br>
WHAT: $what<br>
_END;
}
$result->close();
$conn->close();
?>
I understand that while a $result element is available, it will be assigned to $row and processed in the loop. But how does the interpreter know to move to the next $result element?
The code even works when using a for loop instead, such as...
$row_count = $result->num_rows;
for($j = 0; $j < $row_count; $j++) {
$row = $result -> fetch_array(MYSQLI_ASSOC);
My question boils down to this: how does the interpreter know to use the next element in $result without needing something like $result[$j]?
The query returns a mysqli_result. Per the docs, this object is iterable http://php.net/manual/en/class.mysqli-result.php. So every time you call fetch_array(), the result object it is keeping track of which row it is currently on and returning the appropriate result, then moving forward one element in the result set. When there are no more results left, the function returns null which is evaluated as false thus terminating the loop.

How to return empty array or resultset from a query with mysqli_fetch_all()?

My PHP code:
function get_something() {
global $link;
$sql = "SELECT * FROM new";
$result = mysqli_query($link, $sql);
$names = mysqli_fetch_all($result, MYSQLI_ASSOC);
return $names;
}
What is my problem:
When my table new is empty, I get the following error:
mysqli_fetch_all() expects parameter 1 to be mysqli_result`
If it isn't empty everything is working fine.
I need to check if my database is empty and if it's not, I will call mysqli_fetch_all. Otherwise, my function should return an empty array.
How is this possible to do?
Use mysqli_num_rows($result) to check how many rows were returned from the query. But if table new doesn't exist, $result will be false so we have to check that $result is valid as well:
if ($result && mysqli_num_rows($result) > 0)
$names = mysqli_fetch_all($result, MYSQLI_ASSOC);
else
$names = array();
return $names;
mysqli_fetch_all($result, MYSQLI_ASSOC) generates an indexed array of associative arrays. When there are no rows found, it will deliver an empty array (which is what you want). It is absolutely pointless to call mysqli_num_rows(), so don't make your script do any unnecessary work.
Furthermore:
many developers will advise you not to make global declarations to pass variables in your custom function scope. Instead, pass the connection variable into your function as a parameter.
I always try to avoid declaring single use variables. For your case, $sql and $names will only be used/referenced once after being declared, so just don't declare them.
As a matter of personal preference, I recommend using OO syntax with mysqli functions because it is less verbose, but in my following snippet I'll leave it like your original post.
Suggested Code:
function get_something($link) {
if (!$result = mysqli_query($link, "SELECT * FROM new")) {
return []; // check mysqli_error($link) because your query failed
}
return mysqli_fetch_all($result, MYSQLI_ASSOC);
}

PHP JSON array from SQLite3

I'm trying convert data from a SQLite3 db to a JSON array by using PHP. I'm getting close, but I can't seem to get it right.
This is the error I'm getting:
PHP Warning: PDOStatement::fetchAll() expects parameter 1 to be long, object given in...
Thanks!
<?php
$db = new PDO('sqlite:example.db');
$result = $db->query('SELECT * FROM test');
$json = array();
$result->setFetchMode(PDO::FETCH_ASSOC);
while ($data = $result->fetchall($result)){
$x = $data['Time'];
$y = $data['Temperature'];
$json[] = array( (int($x)), (int($y)) );
}
?>
Got it working now. Thanks for your help!
<?php
$db = new PDO('sqlite:example.db');
$result = $db->query('SELECT * FROM test');
$datapie = array();
$result->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $result->fetch()) {
extract($row);
$datapie[] = array(floatval($Temperature), $Time);
}
$data = json_encode($datapie);
?>
Change:
$result->fetchall($result)
to:
$result->fetch()
You had two problems: the argument to fetchAll() should be a fetch mode, not a result. And fetchAll() returns all the rows, not one row at a time. If you're calling in a loop you use fetch().
PDO's fetchAll function, doesn't expect the query itself as a param.
Check it's manual here - you can leave it blank, or set the fetch mode:
http://php.net/manual/en/pdostatement.fetchall.php

Loading MySQL data into a PHP array

I am trying to load a list of IDs into a PHP array which I can loop through. The SQL query I am using returns 283 rows when I run it in PHPMyAdmin. However, when I run the following PHP script, it only returns a single row (the first row). How can I modify my code to include all the rows from the resulting SQL query in my PHP array?
Code:
//Get active listing IDs
$active = "SELECT L_ListingID FROM `markers`";
$active = mysql_query($active) or die(mysql_error());
if(is_resource($active) and mysql_num_rows($active)>0){
$row = mysql_fetch_array($active);
print_r($row);
};
Thanks,
Using mysql_fetch_array will return only the first row and then advance the internal counter. You need to implement it as part of a loop like the following to get what you want.
while($row = mysql_fetch_array($active)) {
// Your code here
}
Keep in mind that mysql_ functions are now also deprecated and slated to be removed in future version of php. Use mysqli_ functions or PDO.
In PDO it's rather straight forward:
$rows = $conn->query($active)->fetchAll();
See PDO::queryDocs and PDOStatement::fetchAllDocs.
With mysqli you would use mysqli_result::fetch_all and with PDO there's PDOStatement::fetchAll to fetch all rows into an array.
Code for mysqli
$sql = "SELECT L_ListingID FROM `markers`";
$result = $mysqli->query($sql);
if ($result !== false) {
$rows = $result->fetch_all();
}
with PDO it's nearly the same
$sql = "SELECT L_ListingID FROM `markers`";
$result = $pdo->query($sql);
if ($result !== false) {
$rows = $result->fetchAll();
}

Can we send result of mysql query as return value of function using php?

I m creating function that process query and pass it's return result back. so I used following code:
function test(){
$query = "select * from mytable where id=123";
$data = mysql_query($query) or die(mysql_error());
return $data;
}
$info = test();
is it possible and can i use $info to get values as $info[0],$info[1]..
take a look at mysql_fetch_array function.
This function lets you iterate a query result which is a resource and turn each row into an array.Therefore you should use a while loop to get all rows in a resource;
You're missing one vital part, returning the result of mysql_query() just returns a result pointer not the dataset. You should add mysql_fetch_array, mysql_fetch_assoc or mysql_fetch_row:
function test(){
$query = "select * from mytable where id=123 LIMIT 1";
$data = mysql_query($query) or die(mysql_error());
$result = mysql_fetch_row($data);
return $result;
}
$info = test();
now you can use $info[0], $info[1]. When using mysql_fetch_assoc you could use $info['fieldname'].
I also added LIMIT 1, since you're sending a long an ID, this probably is unique and after 1 result there is most likely nothing else to be returned.
You can do that, however it is better in my experience to keep the database stuff encapsulated, so you don't expose MySQL resources outside of the database context that then further need mysql_fetch_assoc() and the like on them.
I would use PDO there, and return the results of fetchAll(PDO::FETCH_ASSOC). That way, $info has the data it needs without needing to run further database functions on.
<?php
$link = mysql_connect('localhost', 'USERNAME', 'PASSWORD');
mysql_select_db('DB NAME', $link);
function test()
{
$result = mysql_query("select * from wp_options");
$data = array();
while($row = mysql_fetch_array($result))
{
$data[] = $row;
}
return $data;
}
echo "<pre>";
print_r(test());
echo "</pre>";
mysql_close($link);
?>

Categories