Incorrect json output from mysql - php

I made a request from MySQL and my code below is not working:
$email =$_POST['email'];
$parola =$_POST['parola'];
$rez = mysqli_query($con, "SELECT * FROM utilizatori WHERE email='$email' AND parola='$parola'");
if($rez){
$succes = 1;
} else {
$succes = 0;
}
$data = array("succes" => $succes);
echo json_encode($data);
In postman it shows me this:

You missed the data variable or your query doesn't not return any output. Please try to use the MySQL query in Phpmyadmin or CLI. If it is OK then use the code like :
$email =$_POST['email'];
$parola =$_POST['parola'];
$rez = mysqli_query($con, "SELECT * FROM utilizatori WHERE email='$email' AND parola='$parola'");
while($result = mysqli_fetch_array($rez))
{
$data[] = $result;
}
if(mysqli_num_rows($rez) != 0) {
$data = array("success" => "Success", "data" => $data );
} else {
$data = array("success" => "Failed", "data" => array() );
}
echo json_encode($data);

Related

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 file else condition output is wrong

Login.php
<?php
include 'Connection.php';
if(isset($_REQUEST["insert"]))
{
$user = $_GET['user'];
$pwd = $_GET['pass'];
//$sql =sqlsrv_query($conn,"select RegNo,UserName,password from Std_Reg where Username= '$user' and Password = '$pwd'");
$sql = "select RegNo,UserName,password from Std_Reg where Username= '$user' and Password = '$pwd'";
$stmt = sqlsrv_query($conn, $sql);
$result = array();
if (!empty($stmt)) {
// check for empty result
if (count($stmt) > 0) {
$stmt = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$product = array();
$product["RegNo"] = $stmt["RegNo"];
$product["UserName"] = $stmt["UserName"];
$product["password"] = $stmt["password"];
// success
$result["success"] = 1;
// user node
$result["product"] = array();
array_push($result["product"], $product);
// echoing JSON response
echo json_encode($result);
} else {
// no product found
$result["success"] = 0;
$result["message"] = "No product found";
// echo no users JSON
echo json_encode($result);
}
//sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnection first
}
}
?>
I have connected to MS SQL Server to PHP File.if condition work properly but else part is not work.I have wrong parameter passed its give output
{"success":1,"product":[{"RegNo":null,"UserName":null,"password":null}]}.
but right else part output is
{
"success": 0,
"message": "No product found"
}
After
$stmt = sqlsrv_query($conn, $sql);
$stmt is either FALSE (when there is a connectivity issue, a syntax error in the query or it refers an object that doesn't exist) or a PHP resource.
Because $stmt is neither an array nor an object that implements the Countable interface, count($stmt) always returns 1.
Use sqlsrv_num_rows() to get the number of rows returned by the query or (if you don't care about the number) use sqlsrv_has_rows():
$stmt = sqlsrv_query($conn, $sql);
if ($stmt) {
if (sqlsrv_has_rows($stmt) > 0) {
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$product = array(
'RegNo' => $row['RegNo'],
'UserName' => $row['UserName'],
'password' => $row['password'],
);
$result = array(
'success' => 1,
'product' => array($product),
);
} else {
// no product found
$result = array(
'success' => 0,
'message' => 'No product found',
);
}
echo json_encode($result);
}
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);

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

MySQL cannot update the rows in the database

I am trying to update my selected row of data but i could not update it. Once i run the code I am getting this output {"RowCount": 0 ,"results": []}. Supposed i should get 1 but i am not getting it. Can i know how to solve this problem.
This is my PHP code:
case 'updateStudent':
$studentUpdateSQL = "UPDATE srs_student SET surname=:surname, forename=:forename,
email=:email WHERE studentid=:id";
$rs = new JSONRecordSet();
$retval = $rs->getRecordSet($studentUpdateSQL, 'ResultSet',
array(':surname'=>$surname,
':forename'=>$forename,
':email'=>$email,
':id'=>$id
));
echo $retval;
break;
This is the JSONRecordSet class:
function getRecordSet($sql, $elementName = "ResultSet", $params = null) {
$stmt = parent::getRecordSet($sql, $params);
$recordSet = $stmt->fetchAll(PDO::FETCH_ASSOC);
$nRecords = count($recordSet);
if ($nRecords == 0) {
$status = 'error';
$message = json_encode(array("text" => "No records found"));
$result = '[]';
}
else {
$status = 'ok';
$message = json_encode(array("text" => ""));
$result = json_encode($recordSet);
}
return "{\"RowCount\": $nRecords ,\"results\": $result}";
}
}
$rs = new JSONRecordSet();
$db_conn = pdoDB::getConnection();
$stmt=$db_conn->prepare($studentUpdateSQL);
$retval=$stmt->execute(array(':surname'=>$surname,
':forename'=>$forename,
':email'=>$email,
':id'=>$id));
echo $retval;

My php file does not return all values in JSON form

So I have a database and I have written a php file that inserts value to the table and then returns all the values in this table.
However, my code only returns just one random value from the table and not all of them. I am not sure why, but this is my code:
<?php
include_once "init.php";
if(!empty($_POST['names'])){
$contactname = $_POST['names'];
$query = "INSERT INTO contacts (contactID, names)
VALUES('NULL', ?)";
$results = $conn -> prepare($query);
$results->bind_param('s', $contactname);
$results->execute();
$results->close();
echo json_encode("Success");
$query_two = "SELECT names FROM contacts";
$result = mysqli_query($conn, $query_two);
$response = array();
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_assoc($result)){
$response["names"][] = $row["names"];
}
}
echo json_encode($response);
}
else{
echo json_encode("Something went wrong");
}
?>
EDIT: Thank you guys for providing me a solution so quickly! I fixed it and it works but the first echo json_encode("Success"); is not being executed.
In your line here:
$response["names"] = $row["names"];
You are replacing the value of $response["names"]. Instead, try adding it to an array:
$response = array("names" => array());
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_assoc($result)){
$response["names"][] = $row["names"];
}
}
To use one JSON object, you'd initialize $response at the top and change the values as needed.
<?php
include_once "init.php";
$response = ['success' => false, 'message' => null, 'names' => []];
if(empty($_POST['names'])) {
$response['message'] = 'No names were provided in the request';
} else {
$contactname = $_POST['names'];
$query = "INSERT INTO contacts (contactID, names) VALUES('NULL', ?)";
$results = $conn->prepare($query);
$results->bind_param('s', $contactname);
$results->execute();
$results->close();
$response['success'] = true;
$query_two = "SELECT names FROM contacts";
$result = mysqli_query($conn, $query_two);
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_assoc($result)){
$response['names'][] = $row['names'];
}
}
}
echo json_encode($response);

Categories