Android Update MySQL table through PHP - php

I am working on an Android App. I need to update a register, I didn't have issues with entries. But when I try to update the table, Doesn't work
this my PHP
<?php
require_once 'include/userupdate.php';
$username = "";
$name = "";
$movil="";
$email = "";
$password = "";
$fnac = "";
$calle_numero_piso ="";
$nom_urba = "";
$cod_postal ="";
$localidad="";
$observaciones="";
/////////////////
if(isset($_POST['username'])){
$username = $_POST['username'];
}
if(isset($_POST['name'])){
$name = $_POST['name'];
}
if(isset($_POST['movil'])){
$movil = $_POST['movil'];
}
if(isset($_POST['email'])){
$email = $_POST['email'];
}
if(isset($_POST['password'])){
$password = $_POST['password'];
}
if(isset($_POST['fnac'])){
$fnac = $_POST['fnac'];
}
if(isset($_POST['calle_numero_piso'])){
$calle_numero_piso = $_POST['calle_numero_piso'];
}
if(isset($_POST['nom_urba'])){
$nom_urba = $_POST['nom_urba'];
}
if(isset($_POST['cod_postal'])){
$cod_postal = $_POST['cod_postal'];
}
if(isset($_POST['localidad'])){
$localidad = $_POST['localidad'];
}
if(isset($_POST['observaciones'])){
$observaciones = $_POST['observaciones'];
}
// Instance of a User class
$userObject = new User();
// update user
$json_registration = $userObject->updateRegisterUser($username, $name, $movil, $email, $password, $fnac, $calle_numero_piso, $nom_urba, $cod_postal, $localidad, observaciones );
echo json_encode($json_registration);
}
?>
And this my update.php
<?php
include_once 'db.php';
class User{
private $db;
private $db_table = "users";
public function __construct(){
$this->db = new DbConnect();
}
mysqli_close($this->db->getDb());
return false;
}
public function updateRegisterUser($username, $name, $movil, $email, $password, $fnac, $calle_numero_piso, $nom_urba, $cod_postal, $localidad, $observaciones ){
$query = "UPDATE users SET name = '$name', movil = '$movil', email = '$email', password = '$password', fnac = '$fnac', calle_numero_piso = '$calle_numero_piso', nom_urba ='$nom_urba', cod_postal = '$cod_postal', localidad = '$localidad', observaciones = '$observaciones' WHERE username = $username;";
$updated = mysqli_query($this->db->getDb(), $query);
if($updated == 1){
$json['success'] = 1;
}else{
$json['success'] = 0;
}
mysqli_close($this->db->getDb());
return $json;
}
public function loginUsers($username, $password){
$json = array();
$canUserLogin = $this->isLoginExist($username, $password);
if($canUserLogin){
$json['success'] = 1;
}else{
$json['success'] = 0;
}
return $json;
}
}
?>
I believe I there is something wrong with both php, but I am not sure where.

try this , as obvious your username is a string so it should be kept inside single quotes
$query = "UPDATE users SET name = '$name', movil = '$movil', email = '$email', password = '$password', fnac = '$fnac', calle_numero_piso = '$calle_numero_piso', nom_urba ='$nom_urba', cod_postal = '$cod_postal', localidad = '$localidad', observaciones = '$observaciones' WHERE username = '$username'";
One advise for best practice is, always make some primary key recommended as int autoincrement which will help to enforce uniqueness because in this case you can have two users with same name which will be a problem when your database grows.

Related

Why is this piece of code not writing anything into database?

I need a second pair of eyes to have a look at my code and tell me what I am missing, as I think I have identified the portion of code that doesn't work, I just don't know why.
Basically I am trying to register a user to a database, in a way that it prevents SQL injection. For the life of me however, it doesn't work. When I deconstruct the code and make it less secure, it works. Anyway, code is here:
//require_once 'sendEmails.php';
session_start();
$username = "";
$email = "";
$user_dob = "";
$user_fname = "";
$user_lname = "";
$user_telephone = "";
$errors = [];
$servername = '';
$login = '';
$password = '';
$DBname = '';
$rows = 0;
$query = "";
$conn = new mysqli($servername, $login, $password, $DBname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($conn) {
echo "Connected successfully";
}
// SIGN UP USER
if (isset($_POST['signup-btn'])) {
if (empty($_POST['username'])) {
$errors['username'] = 'Username required';
}
if (empty($_POST['email'])) {
$errors['email'] = 'Email required';
}
if (empty($_POST['password'])) {
$errors['password'] = 'Password required';
}
if (isset($_POST['password']) && $_POST['password'] !== $_POST['passwordConf']) {
$errors['passwordConf'] = 'The two passwords do not match';
}
if (empty($_POST['dob'])) {
$errors['dob'] = 'Date of birth required';
}
if (empty($_POST['fname'])) {
$errors['fname'] = 'First name required';
}
if (empty($_POST['lname'])) {
$errors['lname'] = 'Last name required';
}
if (empty($_POST['telephone'])) {
$errors['telephone'] = 'Telephone number required';
} //--checks input in browser
//I think it works untill this point...
$token = bin2hex(random_bytes(50)); // generate unique token
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT); //encrypt password
$user_dob = $_POST['dob'];
$user_fname = $_POST['fname'];
$user_lname = $_POST['lname'];
$user_telephone = $_POST['telephone'];
$email = $_POST['email'];
//Above assigns inputted values into variables declared at the start
//echo $token, $email; //-- this works
//nl2br() ; // -- line break in php
// Check if email already exists
//$result = $mysqli->query("SELECT * FROM User_tbl WHERE email='$email' LIMIT 1");
$sql = "SELECT * FROM User_tbl WHERE email='$email' LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > $rows) {
$errors[] = $email;
echo "Email already exists";
}
$errorsInt = count($errors);
echo mysqli_num_rows($result);
echo count($errors);
echo $errorsInt;
if ($errorsInt === $rows) {
$query = "INSERT INTO User_tbl SET token=?, username=?, password=?, user_dob=?, user_fname=?, user_lname=?, user_telephone=?, email=?";
// "INSERT INTO User_tbl VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
echo $query;
//---------------------------------------------------------------------------
$stmt = $conn->prepare($query); //first
$stmt->bind_param('sssissis', $token, $username, $password, $user_dob, $user_fname, $user_lname, $user_telephone, $email);
$result = $stmt->execute();
echo $result;
if ($result) {
$user_id = $stmt->insert_id;
$stmt->close();
$_SESSION['id'] = $user_id;
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['verified'] = false;
$_SESSION['message'] = 'You are logged in!';
$_SESSION['type'] = 'alert-success';
header('location: index.php');
} else {
$_SESSION['error_msg'] = "Database error: Could not register user";
}
}
}
The problem I believe starts here:
$stmt = $conn->prepare($query); //first
$stmt->bind_param('sssissis', $token, $username, $password, $user_dob, $user_fname, $user_lname, $user_telephone, $email);
$result = $stmt->execute();

Show error message if that particular content is not in database

Here I have code where user is going to be created, they have to enter one accesscode given by admin. That accesscode is limited by some users like 10 or 20. After that it shows error like your accesscode is limited. So until now, it's working fine.
Now if user tries to enter accesscode that is not given by admin it has to show error message like your accesscode is wrong.
Here is my code:
<?php
require('../config.php');
require_once($CFG->dirroot . '/user/editlib.php');
$errorMessage = '';
$successMessage = '';
if(isset($_SESSION['successMessage'])) {
$successMessage = $_SESSION['successMessage'];
unset($_SESSION['successMessage']);
}
if (isset($_POST['register'])) {
$errors = array();
$data = array();
$chk_sql = "SELECT * FROM {user} u where username = ?";
if (!empty($chk_sql) ) {
$errorMessage = 'Username already taken';
}
if(!$chk_username = $DB->get_record_sql($chk_sql, array($_POST['username']))) {
$secret = $_POST['secret'];
$access_code_sql = "SELECT * FROM {accesscode} WHERE random_no= ? and `number` > `used` and status=1";
if($chk_secret = $DB->get_record_sql($access_code_sql, array($secret))) {
$cadminid = $chk_secret->cadmin_id;
$clientid = $chk_secret->clientid;
$DB->execute("UPDATE {accesscode} SET used = used+1 WHERE random_no = '$secret'");
$insert_record = new stdClass();
$insert_record->firstname = $_POST['firstname'];
$insert_record->lastname = $_POST['lastname'];
$insert_record->username = $_POST['username'];
$insert_record->secret = $secret;
$insert_record->password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$insert_record->timecreated = time();
$insert_record->maildigest = $cadminid;
$insert_record->maildisplay = $clientid;
$insert_record->idnumber = 1;
$insert_record->mnethostid = 1;
$insert_record->confirmed = 1;
$insert_record->email = $_POST['email'];
if ($result = $DB->insert_record('user', $insert_record)) {
$_SESSION['successMessage'] = "record created successfully";
header('Location: register.php');
} else
$errorMessage = "error! can you please try again";
} else
$errorMessage = "your access code limit completed";
}
}
?>
Can you give us more information about your problem? What doesn't work?Try some "var_dump()" in your loop to know if you pass through or not so you can tell us where is the problem !
But first thing I see is here :
if(! $chk_username = $DB->get_record_sql($chk_sql, array($_POST['username'])) )
and here :
if($result = $DB->insert_record('user', $insert_record))
You should use "==" or "===" because using "=" means you assign a value to "$chk_username" and "result".
Then here is some librairie you can use if you want to display flash message, this is just for your information :
https://github.com/plasticbrain/PhpFlashMessages
And if you want to do it in JS you can use : https://github.com/CodeSeven/toastr
Hope it helps !
i changed the condition like this
<?php
require('../config.php');
require_once($CFG->dirroot . '/user/editlib.php');
$errorMessage = '';
$successMessage = '';
if(isset($_SESSION['successMessage']))
{
$successMessage = $_SESSION['successMessage'];
unset($_SESSION['successMessage']);
}
if (isset($_POST['register'])) {
$errors = array();
$data = array();
$chk_sql = "SELECT * FROM {user} u where username = ?";
if (!empty($chk_sql) ) {
$errorMessage='Username already taken';
}
if(!$chk_username = $DB->get_record_sql($chk_sql, array($_POST['username']))
)
{
$secret = $_POST['secret'];
$access_code_sql = "SELECT * FROM {accesscode} WHERE random_no= ? and
status=1";
if($chk_secret = $DB->get_record_sql($access_code_sql, array($secret)) )
{
if ( $chk_secret->used >= $chk_secret->number ) {
$errorMessage = "your access code limit completed..";
}else
{
$cadminid = $chk_secret->cadmin_id;
$clientid = $chk_secret->clientid;
$DB->execute("UPDATE {accesscode} SET used = used+1 WHERE random_no = '$secret'");
$insert_record = new stdClass();
$insert_record->firstname = $_POST['firstname'];
$insert_record->lastname = $_POST['lastname'];
$insert_record->username = $_POST['username'];
$insert_record->secret = $secret;
$insert_record->password = password_hash($_POST['password'],
PASSWORD_DEFAULT);
$insert_record->timecreated = time();
$insert_record->maildigest = $cadminid;
$insert_record->maildisplay = $clientid;
$insert_record->idnumber = 1;
$insert_record->mnethostid = 1;
$insert_record->confirmed = 1;
$insert_record->email = $_POST['email'];
if($result = $DB->insert_record('user', $insert_record))
{
$_SESSION['successMessage'] = "record created successfully";
header('Location: register.php');
}
else
$errorMessage = "error! can you please try again";
}
}
else
$errorMessage = "your access code is wrong..";
}
}
?>
it's working..

How to make Login in UWP using PHP and MYSQL

I want to make login and registration in my UWP app using PHP and MySQL
I use this code below to do it but it didn't work
I try many ways in internet but its so old
I make PHP and MySQL Database in a localhost xampp
I'm beginner in PHP so pleas anyone tell me the error in my code
I use this code to POST data to serve in UWP :
private async void Button_Click(object sender, RoutedEventArgs e)
{
Uri requestUri = new Uri("http://localhost/test/index.php");
HttpStringContent stringContent = new HttpStringContent
(" { \"email\": \"" + emailbox.Text + "\" , \"password\":\"" + passwordbox.Text + "\" } "
, Windows.Storage.Streams.UnicodeEncoding.Utf8
, "application/json");
//Dictionary<string, string> pairs = new Dictionary<string, string>();
//pairs.Add("email", emailbox.Text);
//pairs.Add("password", passwordbox.Text);
//HttpFormUrlEncodedContent encodedContent = new HttpFormUrlEncodedContent(pairs);
Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient();
await client.PostAsync(requestUri, stringContent);
}
And This is my PHP backend code
config.php
<?php
define("DB_HOST","127.0.0.1");
define("DB_USER","root");
define("DB_PASSWORD","");
define("DB_NAME","firstdb");
?>
db_connect.php
<?php
include_once 'config.php';
class DbConnect{
private $connect;
public function __construct(){
$this->connect = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno($this->connect)){
echo "Unable to connect to MySQL Database: " . mysqli_connect_error();
}
}
public function getDb(){
return $this->connect;
}
}
?>
user.php
<?php
include_once 'db_connect.php';
class User{
private $db;
private $db_table = "users";
public function __construct(){
$this->db = new DbConnect();
}
public function isLoginExist($email, $password){
$query = "select * from ".$this->db_table." where email = '$email' AND password = '$password' Limit 1";
$result = mysqli_query($this->db->getDb(), $query);
if(mysqli_num_rows($result) > 0){
mysqli_close($this->db->getDb());
return true;
}
mysqli_close($this->db->getDb());
return false;
}
public function isEmailUsernameExist($email){
$query = "select * from ".$this->db_table." where email = '$email'";
$result = mysqli_query($this->db->getDb(), $query);
if(mysqli_num_rows($result) > 0){
mysqli_close($this->db->getDb());
return true;
}
return false;
}
public function isValidEmail($email){
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
public function createNewRegisterUser( $email, $password){
$isExisting = $this->isEmailUsernameExist($email);
if($isExisting){
$json['success'] = 0;
$json['message'] = "Error in registering. Probably the username/email already exists";
}
else{
$isValid = $this->isValidEmail($email);
if($isValid)
{
$query = "insert into ".$this->db_table." (email, password) values ('$email','$password')";
$inserted = mysqli_query($this->db->getDb(), $query);
if($inserted == 1){
$json['success'] = 1;
$json['message'] = "Successfully registered the user";
}else{
$json['success'] = 0;
$json['message'] = "Error in registering. Probably the username/email already exists";
}
mysqli_close($this->db->getDb());
}
else{
$json['success'] = 0;
$json['message'] = "Error in registering. Email Address is not valid";
}
}
return $json;
}
public function loginUsers($email, $password){
$json = array();
$canUserLogin = $this->isLoginExist($email, $password);
if($canUserLogin){
$json['success'] = 1;
$json['message'] = "Successfully logged in";
}else{
$json['success'] = 0;
$json['message'] = "Incorrect details";
}
return $json;
}
}
?>
index.php
<?php
require_once 'user.php';
$username = "";
$password = "";
$email = "";
if(isset($_POST['email'] && isset($_POST['password']))){
$email = $_POST['email'];
}
if(isset($_POST['password'])){
$password = $_POST['password'];
}
$userObject = new User();
// Registration
if(!empty($password) && !empty($email)){
$hashed_password = md5($password);
$json_registration = $userObject->createNewRegisterUser($email, $hashed_password);
echo json_encode($json_registration);
}
// Login
if(!empty($password) && empty($email)){
$hashed_password = md5($password);
$json_array = $userObject->loginUsers($email, $hashed_password);
echo json_encode($json_array);
}
?>
I would recommend you to use a Password Entry instead of a visible entry in your app like a PasswordBox. Try to make your request like that.
var loginUrl = "http://localhost/test/index.php";
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>
{ { "username", emailbox.Text }, { "password", passwordbox.Text } };
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync(loginUrl, content);
string result = await response.Content.ReadAsStringAsync();
}

Login form validation always says WRONG USER DETAILS

This php code for login form validation. Why it always returns 'Wrong user data' (Грешни данни!). $name & $pass1 come from the login form which is in other file.
$activated has values 0 || 1 and it is to see if user confirmed registration from email.
<?php
//connection with database
require "db_connect.php";
require "password_compat-master/lib/password.php";
$name = mysqli_real_escape_string($conn, stripslashes(trim(filter_input(INPUT_POST, 'name'))));
$pass1 = mysqli_real_escape_string($conn, stripslashes(trim(filter_input(INPUT_POST, 'pass1'))));
$errorName = '';
$errorPass1 = '';
$feedback = '';
$mainError = false;
//get hash
$retHash = "SELECT password FROM users WHERE user_name='$name'";
$query_retHash = mysqli_query($conn, $retHash);
$row = mysqli_fetch_array($query_retHash);
$hash = $row['password'];
//get name
$retName = "SELECT user_name FROM users WHERE user_name='$name'";
$query_retName = mysqli_query($conn, $retName);
$row = mysqli_fetch_array($query_retName);
$uname = $row['user_name'];
//get 'activated'
$retAct = "SELECT user_name FROM users WHERE user_name='$name'";
$query_retAct = mysqli_query($conn, $retAct);
$row = mysqli_fetch_array($query_retAct);
$activated = $row['activated'];
if (filter_input_array(INPUT_POST)) {
if ($name !== $uname) {
$mainError = true;
}
if (!password_verify($pass1, $hash)) {
$mainError = true;
}
if ($activated != 1) {
$mainError = true;
}
if (!$mainError) {
$feedback = 'Здравей,' . $name . '!';
} else {
$feedback = 'Грешни данни!';
}
}
?>
As #Rajdeep Answered,
$retAct = "SELECT user_name FROM users WHERE user_name='$name'";
^ it should be activated
Better use one query. Fetch all details.
<?php
//connection with database
require "db_connect.php";
require "password_compat-master/lib/password.php";
$name = mysqli_real_escape_string($conn, stripslashes(trim(filter_input(INPUT_POST, 'name'))));
$pass1 = mysqli_real_escape_string($conn, stripslashes(trim(filter_input(INPUT_POST, 'pass1'))));
$errorName = '';
$errorPass1 = '';
$feedback = '';
$mainError = false;
//get hash
$retHash = "SELECT * FROM users WHERE user_name='$name'";
$query_retHash = mysqli_query($conn, $retHash);
$row = mysqli_fetch_array($query_retHash);
$hash = $row['password'];
$uname = $row['user_name'];
$activated = $row['activated'];
if (filter_input_array(INPUT_POST)) {
if ($name !== $uname) {
$mainError = true;
}
if (!password_verify($pass1, $hash)) {
$mainError = true;
}
if ($activated != 1) {
$mainError = true;
}
if (!$mainError) {
$feedback = 'Здравей,' . $name . '!';
} else {
$feedback = 'Грешни данни!';
}
}
?>
Look at this statement here,
//get 'activated'
$retAct = "SELECT user_name FROM users WHERE user_name='$name'";
^ it should be activated
And there's no point running three separate queries. You can achieve the same thing using only one query, like this:
// your code
$query = "SELECT user_name, password, activated FROM users WHERE user_name='$name' LIMIT 1";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_array($result);
$uname = $row['user_name'];
$hash = $row['password'];
$activated = $row['activated'];
if (filter_input_array(INPUT_POST)) {
// your code
}

Convert MySQL login script to PDO

I've written a functional login script using MySQL. However, I've now been told that it needs to be done using PDO, and I've a functional PDO connection:
function getConnection()
{
$userName = '*****';
$password = '*****';
$dbname = '******';
$db = new PDO("mysql:host=localhost;dbname=$dbname", $userName, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
However I've no idea how to convert the login query to PDO.
if (isset($_REQUEST['attempt']))
{
$user = $_POST['user'];
$password = $_POST['password'];
$qry = mysql_query
("SELECT *
FROM subscriber
WHERE email = '$user'
AND password = '$password'")
or die(mysql_error());
$total = mysql_num_rows($qry);
if ($total > 0)
{
session_start();
$_SESSION['user'] = 'yes';
header('location: account.php');
exit;
}
else
{
// Do nothing.
}
}
How can I do it?
To get you started:
$db = getConnection();
$stmt = $db->prepare("
SELECT * FROM subscriber WHERE email = :email AND password = :password
");
$stmt->bindParam(":email" , $user );
$stmt->bindParam(":password", $password);
$stmt->execute();
$total = $stmt->rowCount();
Non-bloated version:
$stm = $pdo->prepare("SELECT * FROM subscriber WHERE email = ? AND password = ?");
$stm-> execute($_POST['user'], $_POST['password']);
if ($id = $stm->fetchColumn()) {
session_start();
$_SESSION['user'] = $id;
header('location: account.php');
exit;
}
You can also use this example if you would not like to use bindParam. But I extracted it from #eggyal's answer. Great thanks go to eggyal.
<?php session_start();
include_once('pdo.inc.php');
$username = (isset($_POST['username']))? trim($_POST['username']): '';
$password = (isset($_POST['password']))? $_POST['password'] : '';
$pas = md5($password);
$redirect = (isset($_REQUEST['redirect']))? $_REQUEST['redirect'] :
'view.php';
$query = ("SELECT username FROM site_user WHERE username=:username
AND password =:password");
$query_login = $con->prepare($query);
$query_login->execute(array(
':username'=>$username,
':password'=>$pas));
$result = $query_login->rowCount();
if($result>0)
{
$_SESSION['username'] = $username;
$_SESSION['logged'] = 1;
echo "success";
}
else {
// Set these explicitly just to make sure
echo 'User name invalid';
}
?>

Categories