Error in php code.Maybe my for loop is wrong? - php

ok i am not familiar with php but i have to use it for my android application to take data from mysql server.This is what i ve done so far.When i call this script from the app i want to create a new booking row and all the booked seat rows that the user selected . The above php throws an exception but i dont know where.
<?php
#open connection
require("config.inc.php");
//if posted data is not empty
if (!empty($_POST)) {
$query = "INSERT INTO booking (show_id) VALUES (:showId) ";
$query_params = array(
':showId' => $_POST['showId']);
$query_params1 = array(
':seatNo' => $_POST['seatNo']);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$lastRow = $db->lastInsertId('booking');
for($i=0; $i<$_POST['size']; $i++){
$query1 = "INSERT INTO booked_seats (booking_id,seat) VALUES ($lastRow,:seatNo) ";
$query_params1 = array(
':seatNo' => $_POST["seat{$i}"]);
$stmt = $db->prepare($query1);
$result = $stmt->execute($query_params1);
}
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error. Please Try Again!";
die(json_encode($response));
}
$response["success"] = 1;
$response["message"] = "Reservation Completed!";
echo json_encode($response);
}
?>
and this is the java code where i call the php
protected String doInBackground(String... strings) {
String msg=null;
try {
List<NameValuePair> params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("showId", showId));
params.add(new BasicNameValuePair("size",Integer.toString(selectedSeats.size())));
for(int i=0; i<selectedSeats.size(); i++) {
params.add(new BasicNameValuePair("seat"+Integer.toString(i),Integer.to String(selectedSeats.get(i))));
}
JSONObject jsonObject=jsonParser.makeHttpRequest( LOGIN_URL, "POST", params);
msg = jsonObject.getString(TAG_MESSAGE);
}
catch (JSONException e){
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
return msg;
}
I know that the tag seat* that i use may be a little bit unusual but i couldnt think anything else.
The weird think is that the above code works.It makes the changes in the database but the msg
"Reservation Completed! is never reachable because it throws an exception somewhere!

Try using the following to echo the json:
header('Content-Type: application/json');
echo json_encode($response);
Also, ommit the PHP closing tag ?>. Last but not least; make sure nothing else is being sent to output before echo-ing your JSON.
Complete answer:
<?php
#open connection
require("config.inc.php");
//if posted data is not empty
if (!empty($_POST)) {
$query = "INSERT INTO booking (show_id) VALUES (:showId) ";
$query_params = array(
':showId' => $_POST['showId']);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$lastRow = $db->lastInsertId('booking');
for($i=0; $i<$_POST['size']; $i++){
$query1 = "INSERT INTO booked_seats (booking_id,seat) VALUES ($lastRow,:seatNo) ";
$query_params1 = array(
':seatNo' => $_POST["seat" . $i]);
$stmt = $db->prepare($query1);
$result = $stmt->execute($query_params1);
}
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error. Please Try Again!";
die(json_encode($response));
}
$response["success"] = 1;
$response["message"] = "Reservation Completed!";
header('Content-Type: application/json');
echo json_encode($response);
}

Related

Cannot fetch the value from JsonArray

I am having problem fetching out the value from PHP coding to my android. The logcat shows that
:W/System.err: org.json.JSONException:
No value for posts.
This is my php code:
<?php
require("config1.php");
$query="SELECT commentName,comment FROM discussion_comment WHERE discussID = :discussID";
$query_params=array(':discussID'=> $_POST['discussID']);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}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["commentName"] = $row["commentName"];
$post["comment"] = $row["comment"];
array_push($response["posts"], $post);
}
echo json_encode($response);
}else {
$response["success"] = 0;
$response["message"] = "No post Available!";
die(json_encode($response));
?>
When is remove the 'WHERE discussID = :discussID"', I am able to fetch the data, but some is not necessary. What other way to write with Where condition.
My java:
private static final String COMMENT_NAME="commentName";
private static final String COMMENT="comment";
private static final String COMMENT_VIEW_URL="http://fysystem.com/show_comment.php";
#Override
protected String doInBackground(String... args) {
try {
json=jsonParser.getJSONFromUrl(COMMENT_VIEW_URL);
JSONArray jsonArray=json.getJSONArray("posts");
for(int i = 0; i<jsonArray.length();i++) {
json=jsonArray.getJSONObject(i);
commentName=json.getString(COMMENT_NAME);
comment=json.getString(COMMENT);
}
Appreciate your help.
PHP
<?php
require("config1.php");
// Default message
$response = array('success'=>0, 'message'=>'Error. Pass required parameters');
// Check discussID exists in POST params
if(isset($_POST['discussID']) && $_POST['discussID']!=""){
$sql = 'SELECT `commentName`, `comment` FROM `discussion_comment` WHERE `discussID` = :discussID';
try {
// Hope $db is defined in config1.php
$stmt = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute(array(':discussID'=> $_POST['discussID']));
$response = array("success"=>0, "message"=>"Discussion Not found");
// If data exists
if($stmt->rowCount()>0){
// Fetching rows with a scrollable cursor
// http://php.net/manual/en/pdostatement.fetch.php
$posts = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$posts[] = array('commentName'=>$row['commentName'], 'comment' => $row['comment']);
}
// Set the success status 1 and add the posts in return response
$response = array('success'=>1, 'message'=>'Discussion found', 'posts'=>$posts);
}
$stmt = null;
}
catch (PDOException $e) {
// print $e->getMessage();
$response = array('success'=>0, 'message'=>'DB Error');
}
}
// Finally return the response
echo json_encode($response);
?>
Andorid
try {
json=jsonParser.getJSONFromUrl(COMMENT_VIEW_URL);
int success = json.getInt('success');
// Check before access posts data
if(success==1){
JSONArray jsonArray=json.getJSONArray("posts");
for(int i = 0; i<jsonArray.length();i++) {
json=jsonArray.getJSONObject(i);
commentName=json.getString(COMMENT_NAME);
comment=json.getString(COMMENT);
}
}else{
// Handle it here if parameters not exist or db error or no discussion found
}
}
Hope this helps!

Insert data into server

I have problem inserting data into my database. The data can't be inserted and it does not show any errors in my Logcat. I have working on it but still can't solve the problems. This is my PHP code:
<?php
require ("config1.php");
if(!empty($_POST)){
$query = "SELECT * FROM announcement WHERE announceID = :announcementID";
$query_params=array(':announcementID'=> $_POST['announcementID']);
try{
$stmt=$db->prepare($query);
$stmt->execute($query_params);
}catch(PDOException $ex){
$response["success"]=0;
$response["message"]="Database Error1. Please try again";
die(json_encode($response));
}
$row = $stmt->fetch();
if($row){
$query = "INSERT INTO announcement (title,description,start_date,end_date,time)
VALUES (:title,:description,:starDate,:endDate,:time) ";
$query_params= array(
':title'=>$_POST['title'];
':description'=>$_POST['description'];
':startDate' => $_POST['start_date'];
':endDate' => $_POST['end_date'];
':time' => $_POST['time'];
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error2. Please Try Again!";
die(json_encode($response));
}
$response["success"] = 1;
$response["message"] = "Update successful!";
echo json_encode($response)
}
}
?>
Below is my java code:
protected String doInBackground(Void... params) {
RequestHandler rh=new RequestHandler();
HashMap<String,String> param= new HashMap<String, String>();
param.put(KEY_TITLE,announcement_title);
param.put(KEY_DESCRIPTION,announcement_desc);
param.put(KEY_START_DATE,start_date);
param.put(KEY_END_DATE,end_date);
param.put(KEY_TIME,time);
param.put(KEY_IMAGE,announcement_image);
String result= rh.sendPostRequest(ANNOUNCEMENT_URL,param);
return result;
}
Appreciate is someone can point out the problems.
You PHP Code Has Syntax error and Mysql preparement Placeholder error.
I Have Rewritten the Code kindly replace with your Old Code.
<?php
require ("config1.php");
if(!empty($_POST)){
//kindly filter the POST value
$query = "SELECT * FROM announcement WHERE announcementID = :announcementID";
$query_params=array(':announcementID'=> $_POST['announcementID']);
$stmt=$db->prepare($query);
$stmt->execute($query_params);
/*
}catch(PDOException $e){
$response["success"]=0;
$response["message"]="Database Error1. Please try again";
die(json_encode($response));
}
*/
$row = $stmt->fetch();
if($row){
$query = "INSERT INTO announcement (title,description,start_date,end_date,time)
VALUES (:title,:description,:starDate,:endDate,:time)";
//re written by Ajmal PraveeN
$query_params= array(
':title'=>$_POST['title'],
':description'=>$_POST['description'],
':startDate' => $_POST['start_date'],
':endDate' => $_POST['end_date'],
':time' => $_POST['time']
);
/*
try {
*/
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
/*
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error2. Please Try Again!";
die(json_encode($response));
}
*/
$response["success"] = 1;
$response["message"] = "Update successful!";
echo json_encode($response);
}
}
?>
If your $_POST['announcementID'] is a numeric number i can re edit the post with a Sanitize and Title post too.

Sending/retriving arabic charecters (utf8) using json from android to server

I'm trying to store Arabic characters in a database on server. But when I add something it will be displayed as ???????????? in the database! I tried too add from my php to check if the problem from the php file, but it added the text correctly in database. So the error from android and json, how can I make the encoding of json to utf8 in android?
Here's my code:
class AddStories extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Caregiver_ID", ID));
params.add(new BasicNameValuePair("Title", "قصة"));
params.add(new BasicNameValuePair("Story", "قصتي بدأت عندما"));
JSONObject json = jsonParser.makeHttpRequest(url_add_story,"POST", params);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
suc=1;
sucess();
}
else {
suc=0;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
PHP for adding:
<?php
header("Content-Type: text/html; charset=utf-8");
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['Caregiver_ID']) && isset($_POST['Title'])&& isset($_POST['Story'])) {
$Caregiver_ID = $_POST['Caregiver_ID'];
$Title = $_POST['Title'];
$Story = $_POST['Story'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
mysql_query("SET NAMES 'utf8'"); mysql_query('SET CHARACTER SET utf8');
// mysql inserting a new row
$result = mysql_query("INSERT INTO Stories(Caregiver_ID, Title, Story) VALUES('$Caregiver_ID', '$Title','$Story')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "glossary successfully created.";
// echoing JSON response
echo json_encode($response,JSON_UNESCAPED_UNICODE );
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response );
}
?>
Also when I tried to retrieve from android I got this for the text:
نةيىؤتيلالاؤتيلاارلابارابي-الالالتعا
while its retrieved correctly in php.
PHP code
<?php
header("Content-Type: text/html; charset=utf-8");
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query("SELECT *FROM Stories ") or die(mysql_error());
mysql_query("SET NAMES 'utf8'"); mysql_query('SET CHARACTER SET utf8');
if (mysql_num_rows($result) > 0) {
$response["story"] = array();
while ($row = mysql_fetch_array($result)) {
$story = array();
$story ["Caregiver_ID"] = $row["Caregiver_ID"];
$story ["Title"] = mb_convert_encoding($row["Title"],'HTML-ENTITIES','utf-8');
$story ["Story"] = mb_convert_encoding($row["Story"],'HTML-ENTITIES','utf-8');
array_push($response["story"], $story);
}
$response["success"] = 1;
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No locations found";
// echo no users JSON
echo json_encode($response);
}
?>
Try below code in android
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
byte[] buffer = new byte[1024];
int nread;
while ((nread = stream.read(buffer)) > 0) {
baos.write(buffer, 0, nread);
}
} catch (ClientProtocolException | IOException e) {
}
//Create a JSON from the String that was return.
JSONObject jsonObject = new JSONObject();
try {
String jsonText = new String(baos.toByteArray(), StandardCharsets.UTF_8);
jsonObject = new JSONObject(jsonText);
You have to put N before the columns which you need to add the Arabic text.
For example N'مختار'.
According to your code,you should change this line
$result = mysql_query("INSERT INTO Stories(Caregiver_ID, Title, Story) VALUES('$Caregiver_ID', '$Title','$Story')");
........
.....
...
to be
$result = mysql_query("INSERT INTO Stories(Caregiver_ID, Title, Story) VALUES('$Caregiver_ID', N'$Title',N'$Story')");

How to execute PHP query (without arguments) from android

how could I invoke this code:
<?php
//load and connect to MySQL database stuff
require("config.inc.php");
$query_params = null;
$resetQuery = "UPDATE `items` SET `picked`= 0";
try {
$stmt = $db->prepare($resetQuery);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "PHP Database Error!";
die(json_encode($response));
}
echo "DB reset complete";
?>
from android app?
Normally, when there are arguments to pass, I parse JSON object and post it as follows:
JSONObject json = jsonParser.makeHttpRequest(
RESET_DB, "POST", params);

How to get all the product categories from the mysql db via php and return json array

I have an android app.
I want to send a get request to the get_categories.php file.
In the get_categories.php file I want to
$query_categories = "SELECT category_name FROM categories";
and return all the categories found in that table into a json array.
How can I do that?
This is my incomplete code:
if (!empty($_GET)) {
$query_categories = "SELECT category_name FROM categories";
$success = false;
try{
$sth = $connection->prepare($query_categories);
//$sth->execute(array(':user_id' => $user_id));
//$user_items_count = $sth->rowCount(); - these are lines from other php file I've used
foreach($)//??
$success = true;
} catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = $ex;
die(json_encode($response));
$connection = null;
}
if($success) {
$response["success"] = 1;
$response["message"] = "Kylie";
die(json_encode($response));
$connection = null;
} else {
$response["success"] = 2;
$response["message"] = "something went wrong";
die(json_encode($response));
$connection = null;
}
} else {
$response["success"] = 3;
$response["message"] = "Another brick in the wall";
echo json_encode($response);
$connection = null;
}
Later on, in my Java code, how do I decode that?
Usually up until this point, in my other JSON transfers, I've received normal Json object with no arrays and read them this way:
setUserLastSeen(json.getString(TAG_USER_LAST_SEEN)); //for example.
But how do I decode an array?
For php side this how you can get the categories array and make json,for prepared statements this is how you can accomplish
$success = false;
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$success = true;
}
catch(PDOException $e) {
$response["success"] = 0;
$response["message"] = 'Connection failed: ' . $e->getMessage();
$response["data"]=null;
die(json_encode($response));
}
$query_categories = "SELECT category_name FROM categories";
try{
$sth = $sth->prepare($query_categories );
$success = true;
} catch(PDOException $e) {
$response["success"] = 0;
$response["message"] = 'Prepare failed: ' . $e->getMessage();
$response["data"]=null;
die(json_encode($response));
}
try{
$sth->execute();
$success = true;
} catch(PDOException $e) {
$response["success"] = 0;
$response["message"] = 'Execute failed: ' . $e->getMessage();
$response["data"]=null;
die(json_encode($response));
}
$categories = $sth->fetchAll(PDO::FETCH_COLUMN, 0);/* fetches all categories from db */
/* Output of $query_categories
Array
(
[0] => cat1
[1] => cat2
[2] => cat3
[3] => cat4
)
*/
/* json encode $query_categories
["cat1","cat2","cat3","cat4"]
*/
/* check if categories exist or not*/
if(empty($categories)){
$response["success"] = 0;
$response["message"] = "No categories found";
$response["data"]=null;
die(json_encode($response));
$connection = null;
}
if($success) {
$response["success"] = 1;
$response["message"] = "Kylie";
$response["data"]=$categories;
die(json_encode($response));
$connection = null;
/* output
{"success":0,"message":"Kylie","data":["cat1","cat2","cat3","cat4"]}
*/
} else {
$response["success"] = 2;/* don't where you are setting success to 2*/
$response["message"] = "something went wrong";
$response["data"]=null;
die(json_encode($response));
$connection = null;
}
} else {
$response["success"] = 3;/* don't where you are setting success to 3*/
$response["message"] = "Another brick in the wall";
$response["data"]=null;
die(json_encode($response));
$connection = null;
}
I am not good at java but here is the reference How to parse a JSON and turn its values into an Array?
/* store json string in the_json */
JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("data");
Note: make sure on java side you must check the success from json which
must be ==1 and the_json_array is not null
PHP Data Objects
you can use below code to ferch data using json and then decode that json array:
=================================================================================
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("your webservice");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse res = httpclient.execute(httppost);
HttpEntity entity = res.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
Log.d("Data",""+ result);
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
String fd_ono=null;
try
{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
fd_ono=json_data.getString("your column name");
textView.settext(fd_ono.toString());
}
}
catch(JSONException e1)
{
Toast.makeText(getBaseContext(), "Record not found", Toast.LENGTH_LONG).show();
}

Categories