Error in php script when hosted in the remote server only - php

I have an android app with php backend, the problem is one of the php scripts works perfectly on the local server while when online it does not and produce the following error:
Parse error: syntax error, unexpected '"', expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/malblbic/public_html/webservice/profile.php on line 23
Here is my php code.
<?php
/*
Our "config.inc.php" file connects to database every time we include or require
it within a php script. Since we want this script to add a new user to our db,
we will be talking with our database, and therefore,
let's require the connection to happen:
*/
require("config.inc.php");
//initial query
$username = $_POST['username'];
$query = "Select * FROM users;
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch (PDOException $ex) {
$response[‘success’] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "User Available!";
$response["posts"] = array();
foreach ($rows as $row) {
$post = array();
$post["picture"] = $row["picture"];
$post["username"] = $row["username"];
$post["points"] = $row["points"];
//update our repsonse JSON data
array_push($response["posts"], $post);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Users Available!";
die(json_encode($response));
}
?>

Change backticks to regular quotes
$response[‘success’] = 0;
To
$response['success'] = 0;

Related

Php Webservices: Get Multiple Records from MySQL and encode it in JSON array

I am newbie to PHP webservices using MySQL. I follow this tutorial. I created one table -> loan_applications using phpmyadmin. Currenlty I have 3 records in table related to id 1. I would like to retrive all 3 records and would like to encode it in json.
I tried multiple way and tried googling but unable to get proper json array in response. Here is my get_applications_list.php
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array();
if (isset($_GET['id'])) {
// receiving the post params
$id = $_GET['id'];
$applications = $db -> getApplicationsList($id);
if ($applications) {
// got applications successfully
$response["status"] = 0;
$response["id"] = $applications["id"];
$response["application_id"] = $applications["application_id"];
$response["requested_amount"] = $applications["requested_amount"];
$response["interest_per_day"] = $applications["interest_per_day"];
$response["gst"] = $applications["gst"];
$response["tenure"] = $applications["tenure"];
$response["processing_fees"] = $applications["processing_fees"];
$response["amount_user_get"] = $applications["amount_user_get"];
$response["amount_user_pay"] = $applications["amount_user_pay"];
$response["application_latitude"] = $applications["application_latitude"];
$response["application_longitude"] = $applications["application_longitude"];
$response["application_status"] = $applications["application_status"];
$response["created_at"] = $applications["created_at"];
$response["updated_at"] = $applications["updated_at"];
$response["message"] = "Applications details fetched successfully";
echo json_encode($response);
} else {
// applications failed to store
$response["status"] = 1;
$response["message"] = "Unknown error occurred in getting details!";
echo json_encode($response);
}
} else {
// receiving the post params
$response["status"] = 2;
$response["message"] = "Required parameters is missing!";
echo json_encode($response);
}
?>
Here is my DB_Functions.php
<?php
class DB_Functions {
private $conn;
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$db = new Db_Connect();
$this->conn = $db->connect();
}
// destructor
function __destruct() {
}
public function getApplicationsList($id){
$stmt = $this->conn->prepare("SELECT * FROM loan_applications WHERE id = ?");
$stmt->bind_param("s", $id);
$stmt->execute();
$applications = $stmt->get_result()->fetch_assoc();
$stmt->close();
if($applications){
return $applications;
}else {
return false;
}
}
}
?>
Here is response which I am getting :
{"status":0,"id":1,"application_id":1,"requested_amount":5000,"interest_per_day":"0.50","gst":18,"tenure":28,"processing_fees":"5.00","amount_user_get":4705,"amount_user_pay":5700,"application_latitude":"9.999999999","application_longitude":"9.999999999","application_status":1,"created_at":"2018-10-10 21:45:17","updated_at":"0000-00-00 00:00:00","message":"Applications details fetched successfully"}
I am getting only one record but i need all 3 record which associated with id 1. I tried lot but unable to get.
So multiple problems here
1 - Although unsure but Currenlty I have 3 records in table related to id 1 seems incorrect statement. If id is primary key, you cannot have 3 records against one id
2 - $stmt->get_result()->fetch_assoc(); will always return one row, to get multiple rows or collection of rows you will need to do it like following
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
/* free result set */
$result->free();
}
3 - Its quite clear from following code that you are actually sending only one row back
if ($applications) {
// got applications successfully
$response["status"] = 0;
$response["id"] = $applications["id"];
$response["application_id"] = $applications["application_id"];
$response["requested_amount"] = $applications["requested_amount"];
$response["interest_per_day"] = $applications["interest_per_day"];
$response["gst"] = $applications["gst"];
$response["tenure"] = $applications["tenure"];
$response["processing_fees"] = $applications["processing_fees"];
$response["amount_user_get"] = $applications["amount_user_get"];
$response["amount_user_pay"] = $applications["amount_user_pay"];
$response["application_latitude"] = $applications["application_latitude"];
$response["application_longitude"] = $applications["application_longitude"];
$response["application_status"] = $applications["application_status"];
$response["created_at"] = $applications["created_at"];
$response["updated_at"] = $applications["updated_at"];
$response["message"] = "Applications details fetched successfully";
echo json_encode($response);
}
You should do it like this
$applications = getAllApplications(); //returns array of applications
$response['applications'] = $applications; // if they keys you want to send and database fields are same you don't need to set them separately
return json_encode($response);

Convert PHP file To PDO [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
i am beginer to php and i need your help.i want to make the following code to PDO to have a json output for an android app i am trying to bulit.I tryed a lot of solution but nothing correct came because of the JSON responce.I couldn also find good example and tutorials.Also i am new as i said with php so i am afraid to try complicated scenarios
here is the php code
This is my Config file
db_config.php
<?php
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "androidhive"); // database name
define('DB_SERVER', "localhost"); // db server
?>
This is connection file
db_connect.php
<?php
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
// Selecing database
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
}
}
?>
get_all_products.php
<?php
/*
* Following code will list all the products
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$result = mysql_query("SELECT *FROM products") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["products"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["pid"] = $row["pid"];
$product["name"] = $row["name"];
$product["price"] = $row["price"];
$product["created_at"] = $row["created_at"];
$product["updated_at"] = $row["updated_at"];
// push single product into final response array
array_push($response["products"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
?>
I know is very easy for someone with experience but i am strungle with it.please help because i have a strick deadline and no time now for deaper search.Thank you
**Would it be helpfull if i post what i have done?I didnt post it for space reason**s
EDIT
THIS IS WHAT I HAVE DONE SO FAR ANY IDEAS?
$db = new PDO("mysql:host=$dbhost;dbname=$dbname;", $dbuser, $dbpass);
$query = "Select * FROM products";
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute(HAVE NO IDEA!!!!);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
$rows = $stmt->fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["posts"] = array();
foreach ($rows as $row) {
$post = array();
$post["pid"] = $row["pid"];
$post["name"] = $row["name"];
$post["price"] = $row["price"];
//update our repsonse JSON data
array_push($response["posts"], $post);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Post Available!";
die(json_encode($response));
}
?>
Try this approach:
<?php
$response = array()
try {
//connection
$db = new PDO("mysql:host=$dbhost;dbname=$dbname;", $dbuser, $dbpass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//prepare
$query = "Select * FROM products";
$stmt = $db->prepare($query);
//get resutlt
$result = $stmt->execute();
if ($stmt->rowCount > 0) {
$response["success"] = true;
$response["message"] = "Post Available!";
//populate post array
while($row = $stmt->fetch()){
$response["posts"][] = $row;
}
}else{
$response["success"] = false;
$response["message"] = "No Post Available!";
}
}
catch (PDOException $ex) {
$response["success"] = false;
$response["message"] = "Database Error!";
}
echo json_encode($response);
?>
Prepared statements and stored procedures
using fetch all:
$rows = $stmt->fetchAll();
var_dump($rows);
$response["posts"] = $rows;

Using PHP to query a MDB file, and return JSON

I have a Microsoft Access Database, and I am trying to query the table using PHP, and output valid JSON. I have an equivalent code for a MSSQL database, am I am trying to make my code do the same thing, but just for the Access database.
Here is the MSSQL code
$myServer = "server";
$myDB = "db";
$conn = sqlsrv_connect ($myServer, array('Database'=>$myDB));
$sql = "SELECT *
FROM db.dbo.table";
$data = sqlsrv_query ($conn, $sql);
$result = array();
do {
while ($row = sqlsrv_fetch_array ($data, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($data));
$json = json_encode ($result);
sqlsrv_free_stmt ($data);
sqlsrv_close ($conn);
Here is what I tried for the MDB file
$dbName = "/filename.mdb";
if (!file_exists($dbName)) {
die("Could not find database file.");
}
$db = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", $user, $password);
$sql = "SELECT *
FROM cemetery";
$data = $db->query($sql); // I'm getting an error here
$result = array();
// Not sure what do do for this part...
do {
while ($row = fetch($data, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($data));
$json = json_encode ($result);
I kind of followed this to try to connect to the database: http://phpmaster.com/using-an-access-database-with-php/
Currently this is giving me a 500 Internal Server Error. I'm expecting a string such as this to be saved in the variable $json
[
{
"col1":"col value",
"col2":"col value",
"col3":"col value",
},
{
"col1":"col value",
"col2":"col value",
"col3":"col value",
},
{
etc...
}
]
Can someone help me port the MSSQL code I have above so I can use it with an MDB database? Thanks for the help!
EDIT: I'm commenting out the lines one by one, and it throws me the 500 error at the line $data = $db->query($sql);. I looked in the error log, and I'm getting the error Call to a member function query() on a non-object. I already have the line extension=php_pdo_odbc.dll uncommented in my php.ini file. Anyone know what the problem could be?
You only need 1 loop,
fetchAll is your iterable friend:
while ($row = $data->fetchAll(SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
odbc_connect doesn't return an object, it returns a resource. see (http://php.net/manual/en/function.odbc-connect.php) so you would need to do something like this.
$db = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", $user, $password);
$oexec = obdc_exec($db,$sql);
$result[] = odbc_fetch_array($oexec);
and then you can iterate over results..
see also:
http://www.php.net/manual/en/function.odbc-fetch-array.php
http://www.php.net/manual/en/function.odbc-exec.php
I finally figured it out.
<?php
// Location of database. For some reason I could only get it to work in
// the same location as the site. It's probably an easy fix though
$dbName = "dbName.mdb";
$tName = "table";
// Throws an error if the database cannot be found
if (!file_exists($dbName)) {
die("Could not find database file.");
}
// Connects to the database
// Assumes there is no username or password
$conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", '', '');
// This is the query
// You have to have each column you select in the format tableName.[ColumnName]
$sql = "SELECT $tName.[ColumnOne], $tName.[ColumnTwo], etc...
FROM $dbName.$tName";
// Runs the query above in the table
$rs = odbc_exec($conn, $sql);
// This message is displayed if the query has an error in it
if (!$rs) {
exit("There is an error in the SQL!");
}
$data = array();
$i = 0;
// Grabs all the rows, saves it in $data
while( $row = odbc_fetch_array($rs) ) {
$data[$i] = $row;
$i++;
}
odbc_close($conn); // Closes the connection
$json = json_encode($data); // Generates the JSON, saves it in a variable
?>
I use this code to get results from an ODBC query into a JSON array:
$response = null;
$conn = null;
try {
$odbc_name = 'myODBC'; //<-ODBC connectyion name as is in the Windows "Data Sources (ODBC) administrator"
$sql_query = "SELECT * FROM table;";
$conn = odbc_connect($odbc_name, 'user', 'pass');
$result = odbc_exec($conn, $sql_query);
//this will show all results:
//echo odbc_result_all($result);
//this will fetch row by row and allows to change column name, format, etc:
while( $row = odbc_fetch_array($result) ) {
$json['cod_sistema'] = $row['cod_sistema'];
$json['sistema'] = $row['sistema'];
$json['cod_subsistema'] = $row['cod_subsistema'];
$json['sub_sistema'] = $row['sub_sistema'];
$json['cod_funcion'] = $row['cod_funcion'];
$json['funcion'] = $row['funcion'];
$json['func_desc_abrev'] = $row['desc_abreviada'];
$json['cod_tipo_funcion'] = $row['cod_tipo_funcion'];
$response[] = array('funcionalidad' => $json);
}
odbc_free_result($result); //<- Release used resources
} catch (Exception $e) {
$response = array('resultado' => 'err', 'detalle' => $e->getMessage());
echo 'ERROR: ', $e->getMessage(), "\n";
}
odbc_close($conn);
return $response;
And finnally encoding the response in JSON format:
echo json_encode($response);

PHP mysqli script error 500

i have this script to connect my DB and i get error 500 when using it.
I tried to track where the error is and i think its at this line: while ($row = $stmt->fetch_assoc())
But i looked over examples and its the same is mine.
Here is my code thanks for helping:
<?php
$mysqli = new mysqli(*MY DB DETAILS*);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT * FROM comments WHERE workout_name =? AND user =?";
$stmt = $mysqli->prepare($sql) or trigger_error($mysqli->error."[$sql]");
$stmt->bind_param('ss', $workout_name, $user);
$workout_name = $_GET['workout_name'];
$user = $_GET['user'];
$stmt->execute();
if ($stmt)
{
while ($row = $stmt->fetch_assoc())
{
$response["name"] = $row["workout_name"];
echo json_encode($response);
}
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
}
else
{
$response["success"] = 2;
// echoing JSON response
echo json_encode($response);
}
?>
UPDATE:
I had to change $row = $stmt->fetch_assoc()
as described here:
How to remove the fatal error when fetching an assoc array
Before you do this line
$stmt->bind_param('ss', $workout_name, $user);
You have to set $workout_name and $user to contain a value.
eg
$workout_name = 'pumping iron';
$user = 'Arnold Schwarzenegger';
$stmt->bind_param('ss', $workout_name, $user);
In your case as you have not even created these variables yet. I assume you are getting the 500 error because the mysqli code goes BANG trying to find NON-EXISTANT variables to load data from.

Return JSON array from database with PHP to android

I am trying to return a set of results from PHP to android.
I have been able to return a single results but now I am trying to return multiple ones I am having some trouble figuring out how to do this as an array.
PHP function:
public function searchForPeople($tower) {
$uuid = uniqid('', true);
$result = mysql_query("SELECT * FROM users WHERE tower='$tower'") or die(mysql_error());
$resultNo = mysql_num_rows($result);
// check for successful store
if ($result != null) {
//if just one result return it
if ($resultNo == 1) {
// return result
$resultSet[] = mysql_fetch_array($result);
return $resultSet;
//if more than one loop through
} else {
//add each row to an array
while($row = mysql_fetch_array($result)) {
$resultSet[] = $row;
}
return $resultSet;
}
} else {
return false;
}
}
Section of index.php where i POST my data from android to:
//SEARCH FOR PEOPLE
else if ($tag == 'searchPeople') {
$tower = $_POST['tower'];
$result = $db->searchForPeople($tower);
// check array has been created
if ($result != false) {
$response["success"] = 1;
$count = 0;
foreach($result as $row) {
$response[$count]["user"]["name"] = $row["name"];
$response[$count]["user"]["email"] = $row["email"];
$count++;
}
echo json_encode($response);
} else {
$response["error"] = 2;
$response["error_msg"] = "No users found";
echo json_encode($response);
}
}
else {
echo "Invalid Request";
}
I am then trying to get the information back in android as below however recieving the error that there is no value for 0 meaning there must be a problem in the way I have returned the json in PHP.
JSONObject results = new JSONObject(resultsString);
JSONObject json_row = results.getJSONObject("0");
JSONObject json_user = json_row.getJSONObject("user");
Im sure this is a problem with returning the PHP array of SQL results. Probably when I am looping through them to add them to either $resultSet or $response.
Any help greatly appreciated.
EDIT:
Here are the errors I am getting:
11-14 19:42:37.270: E/JSON(639): "[{\"uid\":\"4\",\"unique_id\":\"505efc638e0f48.78430999\",\"name\":\"fish\",\"email\":\"fish\",\"encrypted_password\":\"r\/Hb7uXrHN8bFuRoKlG8+Y5LdKFjM2QyZDUyYzQ1\",\"salt\":\"c3d2d52c45\",\"created_at\":\"2012-09-23 13:11:15\",\"updated_at\":\"2012-11-03 09:56:15\",\"location\":\"888\",\"tower\":\"IS\",\"base_location\":\"\",\"client_site\":\"\",\"graduate\":\"0\",\"location_updated\":\"0000-00-00 00:00:00\"}]"
11-14 19:42:37.270: E/JSON Parser(639): Error parsing data org.json.JSONException: Value [{"uid":"4","unique_id":"505efc638e0f48.78430999","name":"fish","email":"fish","encrypted_password":"r/Hb7uXrHN8bFuRoKlG8+Y5LdKFjM2QyZDUyYzQ1","salt":"c3d2d52c45","created_at":"2012-09-23 13:11:15","updated_at":"2012-11-03 09:56:15","location":"888","tower":"IS","base_location":"","client_site":"","graduate":"0","location_updated":"0000-00-00 00:00:00"}] of type java.lang.String cannot be converted to JSONArray
I recently used a routine similar to the one below. No matter if there is just one result or many results, it always works.
$dbuser = // user name;
$dbpass = // password;
$dbhost = // host name;
$dbname = // database name;
$sql = "SELECT * FROM users WHERE tower=" . $tower;
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$results = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
echo '({"items":'. json_encode($results) .'});';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
You should dump your resultsString to debug Log to see how it looks like and whether it is the expected JSON string. Then you can see where, in the server or the client, you must fix the code.
I'd also look into JSONObject.getJSONArray(), since the response you're sending back consists of nested arrays, AFAICS.
I believe you should use
mysql_fetch_assoc
To pull the rows in PHP. Then your result comes ready to be json_encoded into the string you'll need to return to Android.
So try this:
function sqlToJSON($sql){
$sth = mysql_query($sql);
//if this is an update or an insert nothing to return
if($sth === false || $sth === true){
return null;
}
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
return json_encode($rows);
}
You should be able to run the result of this method through new JSONObject(res); on the Java side
without having to do any additional translation... I'm saying this from memory, so, it may not be 100% right, but if not, it's pretty close.

Categories