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 :)
Related
I am working on a very important project using Arduino Uno and SIM900 GSM Module. Basically I correctly read the ID from an RFID Card(RFID-RC522) and I need to send the ID using an URL to the Host Provider's Database(000webhost) and I need to get the OUTPUT of my query but as you will see a simple change in the code and the output is completely changed.
Here is the code for the PHP file that needs to send the OUTPUT:
<?php
$dbhost = "localhost";
$dbuser = "*******";
$dbpass = "*******";
$db = "********";
$conn = new mysqli($dbhost, $dbuser, $dbpass,$db);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
mysqli_select_db($conn,$db);
date_default_timezone_set('Europe/Rome');
$date = date("Y-m-d G:i:s");
$code=$_REQUEST['code'];
$sql_u = "SELECT * FROM users WHERE code='$code'";
$res_u = mysqli_query($conn, $sql_u);
if (mysqli_num_rows($res_u) > 0)
{
echo "ALREADY EXISTENT $code";
}
else
{
$sql = "INSERT INTO users(code,used) VALUES ('$code','$date')";
if (mysqli_query($conn, $sql)) {
echo "SUCCESS $code";
} else {
echo "ERROR INSERTING $code";
}
}
mysqli_close($conn);
?>
Anyways, here is the Arduino Code:
#include <SoftwareSerial.h>
#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 9
#define SS_PIN 10
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
SoftwareSerial myGsm(7, 8);
String UID = "";
String pUID;
void setup() {
Serial.setTimeout(100);
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522
myGsm.begin(19200);
Serial.begin(9600);
myGsm.println("AT+CGATT=1");
printSerialData();
myGsm.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
printSerialData();
myGsm.println("AT+SAPBR=3,1,\"APN\",\"internet.wind\"");
printSerialData();
myGsm.println("AT+SAPBR=2,1");
printSerialData();
myGsm.println("AT+SAPBR=1,1");
printSerialData();
myGsm.println("AT+HTTPINIT");
printSerialData();
}
void loop() {
if (!mfrc522.PICC_IsNewCardPresent()) {
return;
}
if (!mfrc522.PICC_ReadCardSerial()) {
return;
}
pUID = UID;
UID = mfrc522.PICC_DumpDetailsToSerialUid(&(mfrc522.uid));
if (UID != pUID) {
Serial.print("RFID Code: ");
Serial.print(UID);
Serial.print("\n");
String url = "http://mywebsite.000webhostapp.com/test.php?code=", code = "";
url += UID;
code = "";
String httpara = "";
httpara += "AT+HTTPPARA=\"URL\",";
httpara += url;
url = "http://mywebsite.000webhostapp.com/test.php?code=";
myGsm.println(httpara); // setting the httppara,
printSerialData();
myGsm.println("AT+HTTPPARA=\"CID\",1");
printSerialData();
myGsm.println("AT+HTTPACTION=0"); //submit the GET request
//delay(8000);//the delay is important if the return datas are very large, the time required longer.
printSerialData();
myGsm.println("AT+HTTPREAD=0,20"); // read the data from the website you access
//delay(3000);
printSerialData();
}
}
void printSerialData() {
String readI = myGsm.readStringUntil("\r\n");
Serial.println(readI);
}
The OUTPUT for this code is:
AT+CGATT=1
OK
AT+SAPBR=3,1,"CONTYPE","GPRS"
OK
AT+SAPBR=3,1,"APN","internet.wind"
OK
AT+SAPBR=2,1
+SAPBR: 1,3,"X.X.X.X"
OK
AT+SAPBR=1,1
OK
RFID Code: 172D9B32
AT+HTTPPARA="URL",http://mywebsite.000webhostapp.com/test.php?code=172D9B32
OK
AT+HTTPPARA="CID",1
OK
AT+HTTPACTION=0
OK
AT+HTTPREAD=0,20
OK
If you take a closer look at the last part of the Arduino code, under the line myGsm.println("AT+HTTPACTION=0"); and under the line myGsm.println("AT+HTTPREAD=0,20"); there are some delays that almost all the other SIM900 examples use... I didn't use the delays but with the help from other people, I made it in a way that as soon as the SIM900 has an OUTPUT it just prints it out and eliminating the delay this way. It works fine for all the other commands, but for the last 2 commands it just does something random I think because it should give me the result from the echo of the php file...
NOW look if I enable the two delays:
myGsm.println("AT+HTTPACTION=0"); //submit the GET request
delay(8000);//the delay is important if the return data are very large, the time required longer.
printSerialData();
myGsm.println("AT+HTTPREAD=0,20"); // read the data from the website you access
delay(3000);
printSerialData();
By enabling these 2 line now the OUTPUT is this(correct):
AT+CGATT=1
OK
AT+SAPBR=3,1,"CONTYPE","GPRS"
OK
AT+SAPBR=3,1,"APN","internet.wind"
OK
AT+SAPBR=2,1
+SAPBR: 1,1,"X.X.X.X"
OK
AT+SAPBR=1,1
OK
AT+HTTPINIT
OK
RFID Code: 172D9B32
AT+HTTPPARA="URL",http://mywebsite.000webhostapp.com/test.php?code=172D9B32
OK
AT+HTTPPARA="CID",1
OK
AT+HTTPACTION=0
OK
+HTTPACTION:0,200,16
AT+HTTPREAD=0,20
+HTTPREAD:16
SUCCESS 172D9B32
OK
I am trying to setup a connection to my MySql database via a php page which is hosted on 123-reg. The PHP page is "http://domainName.biz/android_connect/get_all_bars.php" which at the moment the page comes up blank?
The code for that page is as follows:
// 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 pubbar");
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["pubbar"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$pubbar = array();
$pubbar["Pubbar_ID"] = $row["Pubbar_ID"];
$pubbar["Pubbar_Name"] = $row["Pubbar_Name"];
$pubbar["Pubbar_AddressLine1"] = $row["Pubbar_AddressLine1"];
$pubbar["Pubbar_AddressLine2"] = $row["Pubbar_AddressLine2"];
$pubbar["Pubbar_LocationID"] = $row["Pubbar_LocationID"];
$pubbar["Pubbar_Postcode"] = $row["Pubbar_Postcode"];
$pubbar["Pubbar_Latitude"] = $row["Pubbar_Latitude"];
$pubbar["Pubbar_Longitude"] = $row["Pubbar_Longitude"];
$pubbar["Pubbar_TypeID"] = $row["Pubbar_TypeID"];
$pubbar["Pubbar_DateCreated"] = $row["Pubbar_DateCreated"];
$pubbar["Pubbar_DateModified"] = $row["Pubbar_DateModified"];
// push single product into final response array
array_push($response["pubbar"], $pubbar);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No bars found";
// echo no users JSON
echo json_encode($response);
}
This code works on my local WAMP server on my PC
As you can see at the top it connect to another PHP page called "db_connect.php" and the code for that is below:
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();
}
}
Again this work on my local WAMP server database. This also connects to another PHP page called "db_config.php" and the code for that is below:
<?php
/*
* All database connection variables
*/
define('DB_USER', "<USER>"); // db user
define('DB_PASSWORD', "<PASSWORD>"); // db password (mention your db password here)
define('DB_DATABASE', "<DATABASE>"); // database name
define('DB_SERVER', "cust-mysql-X-X"); // db server
?>
As mentioned I have a wamp server setup for testing usage and all this functions as expected through that. However now I wish to put it on my server here, so it is all permanently accessible for my portfolio Android application and the get_all_bars.php page is coming up blank. I've messed around and changed code where I thought it might need changing but unfortunately the page still comes up blank. I have spoke with them before and the config data i.e username, password etc is all correct but I cannot figure out what might be wrong in the rest of this code.
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.
I do not have any other option, but to ask here again... and problem is killing me for the past 5 hours. I got button that call javascript function, and then javascript opens another php page and does insert in MySQL database.
HTML code:
<ul>
<li id="ConfirmButton" name="Insert" onclick="GetAllIDs()"><a>Potvrdi</a></li>
</ul>
Javascript code:
var request_type;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
request_type = new XMLHttpRequest();
}
var http = request_type;
http.open('get', 'insert.php?MatchID='+MatchID+'&TipID='+TipID+'&UserID=' + 1,true);
http.send(null);
PHP code:
include('config.php');
$matchID = $_GET['MatchID'];
$tipID = $_GET['TipID'];
$userID = $_GET['UserID'];
// Escape User Input to help prevent SQL Injection
$MatchID = mysql_real_escape_string($matchID);
$TipID = mysql_real_escape_string($tipID);
$UserID = mysql_real_escape_string($userID);
$insertTicket_sql = "INSERT INTO
betslips(DateTime,MatchID,TipID,UserID)
VALUES(".$MatchID.",".$TipID.",'".date("Y-m-d H:i:s")."',".$UserID.")";
$insertTick= mysql_query($insertTicket_sql) or die(mysql_error());
So after I run this code and I use break point I see in my php code all parameters I sent over forms normally and it's all there, but when I reach code $insertTick I get error
web server exited unexpectedly, restarting new instance.
Has anyone seen this problem before, and how can I deal with it?
Thanks
did anyone seen this problem before?
Not me, I dont use the mysql_* functions.
Your INSERT query parameter and values dont match.
So ive ported your example code to PDO perhaps its some interest:
<?php
//PDO Connect
try{
$con = new PDO('mysql:host=127.0.0.1;dbname=yourDB','root','password');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$con->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}catch (Exception $e){
die('Cannot connect to database. Details:'.$e->getMessage());
}
//Check that the variables are set
if(isset($_GET['MatchID']) && isset($_GET['TipID']) && isset($_GET['UserID'])){
//Prepare your query
$query = $con->prepare("INSERT INTO betslips (DateTime,MatchID,TipID,UserID)
VALUES ('".date("Y-m-d H:i:s")."', :matchID, :tipID, :userID)");
//Bind your values with the placeholders
$query->bindParam(":matchID", $_GET['MatchID']);
$query->bindParam(":tipID", $_GET['TipID']);
$query->bindParam(":userID", $_GET['UserID']);
//Execute
$query->execute();
die('Success!');
}else{
die('Error: Parameter not set.');
}
?>
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.