Insert data into server - php

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.

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!

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

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

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

PHP MySQL Select script

I am working on an app that needs to select data from a MySQL database. I am currently testing the PHP script via my browser to make sure that it is returning the correct data. The issue is currently it returns the exception "Database Error!". I have included my PHP script.
get_agencies_by_city.php
<?php
/*
* Following code will get all agencies matching the query
* Returns essential details
* An agency is identified by agency id
*/
require("DB_Link.php");
$city = ($_GET['City']);
//query database for matching agency
$query = "SELECT * FROM agency WHERE City = $city";
//Execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
//Retrieve all found rows and add to array
$rows = $stmt->FETCHALL();
if($rows) {
$response["success"] = 1;
$response["message"] = "Results Available!";
$response["agencys"] = array();
foreach ($rows as $row) {
$agency = array();
$agency["AgencyID"] = $row["AgencyID"];
$agency["AgencyName"] = $row["AgencyName"];
$agency["Address1"] = $row["Address1"];
$agency["City"] = $row["City"];
$agency["State"] = $row["State"];
$agency["Zip"] = $row["Zip"];
$agency["Lat"] = $row["Lat"];
$agency["Lon"] = $row["Lon"];
//update response JSON data
array_push($response["agencys"], $agency);
}
//Echo JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Agency found!";
die(json_encode($response));
}
?>
Here is the DB_Link.php
<?php
// These variables define the connection information the MySQL database
// set connection...
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
header('Content-Type: text/html; charset=utf-8');
session_start();
?>
You should rewrite your query to this, as it is a prepared statement and your query will be much safer (and working)!
//your code
try {
$statement = $dbh->prepare("SELECT * FROM agency WHERE city = :city");
$statement->execute(array('city' => $city));
// rest of your code
}
// and the exception
catch (PDOException $ex) {
//or include your error statement - but echo $ex->getMessage()
die('Error!: ' . json_encode($ex->getMessage()));
}
also you should check if $_GET really is set!
LIKE THIS:
try {
$stmt = $dbh->prepare("SELECT * FROM agency WHERE city = :city");
$stmt->execute(array('city' => $city));
$rows = $stmt->FETCHALL();
if($rows) {
$response["success"] = 1;
$response["message"] = "Results Available!";
$response["agencys"] = array();
foreach ($rows as $row) {
$agency = array();
$agency["AgencyID"] = $row["AgencyID"];
$agency["AgencyName"] = $row["AgencyName"];
$agency["Address1"] = $row["Address1"];
$agency["City"] = $row["City"];
$agency["State"] = $row["State"];
$agency["Zip"] = $row["Zip"];
$agency["Lat"] = $row["Lat"];
$agency["Lon"] = $row["Lon"];
//update response JSON data
array_push($response["agencys"], $agency);
}
//Echo JSON response
echo json_encode($response);
} }
catch (PDOException $ex) {
//or include your error statement - but echo $ex->getMessage()
die('Error!: ' . json_encode($ex->getMessage()));
}
The variable $city needs to be in your query. Do something like this:
$query = "SELECT * FROM Agency WHERE City = " . $city;

How to delete a friendship from a MySQL db using php/pdo and check if it is successful

Im trying to delete a friendship between two users from the db
the friendship table is simple:
friend_one |friend_two
100 |142
142 |100
Here is the code I have, but its not working:
if (!empty($_POST)) {
$remover_id = $_POST['remover_id'];
$removed_id = $_POST['removed_id'];
try {
$query = "DELETE * FROM
`friendships`
WHERE
(friend_one = :remover_id AND friend_two = :removed_id)
OR
(friend_two = :remover_id AND friend_one = :removed_id)
";
$sth = $connection->prepare($query);
$sth->execute(
array(
':remover_id' => $remover_id,
':removed_id' => $removed_id
));
if($sth->rowCount () >=0){
$response["success"] = $http_response_success;
die(json_encode($response));
$connection = null;
} else {
$response["success"] = $http_response_server_error;
$response["message"] = $http_message_server_error;
die(json_encode($response));
$connection = null;
}
} catch (PDOException $ex) {
$response["success"] = $http_response_server_error;
$response["message"] = $http_message_server_error;
die(json_encode($response));
$connection = null;
}
} else {
$response["success"] = $http_response_bad_request;
$response["message"] = $http_message_bad_request;
die(json_encode($response));
$connection = null;
}
First of all I dont think the way I check for success is correct, second of all, the friendship doesnt get removed from the DB anyway.
When I run this I find myself in the else statement:
if($sth->rowCount () >=0){
$response["success"] = $http_response_success;
die(json_encode($response));
$connection = null;
} else {
$response["success"] = $http_response_server_error;
$response["message"] = $http_message_server_error;
die(json_encode($response));
$connection = null;
}
You have an SQL error for your DELETE statement
DELETE FROM `friendships` WHERE
(friend_one = :remover_id AND friend_two = :removed_id)
OR
(friend_two = :remover_id AND friend_one = :removed_id)
You had an asterisk after delete, where there shouldn't be one. https://dev.mysql.com/doc/refman/5.0/en/delete.html
As for checking for PDO Errors, you shouldn't use $sth->rowCount().
if(!$sth->execute($data)) {
// Error (SQL Error)
}
if($sth->rowCount() > 0) {
// At least 1 record was updated / inserted / deleted / (Possibly Selected)
}

Categories