While-loop in SQL only loops once - php

I have a rest service where I send a get request to a table in my database. I want to build an array with the response. I get the array-structure I want with this code but the problem is that it only loops once. Why is this? If I change the second $result to $result2 it returns false instead of the encoded array.
/**
* #param int $id
* #url periodicalitem
* #return string
*/
public function getPeriodicalItem($id){
$mysqli = $this->db-> getConnection();
$query = 'SELECT * FROM periodicalitem WHERE
periodical_id = ' . $id;
$result = $mysqli->query($query);
$arr = array();
while ($row = $result->fetch_assoc()) {
$query = 'SELECT * FROM inst_codes WHERE id = ' . $row['inst_code'] . '';
$result = $mysqli->query($query);
while ($row2 = $result->fetch_assoc()) {
if($row['inst_code'] == $row2['id'] ){
$arr[$row2['id']] = array('name' => $row2['name'],
'data' => $arr[$row2['id']]['data'] ? array_push($arr[$row2['id']]['data'], $row) : array($row) );
}
}
}
return json_encode($arr);
}

You are over-writing $result = $mysqli->query($query); inside the loop.
Use another variable
public function getPeriodicalItem($id){
$mysqli = $this->db-> getConnection();
$query = 'SELECT * FROM periodicalitem WHERE
periodical_id = ' . $id;
$result = $mysqli->query($query);
$arr = array();
while ($row = $result->fetch_assoc()) {
$query = 'SELECT * FROM inst_codes WHERE id = ' . $row['inst_code'] . '';
$result1 = $mysqli->query($query);
while ($row2 = $result1->fetch_assoc()) {
if($row['inst_code'] == $row2['id'] ){
$arr[$row2['id']] = array('name' => $row2['name'],
'data' => $arr[$row2['id']]['data'] ? array_push($arr[$row2['id']]['data'], $row) : array($row) );
}
}
}
return json_encode($arr);
}

The problem was that each iteration created a new array instead of appending the already existing one. Here is my working code.
/**
* #param int $id
* #url periodicalitem
* #return string
*/
public function getPeriodicalItem($id){
$mysqli = $this->db-> getConnection();
$query = 'SELECT * FROM periodicalitem WHERE
periodical_id = ' . $id;
$result = $mysqli->query($query);
//$arr = array();
while ($row = $result->fetch_assoc()) {
$row = array_map("utf8_encode", $row);
$query = 'SELECT * FROM inst_codes WHERE id = ' . $row['inst_code'] . '';
$result2 = $mysqli->query($query);
while ($row2 = $result2->fetch_assoc()) {
$row2 = array_map("utf8_encode", $row2);
$current = array(
'id'=>$row['id'],
'volume'=>$row['volume'],
'code' =>$row['code'],
'archive' => $row['archive']
);
if(!isset($arr[$row2['id']])){
$arr[$row2['id']] = array();
$arr[$row2['id']][] = array('name' => $row2['name'],
'prefix' => $row2['prefix'],
'show' => 'true');
}
if(isset($arr[$row2['id']]['data'])){
$arr[$row2['id']]['data'][] = $current;
}else{
$arr[$row2['id']]['data'] = array($current);
}
}
}
//$arr['2']['data'][] = array($current);
return json_encode($arr);
}

Related

Fetch data in array format in php & mysql

Fetch the data in array format like :
$value = array ("ABC","XYZ","OPQ");
$query = "SELECT * FROM designation_master";
$result = mysqli_query($mysqli, $query);
while ($row = mysqli_fetch_array($result)) {
$designation= $row["designation"];
}
Need Result:
$value = array ("ABC","XYZ","OPQ");
Fetch the designation column, and push it into an array with the syntax $array[] = $value.
$designation = [];
$query = "SELECT designation FROM designation_master";
$result = mysqli_query($mysqli, $query);
while ($row = mysqli_fetch_array($result)) {
$designation[] = $row["designation"];
}
print_r($designation);
if the "ABC","XYZ","OPQ" are the same field [designation], you can convert $designation to array.
$query = "SELECT * FROM designation_master";
$result = mysqli_query($mysqli, $query);
$designation = array();
while ($row = mysqli_fetch_array($result))
{
$designation[] = $row["designation"];
}

getting ERROR Unexpected '}' while printing json data in postman

I've wrote some code for a mobile app service, i need the output to be in json format, when i tested on postman i got this error: Unexpected '}', but when i print it in the form of an array it works fine, but in json format i got an issue, i don't understand why its showing the error, it looks fine to me, please check the code below.
thank you.
<?php
//$dbcon=mysqli_connect("localhost","root","","testing");
$username = $_REQUEST['username'];
if($username != '') {
$sql= "select * from test j,testing_user u where j.employer_id=u.id order by `date_added` desc limit 10";
$query= mysqli_query($dbcon,$sql);
$records = array();
$rows = array();
if(mysqli_num_rows($query) > 0) {
while($row = mysqli_fetch_object($query)) {
$rows['job_id'] = $row->job_id;
$rows['job_title'] = addslashes($row->job_title);
$rows['username'] = $row->username;
$rows['userid'] = $row->id;
$rows['email'] = $row->email;
$sql1 = mysqli_query($dbcon,"select * from test_company where company_id=".$row->company);
$row1 = mysqli_fetch_object($sql1);
$rows['companyname'] = $row1->name;
$rows['reccruitername'] = $row1->contact_name;
$rows['duration'] = $row->duration;
$skills = trim(addslashes(strip_tags($row->skills_prefered))).PHP_EOL;
$jobskills = utf8_encode($skills);
$rows['job_skills'] = str_replace(' ',' ',$jobskills);
$description = trim(addslashes(strip_tags($row->description))).PHP_EOL;
$desc = utf8_encode($description);
$rows['job_description'] = str_replace(' ',' ',$desc);
$sql2 = mysqli_query($dbcon,"select * from test_cities where code='".(int)$row->city. "'");
$crow = mysqli_fetch_object($sql2);
$sql3 = mysqli_query($dbcon,"select * from test_states where code='".$row->state."'");
$srow = mysqli_fetch_object($sql3);
$rows['joblocation'] = $crow->name.','.$srow->name;
$catsql = mysqli_query($dbcon,"SELECT name FROM test_business WHERE id = '" . (int)$row->category . "'");
$catrow = mysqli_fetch_object($catsql);
$exp = unserialize($row->experience);
$expsql = mysqli_query($dbcon,"SELECT exp_value FROM test_experience WHERE id = '" . (int)$exp['to'] . "'");
$experience = mysqli_fetch_object($expsql);
$rows['jobcategory'] = $catrow->name;
$rows['experience'] = $experience->exp_value;
$rows['zipcode'] = $row->zipcode;
$rows['areacode'] = $row->areacode;
if (preg_match('/[^A-Za-z0-9]+/', $row->job_type)) {
$rows['job_type'] = $row->job_type;
} else {
$params = unserialize($row->job_type);
//implode into a string
$param = implode(",",(array)$params);
$typequery = mysqli_query($dbcon,"SELECT * FROM test_type WHERE id IN ($param)");
$types = mysqli_fetch_object($typequery);
$rows['job_type'] = $types->job_type;
}
$applysql = mysqli_query($dbcon,"select * from testapp_jobs where job_id=".$row->job_id." and jobseeker_id=".$row->id);
$applyrow = mysqli_fetch_object($applysql);
if(!empty($applyrow)) {
$rows['job_status'] = '1';
} else {
$rows['job_status'] = '0';
}
$str = 'No of Vacancies: '.$row->num_jobs.PHP_EOL.'Hourly Pay:'.$row->hourly_pay.PHP_EOL.'Duration:'.$row->duration;
$rows['job_extrainfo'] = utf8_encode($str);
$rows['posted'] = $row->publish_on;
$records[] = $rows;
//print_r($records); die;
}
header('Content-Type: application/json');
echo '{"status":"1","message":"Jobs list found.","jobslist":'.json_encode($records).'}';
} else {
header('Content-Type: application/json');
echo '{"status":"0","message":"No Jobs found."}';
}
} else {
header('Content-Type: application/json');
echo '{"status":"0","message":"Required Fields Missing."}';
}
?>
Formatting Json manually can lead to confusion and is prone to errors.
A better solution is to use json_encode.
here are the lines you should change:
//...
echo json_encode(array('status' => '1', 'message' => 'job list found', 'joblist' => $records));
//...
echo json_encode(array('status' => 0, 'message' => 'No jobs found'));
//...
echo json_encode(array('status' => 0, 'message' => 'Required Fields Missing.'));

php mysql_fetch_assoc to json encode

I am Using Following code php array to encode Json
$query = "SELECT * FROM register WHERE email='$email'AND password='$password'AND status!='0'";
$result = mysql_query($query) or die('Errant query: ' . $query);
$numResults = mysql_num_rows($result);
if ($numResults > 0)
{
$data = array();
while ($row = mysql_fetch_assoc($result))
{
$data = $row;
}
echo json_encode($data);
}
IT gives Me result like
{"id":"26","fname":"Shankar","lname":"Salunkhe","category_name":"2"}
But I wanted To result like
{"SignIn":[{"id":"26","fname":"Shankar","lname":"Salunkhe","category_name":"2"}],"errors":[],"totalNumberOfRecords":1,"responseCode":"00000"}
How Can I do That
Or Suggest Me any other Method to do that
You need to do something like below to get the desired output.
$query = "SELECT * FROM register WHERE email='$email'AND password='$password'AND status!='0'";
$result = mysql_query($query) or die('Errant query: ' . $query);
$numResults = mysql_num_rows($result);
if ($numResults > 0)
{
$data = array();
while ($row = mysql_fetch_assoc($result))
{
$data[] = $row;
}
$result = ['SignIn' => $data, 'totalNumberOfRecords' => $numResults, 'errors' => [], 'responseCode' => 0000];
echo json_encode($result);
exit;
}
You have to store all information in a array to get what you want.
For example,
$data = array("id" =>"26","fname"=>"Shankar","lname"=>"Salunkhe","category_name"=>"2");
$array = array("SignIn" => $data, "errors" => [], "totalNumberOfRecords" => 1,"responseCode" => "00000");
$result = json_encode($array);

select query through function.. to fetch data from db

How do I fetch data from db using select query in a function?
Example
function ec_select_query($student, $row = '', $fields=array()) {
$qry = "SELECT * FROM student";
$qry = mysql_query($qry);
while($row = mysql_fetch_assoc($qry)){}
return $row;
}
If you want to return all rows then first save it in an array in while loop then return this array.
function ec_select_query($student,$row='',$fields=array())
{
$qry = "SELECT * FROM student";
$qry = mysql_query($qry);
$result = array();
while($row = mysql_fetch_assoc($qry))
{
$result[] = $row;
}
return $result;
}
Its is running code. Modify it according to your needs
$con = mysql_connect('localhost','root','') or die("Unable to connect to MySQL");
mysql_select_db('demo', $con) or die("Database not found");
function ec_select_query($student)
{
$query = "SELECT * FROM $student";
$result = mysql_query($query);
$row = array();
$getData = array();
while($row = mysql_fetch_array($result))
{
$getData[]=$row;
}
return $getData;
}
$information = ec_select_query('accountplans');
echo "<pre>"; print_r($information); die;
Try it
function select_query($table, $where=array(),$fields=array()){
$select_fields = $table."*";
if(!empty($fields) && is_array($fields)){
$select_fields = implode(",", $fields);
}
$sql = "select ".$select_fields." from ".$table." where 1=1 ";
if(!empty($where) && is_array($where)){
foreach ($where as $key => $value) {
$sql .= " AND ".$value;
}
}
$query = mysql_query($sql);
$result = array();
while($row = mysql_fetch_assoc($result)){
$result[] = $row;
}
return $result;
}
Call Function
$fields = array("id","name","city");
$where = array('name = "abc"','city like "aaa"');
$students = select_query("studendts", $where, $fields);
This code might help you :
function ec_select_query($student,$row='',$fields=array())
{
$q = "SELECT * FROM student";
$q = mysql_query($qry);
while($row = mysql_fetch_array($qry))
{
return $row;
}
}
It is easiest way to produce entire data in array
function db_set_recordset($sql) {
$qry = mysql_query($sql);
$row= array();
while($out = mysql_fetch_assoc($qry)) {
$row[] = $out;
}
return $row;
}
$qry = "SELECT * FROM student";
$result = db_set_recordset($qry);

Passing multiple dimension array in PHP

MySql query returns me a multi-dimensional array :
function d4g_get_contributions_info($profile_id)
{
$query = "select * from contributions where `project_id` = $profile_id";
$row = mysql_query($query) or die("Error getting profile information , Reason : " . mysql_error());
$contributions = array();
if(!mysql_num_rows($row)) echo "No Contributors";
while($fetched = mysql_fetch_array($row, MYSQL_ASSOC))
{
$contributions[$cnt]['user_id'] = $fetched['user_id'];
$contributions[$cnt]['ammount'] = $fetched['ammount'];
$contributions[$cnt]['date'] = $fetched['date'];
$cnt++;
}
return $contributions;
}
Now I need to print the values in the page where I had called this function. How do I do that ?
change the function like this:
while($fetched = mysql_fetch_array($row, MYSQL_ASSOC))
{
$contributions[] = array('user_id' => $fetched['user_id'],
'ammount' => $fetched['ammount'],
'date' => $fetched['date']);
}
return $contributions;
Then try below:
$profile_id = 1; // sample id
$result = d4g_get_contributions_info($profile_id);
foreach($result as $row){
$user_id = $row['user_id']
// Continue like this
}

Categories