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

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

Related

How to get value from mssql DB in PHP

Firstly I got the workers name from BIRTHDAYS and then want to get e-mail address from USERS.There is no problem to take workers name's from Table1 but when I try to get the e-mail addresses the db returns me NULL.My DB is mssql.
<?php
include_once("connect.php");
$today = '05.07';
$today1 = $today . "%";
$sql = "SELECT NAME FROM BIRTHDAYS WHERE BIRTH LIKE '$today1' ";
$stmt = sqlsrv_query($conn,$sql);
if($stmt == false){
echo "failed";
}else{
$dizi = array();
while($rows = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
$dizi[] = array('NAME' =>$rows['NAME']);
$newarray = json_encode($dizi,JSON_UNESCAPED_UNICODE);
}
}
foreach(json_decode($newarray) as $nameObj)
{
$nameArr = (array) $nameObj;
$names = reset($nameArr);
mb_convert_case($names, MB_CASE_UPPER, 'UTF-8');
echo $sql2 = "SELECT EMAIL FROM USERS WHERE NAME = '$names' ";
echo "<br>";
$stmt2 = sqlsrv_query($conn,$sql2);
if($stmt2 == false)
{
echo "failed";
}
else
{
$dizi2 = array();
while($rows1 = sqlsrv_fetch_array($stmt2,SQLSRV_FETCH_ASSOC))
{
$dizi1[] = array('EMAIL' =>$rows['EMAIL']);
echo $newarray1 = json_encode($dizi1,JSON_UNESCAPED_UNICODE);
}
}
}
?>
while($rows1 = sqlsrv_fetch_array($stmt2,SQLSRV_FETCH_ASSOC))
{
$dizi1[] = array('EMAIL' =>$rows['EMAIL']);
echo $newarray1 = json_encode($dizi1,JSON_UNESCAPED_UNICODE);
}
you put in $rows1 and would take it from $rows NULL is correct answer :)
take $rows1['EMAIL'] and it would work
and why foreach =?
you can put the statement in while-loop like this:
while ($rows = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$names = $rows['NAME'];
$sql2 = "SELECT EMAIL FROM USERS WHERE NAME = '$names' ";
echo "<br>";
$stmt2 = sqlsrv_query($conn, $sql2);
if ($stmt2 == false) {
echo "failed";
} else {
$dizi2 = array();
while ($rows1 = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC)) {
$dizi1[] = array('EMAIL' => $rows1['EMAIL']);
echo $newarray1 = json_encode($dizi1, JSON_UNESCAPED_UNICODE);
}
}
}

How do i verify query from mysql database before outputing record

In my code am trying to verify if query is true before outputing result i have tried:
require("init.php");
if(empty($_GET["book"]) && empty($_GET["url"])) {
$_SESSION["msg"] = 'Request not valid';
header("location:obinnaa.php");
}
if(isset($_GET["book"]) && isset($_GET["url"])) {
$book = $_GET['book'];
$url = $_GET['url'];
$drs = urldecode("$url");
$txt = encrypt_decrypt('decrypt', $book);
if(!preg_match('/(proc)/i', $url)) {
$_SESSION["msg"] = 'ticket printer has faild';
header("location:obinnaa.php");
exit();
} else {
$ql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$count = mysqli_num_rows($sql);
if($count < 1) {
$_SESSION["msg"] = 'Transation has oready been made by a customer please check and try again';
header("location:obinnaa.php");
exit();
}
while($riow = mysqli_fetch_assoc($ql)) {
$id = $riow["id"];
$tqty = $riow["quantity"];
for($b = 0; $b < $tqty; $b++) {
$run = rand_string(5);
$dua .= $run;
}
}
$sql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$split = $dua;
$show_plit = str_split($split, 5);
$b = 0;
while($row = mysqli_fetch_assoc($sql)) {
$id = $row["id"];
$qty = $row["quantity"];
$oldB = $b;
$am = " ";
for(; $b < $oldB + $qty; $b++) {
$am .= "$show_plit[$b]";
$lek = mysqli_query($conn, "UPDATE books SET ticket='$am' WHERE id=$id");
}
if($lek) {
$adr = urlencode($adr = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
$ty = encrypt_decrypt("encrypt", $txt);
$vars = array(
"book" => $ty,
"url" => $adr
);
$querystring = http_build_query($vars);
$adr = "viewbuy.php?" . $querystring;
header("location: $adr");
} else {
$_SESSION["msg"] = 'Transation failed unknow error';
header("location:obinnaa.php");
}
}
}
}
but i get to
$_SESSION["msg"]='Transation has oready been made by a customer please check and try again
even when the query is right what are mine doing wrong.
Check your return variable name from the query. You have $ql when it should be $sql.
$sql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$count = mysqli_num_rows($sql);
A good IDE would flag this. NetBeans is a good free one.
Public Service Announcement:
NEVER build SQL queries straight from a URL parameter. Always sanitize your inputs and (better yet) use parameterized queries for your SQL calls. You can Google these topics for more info.

While-loop in SQL only loops once

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

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
}

SQL won't work? It doesn't come up with errors either

I have PHP function which checks to see if variables are set and then adds them onto my SQL query. However I am don't seem to be getting any results back?
$where_array = array();
if (array_key_exists("location", $_GET)) {
$location = addslashes($_GET['location']);
$where_array[] = "`mainID` = '".$location."'";
}
if (array_key_exists("gender", $_GET)) {
$gender = addslashes($_GET["gender"]);
$where_array[] = "`gender` = '".$gender."'";
}
if (array_key_exists("hair", $_GET)) {
$hair = addslashes($_GET["hair"]);
$where_array[] = "`hair` = '".$hair."'";
}
if (array_key_exists("area", $_GET)) {
$area = addslashes($_GET["area"]);
$where_array[] = "`locationID` = '".$area."'";
}
$where_expr = '';
if ($where_array) {
$where_expr = "WHERE " . implode(" AND ", $where_array);
}
$sql = "SELECT `postID` FROM `posts` ". $where_expr;
$dbi = new db();
$result = $dbi->query($sql);
$r = mysql_fetch_row($result);
I'm trying to call the data after in a list like so:
$dbi = new db();
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
$sql .= " ORDER BY `time` DESC LIMIT $offset, $rowsperpage";
$result = $dbi->query($sql);
// while there are rows to be fetched...
while ($row = mysql_fetch_object($result)){
// echo data
echo $row['text'];
} // end while
Anyone got any ideas why I am not retrieving any data?
while ($row = mysql_fetch_object($result)){
// echo data
echo $row->text;
} // end while
I forgot it wasn't coming from an array!

Categories