CodeIgniter: Error on retrieving a single result row - php

Good day!
I have this code in getting an employee's information. (single result)
controller:
public function get_employee_info()
{
$id = $this->input->post("id");
$data["emp_default_info"] = $this->My_model->get_single_result("SELECT * FROM employees WHERE id = '$id' ");
$this->load->view("employee_info_view", $data);
}
model:
public function get_single_result($query_statement)
{
$query = $this->ECS_DB->query($query_statement);
return $query->row_array();
}
view:
foreach ($emp_default_info as $row)
{
echo $id = $row->id;
echo "<br/>".$lname = $row->lname;
echo "<br/>".$fname = $row->fname;
echo "<br/>".$mname = $row->mname;
}
ERROR:
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
All I want to do is to return the specific employee's info. I don't know why I got this error.
Any help please?
Thank you!

Try This
Controller :
public function get_employee_info() {
$id = $this->input->post("id");
$data["emp_default_info"] = $this->My_model->get_single_result($id);
$this->load->view("employee_info_view", $data);
}
Model :
public function get_single_result($id)
{
$this->db->where("id",$id);
$query = $this->db->get("employees");
return $query->result();
}
View :
foreach ($emp_default_info as $row)
{
echo $id = $row->id;
echo "<br/>".$lname = $row->lname;
echo "<br/>".$fname = $row->fname;
echo "<br/>".$mname = $row->mname;
}

A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Its because $emp_default_info is either null or false or argument is not array
So what you can do is as follows:
Either correct your model code :
public function get_single_result($query_statement)
{
$query = $this->ECS_DB->query($query_statement);
$row = $query->row_array();
if (isset($row)){
return $row;
}
return array();
}
OR
validate in view whether its array
Also $emp_default_info is array because you called row_array();, you can't access like $row->id
if(is_array($emp_default_info) && !empty($emp_default_info))
{
foreach ($emp_default_info as $row)
{
echo $id = $row['id'];
echo "<br/>".$lname = $row['lname'];
echo "<br/>".$fname = $row['fname'];
echo "<br/>".$mname = $row['mname'];
}
}else{
echo "Employee Information not found";
}
We can regenerate this error like this for example
$ php -r 'foreach(null as $e){}'
PHP Warning: Invalid argument supplied for foreach() in Command line code on line 1
/*false OR FALSE*/
$ php -r 'foreach(false as $e){}'
PHP Warning: Invalid argument supplied for foreach() in Command line code on line 1
/* Not array */
$ php -r 'foreach("somestring" as $e){}'
PHP Warning: Invalid argument supplied for foreach() in Command line code on line 1

You do not have use foreach as row_array returns array of specific row only. check documentation for further information
echo $id = $row['id'];
echo "<br/>".$lname = $row['lname'];
echo "<br/>".$fname = $row['fname'];
echo "<br/>".$mname = $row['mname'];

row_array() returns array of results.
View:
echo $id = $row['id'];
echo "<br/>".$lname = $row['lname'];
echo "<br/>".$fname = $row['fname'];
echo "<br/>".$mname = $row['mname'];

You can try with minimum no. of lines.
public function get_employee_info()
{
$id = $this->input->post("id");
$this->db->where('id', $id);
$q = $this->db->get('employees');
$row = array_shift($q->result_array());
echo $row['fname']; //and so on
}
So no need to add code for fetching one record in Model as you did. Its already there in parent model.

Function row_array returns The requested row or NULL if it doesn’t exist.
So if your query fails NULL will be stored in $data["emp_default_info"].
And you need to pass variable of type array/object to foreach, in your case it is might be NULL.Try your output query at database site(workbench or phpmyadmin) first.
If query success it will return a row(single row).So you can loop like
foreach($emp_default_info as $val)
{
echo $val;
}
because it returns only one row you dont need to use a loop.you can access
it by array index directly as $emp_default_info['id'] etc.

Related

When using foreach with while loop it's showing error in php

I have a PHP query for select data from database its working. and I'm user foreach for print data out of while loop. And it's also working but when I'm trying to select same value with foreach it's showing error. I check my code and i right.
Code id Here
<?php
$sql = "SELECT * FROM user WHERE userid = '205'";
$result = mysqli_query($con_db, $sql);
//Creating array
$userdata = array();
if (mysqli_num_rows($sql) > 0) {
while($row = mysqli_fetch_assoc($sql)) {
$userdata[] = $row;
}
}else{
echo "No Result Found";
}
//Here I'm Showing Data
foreach($userdata as $user) {
echo $user["useremail"];
}
?>
When i'm Run This Code like
<?php
foreach($userdata as $user) {
echo "<p>".$user['userloginemail']."</p>";
}
echo "<br><br>";
foreach($userdata as $userdata) {
echo "<p>".$user['userloginemail']."</p>";
}
?>
This is Result
example#gmail.com
//This is Error
Notice: Undefined variable: user in
C:\xampp\htdocs\ats\recruiters\recruiter.php on line 111
Warning: Invalid argument supplied for foreach() in
C:\xampp\htdocs\ats\recruiters\recruiter.php on line 111
This is not sollution but suggestion that this is silly mistakes that developers do and makes bigger problem So it is good if you learn own self.
Notice: Undefined variable: sqldata in
This error mean by That The Defined variable by you is not defined or not a valid .
So First Learn this error HERE
And
Warning: Invalid argument supplied for foreach() in
This mean by The Value Supplied in foreach is not valid as per foreach requirement
So kindly check Whetther array is Valid or not by print_d()
Because there is no array or variable defined as $sqldata
I think you want this
<?php
foreach($userdata as $sqldata) {
echo "<p>".$sqldata['userloginemail']."</p>";
}
echo "<br><br>";
foreach($userdata as $sqldata) {
echo "<p>".$sqldata['userloginemail']."</p>";
}
?>
$sqldata not declared!
Try this
<?php
foreach($userdata as $user) {
echo "<p>".$user['userloginemail']."</p>";
}
echo "<br><br>";
foreach($userdata as $user) {
echo "<p>".$user['userloginemail']."</p>";
}
?>
The issue is that you are not passing $result to fetch the data.
$sql is just the query string not the result that comes out from the query
Do this instead
if (mysqli_num_rows($result) > 0) {//pass $result
while($row = mysqli_fetch_assoc($result)) {//pass $result
$userdata[] = $row;
}
} else {
echo "No Result Found";
}
Also make sure to check if array is not empty. Use empty()
if(!empty($userdata)){
//then loop
}
Check the second foreach loop you are declaring $userdata and accessing with $user.
Your code:
foreach($userdata as $userdata) {
echo "<p>".$user['userloginemail']."</p>";
}
Correct Code:
foreach($userdata as $user1) {
echo "<p>".$user1['userloginemail']."</p>";
}

Parsing Array And Object json Via PHP - Invalid argument supplied

I'm Parsing This json Array and I Want to Take type Object and Put That in New Column type2, and This is one Row of My json Rows,
Why I Get This Warning for Some Rows? Warning: Invalid argument supplied for foreach() in C:\wamp64\www\json\json.php on line 18
[{"id":"26","answer":[{"option":"3","text":"HIGH"}],"type":"3"},
{"id":"30","answer":[{"option":"3","text":"LOW"}],"type":"3"},
{"id":"31","answer":[{"option":"3","text":"LOW"}],"type":"3"}]
And This is My Code:
<?php
$con=mysqli_connect("localhost","root","","array");
mysqli_set_charset($con,"utf8");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT `survey_answers`,us_id FROM `user_survey_start`";
if ($result=mysqli_query($con,$sql)){
while ($row = mysqli_fetch_row($result)){
$json = $row[0];
if(!is_null($json)){
$jason_array = json_decode($json,true);
// type2
$type = array();
foreach ($jason_array as $data) {
if (array_key_exists('type', $data)) {
// Now we will only use it if it actually exists
$type[] = $data['type'];
}
}
// lets check first your $types variable has value or not?
if(!empty($type)) {
$types= implode(',',$type); /// implode yes if you got values
}
else {
$types = ''; //blank if not have any values
}
$sql2="update user_survey_start set type2='$types' where us_id=".$row[1];//run update sql
echo $sql2."<br>";
mysqli_query($con,$sql2);
}
}
}
mysqli_close($con);
?>
That is Strang, Why Some Row Has Output And Some Rows Hasn't Any Output, Those Json Type Are Same.
I Find The Problem, Because Some json entered, I Mean.
This One Has Warning: Invalid argument supplied for foreach()
[{"id":"26","answer":[{"option":"4","text":"Hello
"}],"type":"3"}]
And This One is Okey
[{"id":"26","answer":[{"option":"4","text":"Hello"}],"type":"3"}]
How Can I Fix The Problem?
you also try is_array before your for each loop
if (is_array($jason_array))
{
foreach ($jason_array as $data) {
{
...
}
}

Pass mysql_query results to foreach

I used the following code to to get list of users facebook friends and ccheck it against users in an app database. This code would return the users of the app, who are Facebook friends of the user.
$friends_set = '(';
foreach($friends["data"] as $value) {
$friends_set .= $value['id'].',';
}
$new_set = preg_replace('/,$/',')',$friends_set);
$res = mysql_query("SELECT * from user AS u, upload AS up WHERE u.fb_id IN $new_set AND u.fb_id=up.user_id") or die(mysql_error());
while($row = mysql_fetch_array($res)) {
echo $row['fb_id']. "". $row['first_name'];
echo "<br>";
}
$data['top_friends']=$res;
$this->load->view('myview');
This code works. It is in a controller of my codeigniter application and it successfully echos the correct data onto the page.
However now I need to print the result of the query in a for each statement in my view like this:
<?php foreach ($top_friends as $me) : ?>
<div >
<p><?php echo $me['first_name']; ?></p>
<?php endforeach; ?>
However when I try getting the query results in the view using the for each it doesn't work.
How do i fix this?
You could try it the codeignitor way, Create a model function say get_top_friends and i assume that you are passing a comma separated string as argument like $fb_id = '45,65,78,89'. Say facebook_model is the name of the model then :
class Facebook_model extends CI_Model{
//other functions and constrcutor here
//function to get the top friends
function get_top_friends($fb_id){
$fbId = explode(",",$fb_id)
$this->db->select('*');
$this->db->where_in('fb_id',$fbId);
$this->db->order_by('points','desc');
$this->db->limit(10);
$query = $this->db->get('user');
if ($query->num_rows() < 1) return FALSE;
return $query->result_array();
}
}
And make change in your code as below:
$friends_set = '';
foreach($friends["data"] as $value) {
$friends_set .= $value['id'].',';
}
$new_set = preg_replace('/,$/',')',$friends_set);
$res = $this->facebook_model->get_top_friends($new_set);
$data['top_friends']=$res;
$this->load->view('myview',$data);
And now in view you can try
foreach ($top_friends as $me){
echo $me['first_name'];
}
[Updated for user ]
If you want to do it as in your question : then try,
$result = array();
while($row = mysql_fetch_array($res)) {
$result[] = $row;
}
$data['top_friends']=$result;
$this->load->view('myview',$data);//pass data to view

Foreach invalid argument

I am creating a search function that will allow a user to search for a house in my database by postcode initially. The function can be seen below, when the function is executed and finds a true statement I get no errors however when I execute the search and I get a no fields been returned I am left with this error:
No Records Found
Warning: Invalid argument supplied for foreach() in /Applications/XAMPP/xamppfiles/htdocs/undergradpad/search.php on line 26
I want it to display No Records Found however I don't know how I should correct the above error.
search.php:
<table width="500" border="1" cellpadding="5">
<tr>
<th width="16" scope="row">id</th>
<td width="95">bedrooms</td>
<td width="140">description</td>
<td width="104">roadname</td>
<td width="71">postcode</td>
</tr>
<?php
require("classes/class.House.inc");
$obj = new House();
$obj->search($_POST['term']);
foreach($obj->data as $val){
extract($val);
?>
<tr>
<td scope="row"><?php echo $id; ?></td>
<td><?php echo $bedrooms; ?></td>
<td><?php echo $description; ?></td>
<td><?php echo $roadname; ?></td>
<td><?php echo $postcode; ?></td>
</tr>
<?php
}
?>
</table>
classes/class.House.inc:
<?php
include("connect/class.Database.inc");
class House extends Database {
public function read(){
$query = "SELECT * FROM houses";
$result = $this->mysqli->query($query);
$num_result = $result->num_rows;
if($num_result > 0){
while($rows =$result->fetch_assoc()){
$this->data[]=$rows;
//print_r($rows);
}
return $this->data;
}
}
public function search ($term){
$query = "SELECT * FROM houses WHERE postcode like '%".$this->mysqli->real_escape_string($term)."%'";
$result = $this->mysqli->query($query);
$num_result = $result->num_rows;
if($num_result > 0){
while($rows =$result->fetch_assoc()){
$this->data[]=$rows;
//print_r($rows);
}
return $this->data;
} else{
echo 'No Records Found';
}
}
}
?>
in this variable ($obj->data) you just get null data.
First check if not empty and than use foreach and don't have error if yout method don't return null data
just check if (!empty($obj->data)
{
foreach code
}
$obj is a House object. It has no $data property, even if you use it. The search method sets this property, but only if records are found. If no records are found, the method echoes a value.
I would change it like this: Instead of echoing an error, make the method return false:
public function search ($term){
$query = "SELECT * FROM houses WHERE postcode like '%".$this->mysqli->real_escape_string($term)."%'";
$result = $this->mysqli->query($query);
$data = false;
$num_result = $result->num_rows;
while($row =$result->fetch_assoc()){
$data[]=$row;
}
return $data;
}
Now, the function return an array of false if there is no data. You can now use it like this:
$obj = new House();
if ($data = $obj->search($_POST['term']))
{
foreach($obj->data as $val){
extract($val);
}
}
The changes I made:
- No longer set data as a property, since you also return it. You can still do that, if you like, but I think it's confusing to do both.
- Return false if there's no data.
- Change the variable rows to row, since it only contains one row.
if(is_array($obj->data)){
foreach code
}
else{
no record
}

php string error

i am experiencing some weird behaviour here.
i am using the following code to reference the facebook api.
$query = "SELECT msg, user_id, comment_time FROM comments WHERE aid = '$aid' ORDER BY comment_time DESC";
$result = mysql_query($query) or die("ERROR: $query.".mysql_error());
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_object($result)){
$uidval = $row->user_id;
$posterInfo = $facebook->api_client->users_getInfo($uidval, array('name', 'pic_square_with_logo', 'profile_url'));
$nameuser = $posterInfo[0]['name']; //this is line 50
$pic = $posterInfo[0]['pic_square_with_logo'];
$profile_url = $posterInfo[0]['profile_url'];
echo '<img src="'.$pic.'" />';
echo ''.$nameuser.'';
echo '<br>';
echo $row->comment_time;
echo '<br>';
echo $row->msg;
}
}
it gives me this error:
Fatal error: Cannot use string offset as an array in /home/amitver/public_html/roadies/comments.php on line 50
but surprisingly i am using the exact same code successfully at the top of my page. why this weird behaviour. this is the code at the top of page:
//connect to fB
$uid = $user_id;
$userInfo = $facebook->api_client->users_getInfo($user_id, array('name', 'pic_square'));
$nameuser = $userInfo[0]['name'];
$pic = $userInfo[0]['pic_square'];
I think that sometimes theusers_getInfo is returning an array, while other times it is returning a string. Probably it only returns a simple string if only one result is available.
Try this:
$nameuser = ($posterInfo[0]) ? $posterInfo[0]['name'] : $posterInfo['name'];
this will happen if $posterInfo is actually an empty string ('').
can you var_dump($posterInfo) in the loop and check what it's doing...

Categories