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.
Related
I have 3 php files to connect phpmyadmin database.
Content of /Android/db_connect.php:
<?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());
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
}
}
?>
Content of /Android/db_config.php:
<?php
/*
* All database connection variables
*/
define('DB_USER', "u155019120_movie"); // db user
define('DB_PASSWORD', "xxxxxxxxx"); // db password (mention your db password here)
define('DB_DATABASE', "u155019120_movie"); // database name
define('DB_SERVER', "mysql.hostinger.web.tr"); // db server
?>
Content of /publichtml/get_all_products:
<?php
/*
* Following code will list all the products
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/../Android/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);
}
?>
When i open http://moviestolike.pe.hu/get_all_products.php page (also you can view), it says
Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home/u155019120/Android/db_connect.php on line 28
{"products":[{"pid":"1","name":"sogan","price":"19.30","created_at":"2016-03-12 15:08:38","updated_at":"0000-00-00 00:00:00"},{"pid":"2","name":"faltak","price":"22.00","created_at":"2016-03-12 15:08:38","updated_at":"0000-00-00 00:00:00"}],"success":1}
it gives right products. But when i change the deprecated method as
// Connecting to mysql database
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
in first file i wrote here, the output is
Deprecated: mysql_select_db(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home/u155019120/Android/db_connect.php on line 31
Access denied for user ''#'10.2.1.37' to database 'u155019120_movie'
What is wrong? I don't even know what 10.2.1.37 is. My username is what i wrote here.
Also i cant change mysql_select to mysqli_select, it wants one more parameter.
Correct syntax for mysqli_connect
mysqli_connect(host,username,password,dbname,port,socket);
port and socket fields are optional you can ignore those two by using it as
mysqli_connect(host,username,password,dbname);
This question already has answers here:
mysqli_query() expects parameter 1 to be mysqli, object given
(3 answers)
Closed 2 years ago.
I got this error when i try to save database in mysql using wampServer.
mysqli_query() expects parameter 1 to be mysqli, object given in
there are 3 PHP files, db_config.php and db_connect.php and create_person.php and i already reated table PERSON in phpmyadmin.
db_config.php
<?php
/*
* All database connection variables
*/
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "othmane"); // database name
define('DB_SERVER', "localhost"); // db server
?>
db_connect.php
<?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 = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysqli_error());
// Selecing database
$db = mysqli_select_db($con, DB_DATABASE) or die(mysqli_error()) or die(mysqli_error());
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysqli_close();
}
}
?>
create person.php :
<?php
/*
* Following code will create a new person row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['nom']) && isset($_POST['pass_world'])) {
$name = $_POST['nom'];
$pass = $_POST['pass_world'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result =mysqli_query($db,"INSERT INTO person (nom,pass_world) VALUES ('$name', '$pass')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} 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);
}
?>
Your
$db = new DB_CONNECT();
returns an instance of DB_CONNECT class.
What you need in your
mysqli_query(...)
call is the object returned by your mysqli_connect call.
Try changing your:
function __construct() {
// connecting to database
$this->connect();
}
with:
function __construct() {
// connecting to database
$this->conn = $this->connect();
}
Then, change:
$result =mysqli_query($db,"INSERT INTO person (nom,pass_world) VALUES ('$name', '$pass')");
with:
$result =mysqli_query($db->conn,"INSERT INTO person (nom,pass_world) VALUES ('$name', '$pass')");
Also, I think you should read the PHP manual for the functions you are using:
mysqli_connect
mysqli_select_db
I am creating an android app that was previously used with a MySQL database, however now I have to use a SQL Server database. Are there any applications or resources that can convert one to the other?
Here is an example of the php code I was using to connect to the MySQL database:
db_connect.php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
/**
* 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';
define('__ROOT__',dirname(dirname(__FILE__)));
require_once __ROOT__ . '/android_connect/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();
}
}
?>
create_product.php
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {
$name = $_POST['name'];
$price = $_POST['price'];
$description = $_POST['description'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, price, description) VALUES('$name', '$price', '$description')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} 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);
}
?>
I am having difficulty getting my Android application to transmit the input it has received to myphpadmin server.
I am wondering what do i need to add to my Andriod coding so that my application is able to get the php script to run and transmit the information to the server.
What i have done so far is creating php scripts for configuration and connection purpose.
<?php
define('DB_USER', "root"); // db user
define('DB_PASSWORD', "password"); // db password (mention your db password here)
define('DB_DATABASE', "Wifi"); // database name
define('DB_SERVER', "http://andy-009.dlink.net/"); // db server
?>
and
/**
* 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());
// returing connection cursor
return $con; }
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
} }
as well as a insertion php script
update_product.php
<?php
/*
* Following code will update a product information
* A product is identified by product id (pid)
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['WifiMacAddress']) && isset($_POST['WifiSSID']) && isset($_POST['WifiLatitude']) && isset($_POST['WifiLongtitude']) && isset($_POST['WifiLocation'])) {
$WifiMacAddress = $_POST['WifiMacAddress'];
$WifiSSID = $_POST['WifiSSID'];
$WifiLatitude = $_POST['WifiLatitude'];
$WifiLongtitude = $_POST['WifiLongtitude'];
$WifiLocation = $_POST['WifiLocation'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql update row with matched pid
$result = mysql_query("UPDATE Wifi SET WifiSSID = '$WifiSSID', WifiLatitude = '$WifiLatitude', WifiLongtitude = '$WifiLongtitude' , WifiLocation = '$WifiLocation' WHERE WifiMacAddress = $WifiMacAddress");
// check if row inserted or not
if ($result) {
// successfully updated
$response["success"] = 1;
$response["message"] = "Product 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);
}
?>
i think communicating between android and php, JSON would be helpful.
you can parse the data into JSON at both ends and transmit them over internet using web-services
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.