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.
Related
I'm currently working on a login system (which works great by using two text fields and the user is then redirected). However, as I am developing a mobile app, it would be much easier to do this in JSON, and I am not entirely sure where to start. What I am basically looking to do is to use a https post request (from my app) so it would request: https://www.example.com/login.php?username=username&password=password
I have created a basic sample, but it's not what I'm looking to do with regards to passing in a parameter via the URL as my code just currently looks for users in the MySQL database and outputs the users in JSON. What I want to be able to do is pass in the username & password parameters, via the URL, and then output a "success" or "error" JSON response if the username/password is in the database or not.
<?php
$host = "localhost";
$username = "root";
$password = "password";
$db_name = "test";
$con = mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
$sql = "select * from test_table";
$result = mysql_query($sql);
$json = array();
if (mysql_num_rows($result))
{
while ($row = mysql_fetch_row($result))
{
$json['items'] = $row;
}
}
mysql_close($db_name);
echo json_encode($json, JSON_PRETTY_PRINT);
?>
Edit
I have now started working on another system, which is pretty much what I am looking to do (after I found an example here: http://www.dreamincode.net/forums/topic/235556-how-to-create-a-php-login-with-data-from-mysql-database/) except every time that I request something like https://www.example.com/login.php?username=root&password=password - I get the JSON error 1 code
<?php
$host = "localhost"; // Host name
$db_username = "root"; // Mysql username
$db_password = "password"; // Mysql password
$db_name = "test"; // Database name
$tbl_name = "test_table"; // Table name
// Connect to server
mysql_connect("$host", "$db_username", "$db_password") or die("cannot connect");
// Select the database
mysql_select_db("$db_name") or die("cannot select DB");
// Get the login credentials from user
$username = $_POST['username'];
$userpassword = $_POST['password'];
// Secure the credentials
$username = mysql_real_escape_string($_POST['username']);
$userpassword = mysql_real_escape_string($_POST['password']);
// Check the users input against the DB.
$query = "SELECT * FROM test_table WHERE user = '$username' AND password = '$userpassword'";
$result = mysql_query($query) or die("Unable to verify user because " . mysql_error());
$row = mysql_fetch_assoc($result);
if ($row['total'] == 1) {
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
}
else {
// username and password not found
// failed
$response["failed"] = 1;
// echoing JSON response
echo json_encode($response);
}
?>
Try to change following lines and it should works. I get it to work, as the way you describe it.
1- Here you will get URL parameters and sanitize.
$username = $_GET['username'];
$userpassword = $_GET['password'];
$username = mysql_real_escape_string($username);
$userpassword = mysql_real_escape_string($userpassword);
2- Here you count how many rows you have
Change $row = mysql_fetch_assoc($result);
to $total_rows = mysql_num_rows($result);
3- Here you check if you have at least 1 row.
And change if ($row['total'] == 1) { to if ($total_rows == 1) {
That should give output {"success":1}
Note1: This is to solve your request and question, but does not necessary means the right approach or perfect solution in general.
Note2: I would suggest you think of password hashing, post method in stead of get, use mysqli or PDO in sted of mysql and input sensitization and not use URL to pass username and password. I would suggest you look at this link it describes some of the things I mentioned in my note1.
http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
I am creating an android application and submit the user details from Android application to php at server side by JSON. But at server side I am not getting the JSON data. At server side php the JSON comes from android application is seems null. I am using POST method for this. I know that my POST method code is wrong in PHP at server side. But I have no idea to solve this.
Here is my PHP code for getting JSON. Every time I get same message:
Required fields missing
Code:
<?php
/*
* Following code will create a new user row
* All user details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
print_r($_POST);
// check for required fields
if (isset($_POST['Firstname']) && isset($_POST['Lastname']) && isset($_POST['Username']) && isset($_POST['Email']) && isset($_POST['Password']) && isset($_POST['Country']) && isset($_POST['Mobile'])) {
echo('bhargavi');
$Firstname = $_POST['Firstname'];
$Lastname = $_POST['Lastname'];
$Username = $_POST['Username'];
$Email = $_POST['Email'];
$Password = $_POST['Password'];
$Country = $_POST['Country'];
$Mobile = $_POST['Mobile'];
// 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 users(Firstname,Lastname,Username,Email,Password,Country,Mobile) VALUES('$Firstname','$Lastname','$Username','$Email','$Password','$Country','$Mobile')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "User successfully Registered.";
// 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);
}
?>
Probably you should decode the json string before checking $_POST['Firstname'] etc...
Let's say you send from the app a string called data. On php you should do something like that:
$data = json_decode($_POST['data']);
and then check if $data contains the data you neeed by doing:
if (isset($data->Firstname) && isset($data->Lastname) etc...){
...
...
}
If I can give you an advice it would be better if you check data integrity directly from your app instead of doing it on your server, it would give the chance to spare some server resources...
As Jay Blanchard already mentioned don't use mysql like that or you'll be exposed to mysql injection...
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);
}
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!
I'm trying to look up user's username using $_GET but not actually seing the result of the query. Here's the code:
<?php
$host = "localhost";
$username = "root";
$password = "toor"; // :)
$database = "db";
$link = mysql_connect($host, $username, $password);
if(!$link){
exit('Could not connect to database: '. mysql_error());
}
$email = mysql_real_escape_string(htmlspecialchars(stripslashes($_GET["e"])));
$query = "SELECT username FROM cc_card WHERE email = '$email'";
$result = mysql_query($query);
if(mysql_num_rows($result)){
$user = mysql_fetch_assoc($result);
echo $user['username'];
} else {
echo "Something's wrong";
}
it's only returnung "Something's wrong". I wanted it to display the username field of the cc_card table where email = email. What am I doing wrong?
If you're getting "Something's wrong" from the posted code it means nowhere in the cc_card table does the email column match the email value you specify in your query.
You need to verify that the contents of your sanitized $email variable do, in fact, exist somewhere in the table. Try:
} else {
echo "Something's wrong";
var_dump($email);
}
To see the contents of the sanitized $email variable and manually query the database from the shell (or phpmyadmin or whatever) to find whether the value you're specifying exists or not. I'm betting it doesn't exist.
You'd better add the error check after the query.
if (!$result) {
die('Error: ' . mysql_error());
}
If no error, then it means there is no matched email in your database.