php sql code, foreach warning - php

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';

Related

mysql fetch assoc array empty error

I want to output the fetched array onto the frontend. It works fine until the array returns as empty. It throws a PHP error that 'undefined variable $data on php line X'. I've looked for solutions though they have not fully suited what I have in mind. Please assist.
public function search($search) {
try {
$query = $this->connection->prepare ( "SELECT * FROM files WHERE number=$search ORDER BY id" );
$query->execute ();
while ( $row = $query->fetch ( PDO::FETCH_ASSOC ) ) {
$data [] = $row;
}
return $data;
} catch ( PDOException $e ) {
$e->getMessage ();
}
}
You are running your query wrong way.
The only proper way to add a variable into PDO query is to add it through a parameter. It is very important to understand that simply adding quotes around a variable is not enough and will eventually lead to innumerable problems, from syntax errors to SQL injections. On the other hand, due to the very nature of prepared statements, it's a bullet-proof solution that makes it impossible to introduce any problem through a data variable.
$this->connection->prepare ( "SELECT * FROM files WHERE number=? ORDER BY id" );
$query->execute ([$search]);
while to eliminate the error you should use the appropriate fetch mode. So the full code would be
public function search($search) {
$this->connection->prepare ( "SELECT * FROM files WHERE number=? ORDER BY id" );
$query->execute ([$search]);
return $query->fetchAll(PDO::FETCH_ASSOC);
}
note that you should never catch an error to report it

PHP Variable passed to each() is not an array

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

Strange Illegal string offset in foreach from mysqli_fetch_array() and mysqli_fetch_assoc()

I am just testing out a data set I am looking to return from the DB.
I am running this in command line mode. When I var_dump() the data, I can see data being returned, but when I try to traverse the array, which has duplicate data in it, I get the warning message below and can not print the array item.
I am sure to some that is obvious to some, but I do not know why this is happening. I am sure I am doing something wrong here...but what?
Consider:
$link = mysqli_connect("localhost","username","password","mydatabase") or die("Error " . mysqli_error($link));
$query = "SELECT * FROM citizen_application";
$execute = $query or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$result = $link->query($execute);
$data = mysqli_fetch_array($result); // also tried mysqli_fetch_assoc() and the issue persists
//display information:
//var_dump($data); //This show duplicates in the array returned???
foreach($data as $data_unit){
print_r($data_unit["dob"]."\r");
}
The warning in the logs:
Illegal string offset 'dob'
There seems to be no way to do this with a foreach() when running the script in command line mode. But I found a solution below that gives me what I was looking for:
while($data = mysqli_fetch_assoc($result)) {
print_r($data["dob"]."\n");
}
I noticed all the examples in the documentation where doing this way. I thought it was just a preference. It does not seem so. I hope this helps someone else, because this was quite irritating. You used to be able to do this easily with the previous mysql functions.
mysqli_fetch_array returns an array, you're traversing the array with the foreach, $data_unit will most likely be a single element and not an array... try just
foreach($data as $data_unit){
echo $data_unit."\r";
}
or use mysqli_fetch_assoc() and try
foreach($data as $fieldname => $data_unit){
echo "$fieldname = $data_unit\r";
}

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'];
...
}

help with php FOREACH loop

can some please tell me what's wrong with the bellow foreach php loop.
foreach ($_POST[sortlist] as $key => $value)
{
$sql = "UPDATE sortable
SET color_order = " . mysql_real_escape_string($key) . "
WHERE id = " . mysql_real_escape_string($value);
$result = mysql_query($sql) or die(mysql_error());
}
I keep getting warning: invalid argument suplied foreach() in ....
when i upload to server
Thanks
$_POST['sortlist'] is probably not an array. Try print_r($_POST) to see what do you have there.
Try change $_POST[sortlist] to $_POST['sortlist']
I'm assuming that $_POST[sortlist] is not an array. This is probably what you are trying to do:
foreach ($_POST as $varname => $varvalue) {
$sql = "update sortable set color_order = ".mysql_real_escape_string($varname)." where id = ".mysql_real_escape_string($varvalue);
$result = mysql_query($sql) or die(mysql_error());
}
Or if $_POST['sortlist'] is an array, try this:
foreach ($_POST['sortlist'] as $varname => $varvalue) {
$sql = "update sortable set color_order = ".mysql_real_escape_string($varname)." where id = ".mysql_real_escape_string($varvalue);
$result = mysql_query($sql) or die(mysql_error());
}
A tip: the error message refers to the foreach line. That only reads from one variable, $_POST[sortlist], which isn't modified inside the loop. So you can ignore all the SQL stuff; it's not relevant to your problem. Reduce the problem to the smallest possible piece of code that still has an error. That will help you solve it.
Don't use mysql_query , its very insecure and is deprecated .
start using mysqli_query, is not as safe as PDO but will be lot better.
Please, for the love of the internet, don't built an SQL query yourself. Use PDO.

Categories