Parsing Array And Object json Via PHP - Invalid argument supplied - php

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) {
{
...
}
}

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>";
}

CodeIgniter: Error on retrieving a single result row

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.

Solve New Line in JSON via PHP

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,
I Get Invalid argument supplied for foreach() Because of New Line in json in Some Rows. How Can I Solve This?
This One is Not Okey
[{"id":"26","answer":[{"option":"4","text":"Hello
"}],"type":"3"}]
AndThis One is Okey
[{"id":"26","answer":[{"option":"4","text":"Hello"}],"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);
?>
Replace your new line with \n before json decode:
$json = preg_replace('/\r|\n/','\n',trim($json));
$jason_array = json_decode($json,true);
The problem is invalid JSON format.
If your text content have multi lines, you should be use \n, not typing a enter.
[{"id":"26","answer":[{"option":"4","text":"Hello\n"}],"type":"3"}]
^^

How do I output the result from an sql query onto the screen in php

The following is the code I use to try and achieve this.
$con=mysqli_connect("localhost:8889","root","root","booksmart_properties");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else{
echo "we connected";
}
// Perform queries
$sql=mysqli_query($con,"SELECT * FROM ListedProperties");
$result=mysqli_fetch_assoc($sql);
echo $result['*'];
mysqli_close($con);
?>
I'm new to php and i'm sure it's something small, I just can't see it.
Use PHP foreach loop like this:
foreach($result as $key => $val)
{
print $val;
}
You are using
$result = mysqli_fetch_assoc($sql);
which will fetch a result row as an associative array
So you can call your result with a key to get a value.
example:
$result['id']
or to get all:
foreach($result as $key => $value)
{
print $value;
}

JSON returns [null,null] in my app

I want to send database records with a PHPH file via json to my app I am making with IntelXDK. Because I can't use PHP code with the Intel XDK, I needed to use JSON. I want to show the two records 'quote' and 'author' from my 'quotes' table on my screen. Someone helped me to this code but it just returns [null,null]instead of the two records I need.. I tried debugging but I am new to PHP so I can'get it to work.. Anyone who can help or sees an error in this code? Thanks!
PS: Yes I now there are already multiple questions asked on this subject by other people. I have read them all but none of them solves my question..
<?php
if(isset($_GET["get_rows"]))
{
//checks the format client wants
if($_GET["get_rows"] == "json")
{
$link = mysqli_connect("localhost", "xxxxx", "xxxxx", "xxxx");
/* check connection */
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
header("HTTP/1.0 500 Internal Server Error");
exit();
}
$query = "SELECT quote, author FROM quotes WHERE id = " . date('d');
$jsonData = array();
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
$row = $result->fetch_assoc($result);
// Create a new array and assign the column values to it
// You can either turn an associative array or basic array
$ret= array();
$ret[] = $row['quote'];
$ret[] = $row['author'];
//encode to JSON format
echo json_encode($ret);
}
else {
echo json_encode($ret);
}
/* close connection */
mysqli_close($link);
}
else
{
header("HTTP/1.0 404 Not Found");
}
}
else
{
header("HTTP/1.0 404 Not Found");
}
?>
You have a bug in fetch_assoc() function call - remove $result parameter. If you had error reporting enabling, you should see:
Warning: mysqli_result::fetch_assoc() expects exactly 0 parameters, 1 given
Just change it to:
$row = $result->fetch_assoc();
In javascript to parse this response, just do this:
var obj = JSON.parse(xmlhttp.responseText);
document.getElementById("quote").innerHTML = obj[0];
document.getElementById("author").innerHTML = obj[1];
I think your problem is with fetch_assoc()
Try to use that :
$row = mysqli_fetch_assoc($result);
instead of
$row = $result->fetch_assoc($result);
It's works for me with your example
change this
$row = $result->fetch_assoc($result);
to
$row = $result->fetch_assoc();
Just change it to:
$row = $result->fetch_assoc();
Updated:
response = JSON.parse(xmlhttp.responseText);
you can now access them independently as:
reponse.quote and response.author

Categories