PHP Variable passed to each() is not an array - php

I have a class function below that caches a users information, what the error im getting is below
Warning: Variable passed to each() is not an array or object in C:\inetpub\wwwroot\application\base\classes\class.user.php on line 67
And the function is below.
public function cacheUserInfo() {
if (!$this->loggedIn())
return;
global $autoLoader;
$userQuery = $autoLoader->getLibrary('database')->query("SELECT motto,look,rank,last_login,block_newfriends FROM `users` WHERE `id` = '" . $_SESSION['user']['id']. "'");
$userRow = mysqli_fetch_array($userQuery);
while (list($var, $val) = each($userRow)) {
$_SESSION['user'][$var] = $val;
}
}
The query function on database library is just the ->query($sql) function for a MySQLi connection.
It was working one second now its not...
Why am I getting this error?

Why not just use
foreach($userRow as $key => $value)
It looks like your query might be returning null. If that's the case, maybe you should check if it is null first.

You don't need neither each nor foreach here.
All the code you need is just
$_SESSION['user'] =mysqli_fetch_assoc($userQuery);

Related

SQL SELECT returns array but PHP considers that as null

I'm selecting something in mySQL via PHP and that command returns some array (which is right), but when I put that returning SELECT inside if condition and ask if it is returning null than PHP says it is returning null (which is not right, because it is returning array)
include '../db.php'; // my config
function select($command) {
global $db;
$sql = "".$command."";
$sqlDone = $db -> prepare($sql);
$sqlDone -> execute();
$data = $sqlDone -> fetchAll();
return $data;
}
$select = "SELECT likes.ID, likes.ID_user, likes.ID_post FROM likes WHERE likes.ID_user = '53' AND likes.ID_post = '2'"
if (select($select) == null) { // goes throw this
print_r(select($select)); // returns array
} else {
echo 'not null';
}
I tried to use !is_null and it doesn't work anyway.
I tried to put that select command with same values directly inside phpmyadmin and it returns array, so I'm confused. Can you help me out?
PDO's fetchAll() returns an array, if there are no results, it returns an empty array (not NULL).
Just use empty()
$return = select($select); //put this into a variable, because if you don't, you'll query the database twice and may get different results.
if (empty($return)) { // goes throw this
print_r($return); // returns array
} else {
echo 'not null';
}
Side note, your function doesn't really do anything special. You could achieve the same thing with this:
$return = $db->prepare($select)->execute()->fetchAll();
If you used a PDO wrapper, it could be even shorter. For example, using my own wrapper GrumpyPDO, you would use
$return = $db->all($select);
then if you had variables to pass to the query, you would do
$select = "SELECT likes.ID, likes.ID_user, likes.ID_post FROM likes WHERE likes.ID_user = ? AND likes.ID_post = ?"
$return = $db->all($select, [$userid, $postid]);

Can't echo single value from array with a function in PHP

I am having trouble with PHP, where I populate an array with results from a MySQL query.
The problem is when I make a function to echo a certain element of the array, it's not working, where as without a function there are no errors.
Establish connection, perform query, store result in variable:
require_once("db.php");
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$query = "SELECT * FROM arlista";
$query_result = mysqli_query($conn, $query);
mysqli_close($conn);
$result_array = array();
I pass the query results to an array, then I want to query a single value from the array. The problem is if I use a function like this, this does not work. I can't get the element of the array to display in the browser.
function arlista($attr, $rownum){
while($row = mysqli_fetch_array($query_result)){
$result_array[$i] = $row[$attr];
$i++;
}
echo $result_array[$rownum];
}
arlista("ar",1);
However this works if I do not use a function. The browser is displaying the value.
while($row = mysqli_fetch_array($query_result)){
$result_array[$i] = $row["ar"];
$i++;
}
echo $result_array[1];
Could someone explain what is going wrong with the function or how do I fix it to work? Thank you!
The server is running PHP 5.6.19
Check your variable scoping. Your function has no variable $query_result. Turning on error reporting would also give you notices about the problem.
Using a global would work:
function arlista($attr, $rownum){
global $query_result, $result_array;
while($row = mysqli_fetch_array($query_result)){
$result_array[$i] = $row[$attr];
$i++;
}
echo $result_array[$rownum];
}
arlista("ar",1);
Hope that helps!
A function does not bring in the variables that you haven't defined inside the function, or passed in. Since you did not define or pass in $query_result and $result_array, the script would not work. However, without the function, that variable is defined, so the script will work. To make the function work, all you need to do is pass in the variable $query_result, $result_array or define it inside the function.
Edit: As Adam said, you can define in the function to use it as a global variable:
global $query_result, $result_array;
You need to pass $query_result as an argument to the function. You should also initialize the variables that you use within the function. But there's no real need for the $i variable, since you can use [] to push a new element onto an array.
function arlista($attr, $rownum, $query_result){
$result_array = array();
while($row = mysqli_fetch_array($query_result)){
$result_array[] = $row[$attr];
}
echo $result_array[$rownum];
}
arlista("ar", 1, $query_result);
You could also use global $query_result, but explicit arguments are generally better programming style.
You need to either pass $query_result as a function parameter, or define it as a global variable within the function.

My function returns false after moving to a new server

I got php fatal error after transfer server with php v5.6.19, before that I had no problem at all with following script
Fetch data from db table:
function get_department_list($mysqli)
{
$sql = $mysqli->query("SELECT * FROM `dept` ORDER BY `dept_id` ASC");
if($sql->num_rows > 0){
return $sql;
}else{
return false;
}
}
Populate data in HTML:
<ul class="department overflow-scroll text-center">
<?php
$shop = new Shop;
$depts = $shop->get_department_list($mysqli);
while($dept = $depts->fetch_object()){
echo '<li>'.$dept->dept_name.'</li>';
}
?>
</ul>
In the end I got an error:
Fatal error: Call to a member function fetch_object() on boolean in C:\xampp\htdocs\project\include\header.php on line 206
First, you are returning a boolean from your function. So, no wonder PHP says you so.
Second, you should keep the matters separated. a function that works with mysqli should keep all mysqli stuff inside. An return just an array, that can be used anywhere without the need to call mysqli functions again.
function get_department_list($mysqli)
{
$sql = $mysqli->query("SELECT * FROM `dept` ORDER BY `dept_id` ASC");
return $sql->fetch_all();
}
And then use not while but foreach
foreach ($depts as $dept) ...
Besides (and more for the people who may chance to land on this question looking for an answer to their question) you should always set proper error reporting for mysqli, like it shown in this answer
Update your while loop for that case when you get false from $shop->get_department_list() call
updated while like this check for $depts if any data then get $dept:
while($depts && $dept = $depts->fetch_object()){

Extract a mysql resource to php array?

My goal is to display the profile of a user. I have this function:
function get_profile($un) {
if($registerquery = $this->conn->query("SELECT * FROM table WHERE usr = '".$un."' ")){
return $profile = mysql_fetch_array($registerquery);
}
}
Then the display snippet:
<?php $profile = $mysql->get_profile($un);
foreach($profile as $key => $value){
echo "<span>".$key.': '.$value."</span><br />";
}
?>
But I get: "Warning: Invalid argument supplied for foreach() in..."
Help pls???
You need to see if the result was a success or not
if (gettype($result) == "boolean") {
$output = array('success' => ($result ? 1 : 0));
}
And you need to cycle through it if it's a resource type...
if (gettype($result) == "resource") {
if (mysql_num_rows($result) != 0 ) {
while ($row = mysql_fetch_assoc($result)) {
$output[] =$row;
}
}
}
I chopped up some real code that does basically everything pretty awful for you because I can't release it, sorry.
Check the result of get_profile, as it will return null if the query failed. You can't loop over null.
Be very very careful here. You are passing a raw string into the query function without escaping it and without using a parameterized query. Use mysql_escape_string around $un in your query. Your code flaw is called a sql injection attack.
Someone could pass their username as this
myusername'; update users set password = '';
And blank all passwords, thereby allowing themselves to access any account. Other similar shady attacks are equally likely.. you can basically do anything to a database with sql injection attacks.
I Agree with Anthony Forloney. The following code is just returning TRUE or FALSE depending on wether loading the $profile variable worked:
return $profile = mysql_fetch_array($registerquery);
You don't need $profile. You can eliminate it as such:
return mysql_fetch_array($registerquery);
The function will return the array and then when you call the function later you can load it's return value into $profile as you do with the following:
$profile = $mysql->get_profile($un);
Try this:
function get_profile($un) {
if($result = $this->conn->query("SELECT * FROM table WHERE usr = '".$un."' ")){
return $result->fetchArray(MYSQLI_ASSOC);
}
return array();
}
You're mixing MySQLi and MySQL functions and you can't do that. And, the last line of this code will return an empty array if the query does not work, rather than return null.
It is probably empty ($profile). Print the value of "count($profile)"
I have found that the easiest way to loop through mysql results is to use a while loop:
$select = "SELECT * FROM MyTable";
$result = mysql_query($select);
while ($profile = mysql_fetch_array($result)) {
$name = $profile['name'];
...
}

php sql code, foreach warning

I have the following code, not written bymyself, but I am wondering if you could spot anything wrong with it?
$query = "SELECT * from #__properties_type where published = 1 AND parent = ".$Category_id." OR parent = 0";
$db->setQuery( $query );
$types = $db->loadObjectList();
$nP = count($types);
$mitems[0]->id=0;
$mitems[0]->name='Type';
foreach ( $types as $item ) {
$mitems[] = $item;
}
It seems to work fine but sometimes I will see a random Warning: Invalid argument supplied for foreach() in etc/etc/etc/
Any ideas?
Your loadObjectList function seems to return a non-array sometimes, maybe when the SQL query fails.
Quick fix:
if (is_array($types))
foreach ( $types as $item ) {
$mitems[] = $item;
}
but you should look for the deeper cause why the function fails, and handle the error accordingly if there is one.
It probably means your $types variable isn't being set.
This will set a PHP warning off.
Unless $mitems[0] is predefined before your code snippet, there's no way PHP can know about $mitems[0] contains an object, hence $mitems[0]->id will throw an warning.
To solve this:
$mitems[0] = new YourObject();
$mitems[0]->id=0;
$mitems[0]->name='Type';

Categories