i have the following problem... i am building an android app and i regeuest text formated in utf8 (greek chars) from editTexts by using the POST method. The POST method gets the greek chras from the editTexts as '???' and insert them in mysal again as '???'
How will the POST recognize my greek chars???
<?php
// PHP variable to store the host address
$db_host = "localhost";
// PHP variable to store the username
$db_uid = "lolen";
// PHP variable to store the password
$db_pass = "lolen";
// PHP variable to store the Database name
$db_name = "lolen";
// PHP variable to store the result of the PHP function 'mysql_connect()' which establishes the PHP & MySQL connection
$db_con = mysql_connect($db_host,$db_uid,$db_pass) or die('could not connect');
mysql_query("SET character_set_results=utf8", $db_con);
mb_language('uni');
mb_internal_encoding('UTF-8');
mysql_select_db($db_name, $db_con);
mysql_query("set names 'utf8'",$db_con);
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['k_p']) )
{
$Kwdikos_Proiontos=$_POST['k_p'];
$Proion=$_POST['p'];
$Kwdikos_Tupou=$_POST['k_t'];
//$Tupos=$_POST['t'];
$sql=mysql_query("SELECT * FROM tupoi WHERE Kwdikos_Tupou LIKE '". $_POST["k_t"]."'", $db_con);
while($row = mysql_fetch_array($sql))
{
$output[]=$row['Tupos'];
$re= json_encode($output[0]);
$dd= json_decode($re, true);
}
$result =mysql_query("INSERT INTO proionta(Kwdikos_Proiontos, Proion, Kwdikos_Tupou, Tupos) VALUES('$Kwdikos_Proiontos', '$Proion', '$Kwdikos_Tupou', '$dd')");
//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);
}
?>
ps. my db is already in utf8 cause i display and add other data in greek, by using SELECT , INSERT, in the db.
Finally i found a solution to my problem, i used GET method instead of POST, and now it works correctly! Thnx for the sql injection tips, i will read more about this issue!
Related
I am trying to send data (temperature, humidity and time) from postman through API link for testing my code. I upload my php files in hostinger.com and every time I am trying to send data through postman it gives me OK and no errors but the data not showing in my phpmyadmin database table!
my insert.php code:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
//Creating Array for JSON response
$response = array();
// Check if we got the field from the user
if (isset($_GET['temp']) && isset($_GET['hum']) && isset($_GET['time'])) {
$temp = $_GET['temp'];
$hum = $_GET['hum'];
$time = $_GET['time'];
// Include data base connect class
$filepath = realpath (dirname(__FILE__));
require_once($filepath."/db_connect.php");
// Connecting to database
$dbo = new DB_CONNECT();
// Fire SQL query to insert data in weather
$result = "INSERT INTO 'climate'('temp', 'hum', 'time') VALUES('$temp', '$hum', '$time')";
// Check for succesfull execution of query
if ($result) {
// successfully inserted
$response["success"] = 1;
$response["message"] = "climate successfully created.";
// Show JSON response
echo json_encode($response);
} else {
// Failed to insert data in database
$response["success"] = 0;
$response["message"] = "Something has been wrong";
// Show JSON response
echo json_encode($response);
}
} else {
// If required parameter is missing
$response["success"] = 0;
$response["message"] = "Parameter(s) are missing. Please check the
request";
// Show JSON response
echo json_encode($response);
}
?>
and my db_connect.php :
<?php
class DB_CONNECT {
// Connecting to mysql (phpmyadmin) database
// Constructor
function __construct() {
// Trying to connect to the database
$this->connect();
}
// Destructor
function __destruct() {
// Closing the connection to database
$this->close();
}
// Function to connect to the database
function connect() {
//importing dbconfig.php file which contains database credentials
$filepath = realpath (dirname(__FILE__));
require_once($filepath."/dbconfig.php");
// Connecting to mysql (phpmyadmin) database
$con = mysqli_connect($dbhost_name, $username, $password);
// Selecing database
// returing connection cursor
return $con;
}
// Function to close the database
function close() {
// Closing data base connection
mysqli_close($con);
}
}
?>
and this is my link in postman I am using:
http://mydomain in hostinger.com/api/insert.php?temp=25&hum=80&time=2019-05-
09 08:00:00
and the result is:
{
"success": 1,
"message": "climate successfully created."
}
Is there any problem with my code?
Thanks for all
You haven't actually executed the query. $result is actually $query, and should be passed to your db connection $dbo.
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
trying to update a database using this code
<?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['name']) && isset($_POST['username']) && isset($_POST['password']) && isset($_POST['phone']) && isset($_POST['email'])&& isset($_POST['licno'])&& isset($_POST['licdate'])&& isset($_POST['meddate'])&& isset($_POST['flighttime'])&& isset($_POST['income'])&& isset($_POST['costs'])&& isset($_POST['pending'])&& isset($_POST['nextpayment'])&& isset($_POST['total'])) {
$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$licno = $_POST['licno'];
$licdate = $_POST['licdate'];
$meddate = $_POST['meddate'];
$flighttime = $_POST['flighttime'];
$income = $_POST['income'];
$costs = $_POST['costs'];
$pending = $_POST['pending'];
$nextpayment = $_POST['nextpayment'];
$total = $_POST['total'];
define('DB_USER', ""); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', ""); // database name
define('DB_SERVER', ""); // db server
// array for JSON response
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD,DB_DATABASE);
$sql = "UPDATE login SET username = '$username', password = '$password', phone = '$phone', email = '$email', license = '$licno', expiration = '$licdate', meddate = '$meddate', flighttime = '$flighttime', income = '$income', costs = '$costs', pending = '$pending', nextpayment = '$nextpayment', total = '$total' WHERE name = $name";
$result = $conn->query($sql) or die (mysqli_connect_error());
// mysql update row with matched pid
// check if row inserted or not
if ($result) {
// successfully updated
$response["success"] = 1;
$response["message"] = "Patient details 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 get no response and the db doesnt update, i dont know whats wrong, im sure im sending all parameters and the name im sending corresponds with the name in the db
in android studio i get this error msg
org.json.JSONException: End of input at character 0 of
i know the mistake is not in android studio, its somewhere in this php cause i get the same eror if i do it with postman
Database parameters are blank in this post but not in the real code , so thats not the problem either
At the end of the query, change WHERE name = $name"; to WHERE name = '$name'";
Define your database details. Right now its blank.
define('DB_USER', ""); // db user empty
define('DB_PASSWORD', ""); // db password empty
define('DB_DATABASE', ""); // database name
define('DB_SERVER', ""); // db server empty
Also recommend don't define your database details openly.
I am trying to do php post to mysql databse using a android app and a website url.
But I do not know how to make a post request through a url.
I tried http://localhost/api/create_product.php?name=chetan&price=2000&description=someDescription
This returns required fields missing.
Maybe the url I'm trying to pass is incorrect
Help me to know that how do I do a post in DB using URL that returns JSON for success.
<?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);
}
?>
DB_CONNECT() is working fine as I am able to do a GET query successfully
http://localhost/api/create_product.php?name=chetan&price=2000&description=someDescription => This is a request with GET parameters and your statement here :
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {
Are checking for POST parameters, either you change every $_POST by $_GET, either you change your method of passing arguments cause usually when you give arguments to put it in a database it's through POST and not GET for security reasons. GET parameters are used to read something but not insert.
I wanna save chinese
if I don't have use utf8 to save it will be "?" ,so how to use utf8 to save.
or have other way can save chinese , make it not be "?".
thank help for everyone.
this it my php code (source code on internet)
<?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);
}
?>
if you get your data from a form in browser you have to set the browser to utf8 like this :
<meta charset="UTF-8">
and you have to set your database's table
collation to utf8
and your php connection to database to utf8
mysql_query("SET NAMES 'utf8'");
before
$result = mysql_query("INSERT INTO products(name, price, description) VALUES('$name', '$price', '$description')");
try
mysql_query("SET CHARSET utf8");
We have one android application which access WAMP Server using PHP. All queries like, Select* etc working fine. But insert query not working properly in specific condition,
When WAMP already have some data in database we failed to insert new data in database. But when WAMP server don't have any existing data then insert query work successfully. following is PHP code we are using to insert a data,
<?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['UserName']) && isset($_POST['UserID']) && isset($_POST['Password']) && isset($_POST['Age'])&& isset($_POST['ContactNumber']) && isset($_POST['expiryDate'])) {
$UserName = $_POST['UserName'];
$UserID = $_POST['UserID'];
$Password = $_POST['Password'];
$Age = $_POST['Age'];
$ContactNumber = $_POST['ContactNumber'];
$expiryDate = $_POST['expiryDate'];
// 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 normaluser(UserName, UserID, Password,Age,ContactNumber,expiryDate) VALUES('$UserName', '$UserID', '$Password','$Age','$ContactNumber','$expiryDate')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "New user successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! error is there.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required fields is missing";
// echoing JSON response
echo json_encode($response);
}
?>
Can you guys please help use to solved this problem?
Ignoring the using of mysql_* which is deprecated and lack of sanitization of data.
You do not check if this User is already on the database. Assuming at least one of your columns is a unique or Primary key then this query is likely to fail if you try and create the same user twice.
But regardless of that possible issue if you add some useful error processing to your code you will be told exactly what the problem is. This is a little simplistic as you probably dont want these errors sent back to a user but it will tell you the exact error being returned from MySQL:
$result = mysql_query("INSERT INTO normaluser(UserName, UserID, Password,Age,ContactNumber,expiryDate)
VALUES('$UserName', '$UserID', '$Password','$Age','$ContactNumber','$expiryDate')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "New user successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = 'Database error ' . mysql_errno() . ' ' . mysql_error();
// echoing JSON response
echo json_encode($response);
}