Data not properly passed to php server - php

I have an app that reads in Json data from phpmyadmin thru a php script and displayed in a list activity. Once a store name is clicked, +1 is added to the vote count for that store and is supposed to be sent back to the php server to store the new vote count in phpmyadmin. After the selection, I check the db vote count value and it is not updated. Although I get HTTP/1.1 200 ok in logcat, I don't think the data is being passed or taken in correctly. Can someone help, I'm stuck and have no direction.
Android code:
public void writeJSON() {
String convertedID;
String convertedVote;
//convert int to string value to passed
convertedID = new Integer(selectedID).toString();
convertedVote = new Integer(selectedVote).toString();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/kcstores.php");
try {
//writes the output to be stored in creolefashions.com/test2.php
ArrayList <NameValuePair> nvps = new ArrayList <NameValuePair>(2);
nvps.add(new BasicNameValuePair("storeUpdate", "update"));
nvps.add(new BasicNameValuePair("storeID", convertedID));
nvps.add(new BasicNameValuePair("storeVote", convertedVote));
httppost.setEntity(new UrlEncodedFormEntity(nvps));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
Log.i("writeJSON", response.getStatusLine().toString());
} catch(Exception e) {
Log.e("log_tag", "Error in http connection"+e.toString());
}
}
PHP Code:
<?php
$link = mysql_connect("localhost", "root", "") or die (mysql_error());
mysql_select_db("king_cake_stores")or die (mysql_error());
$query = "SELECT * FROM storeInfo";
$result = mysql_query($query);
$getUpdate = "noupdate";
if (isset($_POST['storeUpdate'])) {
echo "receiving data from app";
$getUpdate = $_POST['storeUpdate'];
$getStoreID = $_POST['storeID'];
$getStoreVote = $_POST['storeVote'];
}
// If command == getStoreID, it updates the table storeVote value
// with the android storeVote value based upon correct storeID
if ($getUpdate == "update") {
mysql_select_db("UPDATE storeInfo SET storeVote = $getStoreVote
WHERE storeID == $getStoreID");
} else {
// stores the data in an array to be sent to android application
while ($line = mysql_fetch_assoc($result)) $output[]=$line;
print(json_encode($output));
}
mysql_close($link);
?>

I suggest you start debugging from the server end and start working your way backwards.
First, start logging the response text from your HttpResponse.
Echo the mysql query text in your php file, and make sure it looks the way you're expecting it to.
If it looks correct, check your database structure.
If not, try doing a var_dump($_POST), and check to see if your parameters are being sent correctly.
If you run through these steps, you should have a better idea of where the problem is.

This might not be the whole problem, but:
mysql_select_db("UPDATE storeInfo SET storeVote = $getStoreVote
WHERE storeID == $getStoreID");
That should be mysql_query.

Here try this, using PDO:
<?php
//Db Connection Class
Class db{
private static $instance = NULL;
private function __construct() {}
public static function getInstance($DBUSER,$DBPASS) {
if (!self::$instance){
try {
self::$instance = new PDO("mysql:host=localhost;dbname=king_cake_stores", $DBUSER, $DBPASS);
self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch (Exception $e){
die('Cannot connect to mySQL server.');
}
}
return self::$instance;
}
private function __clone(){}
}
//Connect to PDO
$db = db::getInstance('username','password');
//Inser Update
if (isset($_POST['storeUpdate'])) {
try {
/*** UPDATE data ***/
$query = $db->prepare("UPDATE storeInfo
SET storeVote = :storeVote
WHERE storeID = :storeID");
$query->bindParam(':storeVote', $_POST['storeVote'], PDO::PARAM_STR);
$query->bindParam(':storeID', $_POST['storeID'], PDO::PARAM_INT);
/*** execute the prepared statement ***/
$query->execute();
}catch(PDOException $e){
echo $e->getMessage();
}
//Output Current
}else{
$result = $db->query('SELECT * FROM storeInfo')->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
}
/*** close the database connection ***/
$db = null;
?>

Try using or die after every PHP command. Also use try catch blocks in Android
This will reduce errors in the code.

Related

how to avoid connecting to mysql database with every request in php?

i have a simple php page that query the database for a random row (with some exceptions), every time it gets a post request.
i have noticed that the post request take some time to get the response.
because with every post request it reconnect to mysql server, so i thought maybe i could store the pdo in $_SESSION and use it to save some time and not have to authenticate with every request
i don't know if there is any way to fix this :)
<?php
// check for POST Request Only
if($_SERVER['REQUEST_METHOD'] !== 'POST') {
header("HTTP/1.0 405 Method Not Allowed");
exit();
}
$host = 'localhost';
$db = 'Quiz';
$user = 'admin';
$pass = 'password';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
if (!empty($_POST['old'])) {
$in = str_repeat('?,', count($_POST['old']) - 1) . '?';
$sql = "SELECT * FROM QT WHERE id NOT IN ($in) ORDER BY RAND() LIMIT 1";
$stm = $pdo->prepare($sql);
$stm->execute($_POST['old']);
$data = $stm->fetchAll();
echo json_encode($data);
exit();
} else {
$stm = $pdo->prepare('SELECT * FROM QT ORDER BY RAND() LIMIT 1');
$stm->execute();
$data = $stm->fetchAll();
echo json_encode($data);
exit();
}
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
?>
Сonnecting to mysql database with every request is how
PHP intended to work
Nothing wrong here, nothing to optimize here.
Go connect on every request and next time try to optimize a real issue.
so i thought
Don't think. Measure.
From the experience I can tell you that its the query that takes the time, not the connection. But technically that would be a guess all the same. So you have to measure first, then get the real issue, then google for it, solutions are plenty.
But measure first.

Unable to post API Rest PHP SQLITE

I'm looking for since few days to create a API Restful in PHP to add record on my sqlite database. But when I use POSTMAN to try it, my php code doesn't work, but it's work (with little modifies) with mysql databases.
Could you help me please ? (This code is just a test)
<?php
header('Content-Type: application/json');
try{
$pdo = new PDO('sqlite:database.db');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$retour["success"] = true;
$retour["message"] = "Connexion OK";
} catch(Exception $e){
$retour["success"] = false;
$retour["message"] = "Connexion impossible";
}
if ( !empty($_POST["ville_depart"]) && !empty($_POST["ville_destination"]) && !empty($_POST["date"]) && !empty($_POST["nb_heure"]) && !empty($_POST["prix"]) ) {
$requete = $pdo->prepare('INSERT INTO api (id, ville_depart, ville_destination, date_depart, nb_heure_vol, prix) VALUES (?, :ville1, :ville2, :date_vol, :nb, :prix)');
$requete->bindParam(':ville1', $_POST["ville_depart"]);
$requete->bindParam(':ville2', $_POST["ville_destination"]);
$requete->bindParam(':date_vol', $_POST["date_depart"]);
$requete->bindParam(':nb', $_POST["nb_heure_vol"]);
$requete->bindParam(':prix', $_POST["prix"]);
$requete->execute();
$retour["success"] = true;
$retour["message"] = "add flight";
$retour["results"] = array();
} else {
$retour["success"] = false;
$retour["message"] = "manque infos";
}
echo json_encode($retour);
// close the database connection
$pdo = NULL;
?>
The result from POSTMAN is not really "speaking", but I can't to find other informations (in the log files) to help me...
[edit to be conform at the previous code]
I think my problem come from my "$_POST" because, when I tried to put some values into the "INSERT" line, that works well.
ex:
$requete = $pdo->prepare("INSERT INTO api (id,ville_depart, ville_destination, date_depart, nb_heure_vol, prix) VALUES ('123', 'LYON', 'TLS', '2019-09-09', '13', '132')");
$requete->execute();

PHP PDO MySQL: Insert statement runs without error, no insert occurs

My code:
<?php
try {
$t = '040485c4-2eba-11e9-8e3c-0231844357e8';
if (array_key_exists('t', $_REQUEST)) {
$t = $_REQUEST["t"];
}
if (!isset($_COOKIE['writer'])) {
header("Location: xxx");
return 0;
}
$writer = $_COOKIE['writer'];
$dbhost = $_SERVER['RDS_HOSTNAME'];
$dbport = $_SERVER['RDS_PORT'];
$dbname = $_SERVER['RDS_DB_NAME'];
$charset = 'utf8' ;
$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname};charset={$charset}";
$username = $_SERVER['RDS_USERNAME'];
$password = $_SERVER['RDS_PASSWORD'];
$pdo = new PDO($dsn, $username, $password);
$stmt = $pdo->prepare("select writer from mydbtbl where writer=? and t=?");
$stmt->execute(array($writer, $t));
$num = $stmt->fetch(PDO::FETCH_NUM);
if ($num < 1) {
header("Location: login.php");
return 0;
}
$dbMsg = "Authorized";
$dbname = 'imgs';
$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname};charset={$charset}";
$pdo = new PDO($dsn, $username, $password);
if (isset($_FILES['filename'])) {
$name = $_FILES['filename']['name'];
// set path of uploaded file
$path = "./".basename($_FILES['filename']['name']);
// move file to current directory
move_uploaded_file($_FILES['filename']['tmp_name'], $path);
// get file contents
$data = file_get_contents($path, NULL, NULL, 0, 60000);
$stmt = $pdo->prepare("INSERT INTO file (contents, filename, t) values (?,?,?)");
$stmt->execute(array
($data,
$name,
$t)
);
$dbMsg = "Added the file to the repository";
// delete the file
unlink($path);
}
} catch (Exception $e) {
$dbMsg = "exception: " . $e->getMessage();
}
In the code you will see that the first part is for doing authentication. Then I create a new PDO object on the img schema, and do my file insert query after that.
Later, where I am printing out $dbMsg, it is saying "added file to the repository". But when I query the database (MySQL on Amazon AWS using MySQL Workbench) nothing has been inserted.
I don't understand why if nothing is getting inserted I am not getting an error message. If it says "added file to the respository", doesn't that mean the insert was successful? The only thing I can think is that using a different schema for this is mucking things up. All of my inserts to ebdb are going through fine
--- EDIT ---
This question was marked as a possible duplicate on my query about not getting an error message on my insert / execute code. This was a useful link and definitely something I will be aware of and check in the future, but ultimately the answer is the one I have provided regarding the terms of service for my aws account
The answer is that the (free) amazon account policy I am working under only allows me to have 1 database / schema. When I switched the table over to ebdb it worked right away. I am answering my own question (rather than deleting) so hopefully others using AWS / MySQL can learn from my experience.

Execute PHP-File once on ButtonClick - Android

I have a value on a database and can finally display it in a textView, now i want to update that number on buttonclick.
The php-scripts work fine, if I open them in my browser and check my DB, the value changed +1.
Now my question is:: How can i execute this file from my android app? I don't want to read it, I just want to execute the file once, so that the value in the DB changes. I tried it this way:
public void updateData(String uri) {
try {
URL url = new URL(uri);
HttpURLConnection connn = (HttpURLConnection) url.openConnection();
connn.connect();
} catch (Exception e) {
e.printStackTrace();
}
}
This is my PHP-File but as mentioned before it works fine::
/*
$con = mysql_connect('127.0.0.1', 'root', '');
if(!$con)
{
die('could not connect to database' . mysql_error());
}
mysql_select_db('vehicles', $con);
$plusOne = ("UPDATE `counter` SET cars = cars + 1 WHERE id = 1;");
mysql_close($con);
?> */
EDIT:: Ok nevermind everything works fine now :)

taking a symbol from edittext and save it in database

I'm trying to take a symbol from an EditText in my Android application and save it in the database (it's retrieved from the database and I'm editing it). For example, I have this symbol: μ. It will be retrived fine, but when I edit it and save the changes the symbol will be saved as a ?, and I don't know why.
I've added this to my PHP file:
mysql_query("SET NAMES 'utf8'");
header("Content-type: application/json; charset=utf-8");
and this is the Java code
class SaveglossaryDetails extends AsyncTask<String, String, String> {
/**
* Saving glossary
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String Name = name.getText().toString();
String Description = description.getText().toString();
String Symbol = symbol.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_GID, gid));
params.add(new BasicNameValuePair(TAG_NAME, Name));
params.add(new BasicNameValuePair(TAG_DESCRIPTION, Description));
params.add(new BasicNameValuePair(TAG_SYMBOL, Symbol));
// sending modified data through http request
// Notice that update glossary url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_glossary,"POST", params);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully updated
Intent i = new Intent(getApplicationContext(), AdminGlossary.class);
i.putExtra("admin", admin);
startActivity(i);
} else {
// failed to update glossary
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
my php code
<?php
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['ID_glossary']) && isset($_POST['symbol']) && isset($_POST['name']) && isset($_POST['description'])) {
$ID_glossary = $_POST['ID_glossary'];
$name = $_POST['name'];
$symbol = $_POST['symbol'];
$description = $_POST['description'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
mysql_query("SET NAMES 'utf8'");
// mysql update row with matched pid
$result = mysql_query("UPDATE glossary SET Symbol='$symbol', Name = '$name', Description = '$description' WHERE ID_Glossary = $ID_glossary");
header("Content-type: application/json; charset=utf-8");
// check if row inserted or not
if ($result) {
// successfully updated
$response["success"] = 1;
$response["message"] = "glossary successfully updated.";
// echoing JSON response
echo json_encode($response);
} else {
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
the db_connect
<?php
/**
* A class file to connect to database
*/
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());
mysqli_query($link, "SET SESSION CHARACTER_SET_RESULTS =utf8;");
mysqli_query($link, "SET SESSION CHARACTER_SET_CLIENT =utf8;");
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
}
}
?>
How can I solve this, and where is the problem?
Alright, I think I've got your problem.
Before every insert query on the server side, try adding
mysql_set_charset('utf8',$link);
This is because mysql_query("SET NAMES 'utf8'"); tells the database what charset to expect, but the mysql is not sending it with that charset. Let me know if this works.
This may not be the problem, but if you execute mysql_client_encoding($link); on the php script and it does not return utf8 then this is most likely the issue.
Also, you should know that mysql_* functions are deprecated. You should use mysqli_ or PDO.
Source
Ok now that I've seen more code, I see you're doing alot of things wrong.
Here's a pastie you can use to see the changes I've made.

Categories