Can't update database using php and Mysql - php

I am trying to update a user password in database with the following code
<?php
session_start();
if( isset($_SESSION['user']) ){
}
else
{
header("location: index.php");
}
$host = "localhost";
$username = "xxxx";
$password = "xxxxx";
$db_name = "auth_db";
$tbl_name = "users";
$link = new mysqli("$host", "$username" , "$password", "$db_name");
if(mysqli_connect_error())
{
die('Connect Error ('.mysqli_connect_errno().')' .msqli_connect_error());
}
$username = $_SESSION['user'];
$pwd = $_POST['oldpass'];
$pwd1 = $_POST['newpass'];
$pwd2 = $_POST['newpass1'];
if($pwd1 !== $pwd2)
{
Print '<script>alert("New Passwords do not match");</script>';
Print '<script>window.location.assign("pwd.php");</script>';
}
$query = mysqli_query($link, "SELECT * from users WHERE username = '$username'");
$user_exist = mysqli_num_rows($query);
$tbl_user = "";
$tbl_password = "";
$password = 0 ;
if($user_exist > 0)
{
while($row = mysqli_fetch_assoc($query))
{
$tbl_user = $row['username'];
$tbl_password = $row['password'];
$password = password_verify($pwd, $tbl_password);
}
if(($username == $tbl_user) && ($password))
{
if($password)
{
$new_hash = password_hash(('$pwd1'), PASSWORD_BCRYPT);
mysqli_query($link, "UPDATE $tbl_name SET password = '$new_hash' WHERE username = '$tbl_user'");
Print '<script>alert("Updated, Please relogin.");</script>';
Print '<script>window,location.assign("logout.php");</script>';
}
}
else
{
Print '<script>alert("Incorrect Password");</script>';
Print '<script>window,location.assign("pwd.php");</script>';
}
}
?>
I am able to generate the hash but it is not getting updated in the database and the page is redirected to the given link. I am thinkinging that there is something worng with my
mysqli_query($link, "UPDATE $tbl_name SET password = '$new_hash' WHERE username = '$tbl_user'");
Any help is appreciated. Thank you.

your code has many syntax errors. i have cited some and put it in comments so you can change it yourself.
<?php
session_start();
if( isset($_SESSION['user']) ){
}
else
{
header("location: index.php");
}
$host = "localhost";
$username = "xxxx";
$password = "xxxxx";
$db_name = "auth_db";
$tbl_name = "users";
$link = new mysqli("$host", "$username" , "$password", "$db_name");
if(mysqli_connect_error())
{
die('Connect Error ('.mysqli_connect_errno().')' .msqli_connect_error());
}
$username = $_SESSION['user'];
$pwd = $_POST['oldpass'];
$pwd1 = $_POST['newpass'];
$pwd2 = $_POST['newpass1'];
if($pwd1 !== $pwd2)
{
Print '<script>alert("New Passwords do not match");</script>';
Print '<script>window.location.assign("pwd.php");</script>';
}
$query = mysqli_query($link, "SELECT * from users WHERE username = '$username'");
$user_exist = mysqli_num_rows($query);
$tbl_user = ""; // instead of reinitializing these as a blank slate just use the unset(); function
$tbl_password = ""; // so its unset($tbl_user); so you can save memory.
$password = 0 ;
if($user_exist > 0)
{
while($row = mysqli_fetch_assoc($query))
{
$tbl_user = $row['username'];
$tbl_password = $row['password'];
$password = password_verify($pwd, $tbl_password);
}
if(($username == $tbl_user) && ($password))
{
if($password)
{
$new_hash = password_hash(('$pwd1'), PASSWORD_BCRYPT);
mysqli_query($link, "UPDATE $tbl_name SET password = '$new_hash' WHERE username = '$tbl_user'");
Print '<script>alert("Updated, Please relogin.");</script>';
Print '<script>window,location.assign("logout.php");</script>'; //<- window.location.assign();
}
}
else
{
Print '<script>alert("Incorrect Password");</script>';
Print '<script>window,location.assign("pwd.php");</script>'; //<-- window.location.assign();
}
}
?>

Try this
$link = new mysqli($host, $username , $password, $db_name);
mysqli_query($link, "UPDATE $tbl_name SET pasword = ".$new_hash." WHERE username = ".$tbl_user.");

Related

php user,admin base project with login,signup,abd index page

I'm working on a project which is a user, admin dashboard . first I have a page where is tell user/admin to signup in that i have email, passowrd, cpassword, department, schemes (both are select option field) and designation(like, collector, SdM, ETC) ,and role(user, admin). now then user/admin signup its detail fill in database and then he go to login page and write its email and password and he redirected to login page where also department and schemes select option field .
my question is that what should be logic that when a user/admin signup , the details which he enter and select from select filed that should be displayed to index page .
like he select department(education and its scheme ) so that scheme only display on index page no other department and scheme
i said again my signin and index page is same like 10department and there 50 schemes each of them. user select and he only see on index page that is fill in signin page
just tell me logic
thankyou
code
signin.php
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Connection Established
$server = "localhost";
$username = "root";
$password = "";
$database = "registration";
$conn = mysqli_connect($server, $username, $password, $database);
if (!$conn){
// echo "success";
// }
// else{
die("Error". mysqli_connect_error());
}
$Email = $_POST["Email"];
$password = $_POST["password"];
$cpassword = $_POST["cpassword"];
$department = $_POST["department"];
$schemes = $_POST["schemes"];
$designation = $_POST["designation"];
$Role = $_POST["Role"];
// $exists=false;
$existSql = "SELECT * FROM `usertable` WHERE Email = '$Email'";
$result = mysqli_query($conn, $existSql);
mysqli_set_charset($conn,'utf8'); // for hindi font language issue
$numExistRows = mysqli_num_rows($result);
if($numExistRows > 0){
// $exists = true;
$showError = "Email Already Exists";
}
else{
// $exists = false;
if(($password == $cpassword)){
$hash = password_hash($password, PASSWORD_DEFAULT);
$sql = "INSERT INTO `usertable` (`Email`,`password`,`department`,`schemes`,`designation`,`Role`, `dt`) VALUES ('$Email', '$hash','$department','$schemes','$designation','$Role', current_timestamp())";
$result = mysqli_query($conn, $sql);
if ($result){
$showAlert = true;
}
}
else{
$showError = "Passwords do not match";
}
}
}
// login.php
<?php
$login = false;
$showError = false;
// db Connection
if($_SERVER["REQUEST_METHOD"] == "POST"){
$server = "localhost";
$username = "root";
$password = "";
$database = "Registration";
$conn = mysqli_connect($server, $username, $password, $database);
if (!$conn){
// echo "success";
// }
// else{
die("Error". mysqli_connect_error());
}
$Email = $_POST["Email"];
$password = $_POST["password"];
// $sql = "Select * from users where username='$username' AND password='$password'";
$sql = "Select * from usertable where Email='$Email'";
$result = mysqli_query($conn, $sql);
$num = mysqli_num_rows($result);
if ($num == 1){
while($row = mysqli_fetch_assoc($result)){
if (password_verify($password, $row['password'])){
$login = true;
session_start();
$_SESSION['loggedin'] = true;
$_SESSION['Email'] = $Email;
header("location: index.php");
}
else{
$showError = "Invalid Email";
}
}
}
else{
$showError = "Invalid Email Or Password";
}
}
?>

Can't fetch data from MySQL (php) (Re-edited)

I have realized why i can't actually access userdata (after i am logged) old way to find the username is $_SESSION['username']; (assuming there is a row as 'username' in MySQL database)
So as i have a test account as "good25" (reason to choose numbers was to see if Alphanumeric inputs works fine.. its just checkup by me.. nevermind)
Problem :
assuming, i have rows in a table as 'username' and all of his information.. such as 'password', 'email', 'joindate', 'type' ...
On net i found out how to snatch out username from Session
<?php session_start(); $_SESSION('username'); ?>
successful!!
i had an idea to check if session is actually registering or no??
after a log on start.php i used this code
if(isset($_SESSION['username'])) { print_r($_SESSION['username']); }
the result was "1" (while i logged in using this username "good25")
any suggestions?
index.php (lets say, index.php just holds registration + Login form + registration script.. in login form, action='condb.php')
<?php
require 'condb.php';
if (isset($_POST['btn-signup']))
{
//FetchInputs
$usern = mysqli_real_escape_string($connection,$_POST['username']);
$email = mysqli_real_escape_string($connection,$_POST['email']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
$repassword = mysqli_real_escape_string($connection,$_POST['repassword']);
$usern = trim($usern);
$email = trim($email);
$password = trim($password);
$repassword = trim($repassword);
//SearchUser
$searchusr = "SELECT username FROM $user_table WHERE username='$usern'";
$usersearched = mysqli_query($connection, $searchusr);
$countuser = mysqli_num_rows($usersearched);
//SearchEmail
$searcheml = "SELECT email FROM $user_table WHERE email='$email'";
$emlsearched = mysqli_query($connection, $searcheml);
$counteml = mysqli_num_rows($emlsearched);
//RegisteringUser
if ($countuser == 0)
{
if ($counteml == 0)
{
$ctime = time();
$cday = date("Y-m-d",$ctime);
$aCode = uniqid();
$adduser = "INSERT INTO $user_table(username, email, password, realname, activationcode, verified, joindate, type, points) VALUES ('$usern','$email','$password','$name','$aCode','n','$cday','Free',$signPoints)";
if (mysqli_query($connection, $adduser))
{
?><script>alert('You have been registered');</script><?php
}
else {
?><script>alert('Couldnt Register, please contact Admin<br><?mysqli_error($connection);?>');</script><?php
}
} else {
?><script>alert('Email already exists!');</script><?php
}
} else {
?><script>alert('Username already exists!');</script><?php
}
}
?>
condb.php
$connection = mysqli_connect($db_server, $db_user, $db_pass);
mysqli_select_db($connection, $db_name);
if(!$connection) {
die ("Connection Failed: " . mysqli_connect_error);
}
if (isset($_POST['btn-login']))
{
$uname = mysqli_real_escape_string($connection,$_POST['uname']);
$upass = mysqli_real_escape_string($connection,$_POST['upass']);
//FindUser
$finduser = "SELECT * FROM $user_table WHERE username='$uname' AND password='$upass'";
$findinguser = mysqli_query($connection,$finduser);
$founduser = mysqli_num_rows($findinguser);
//ConfirmPassword
if ($founduser > 0)
{
session_start();
$_SESSION['username'] = $username;
$_SESSION['username'] = true;
if ($findinguser != false)
{
while ($fetchD = mysqli_fetch_array($findinguser, MYSQLI_ASSOC))
{
$fetchD['username'] = $usernn;
$fetchD['email'] = $email;
$fetchD['userid'] = $uid;
$fetchD['realname'] = $rlnm;
$fetchD['points'] = $pts;
$fetchD['type'] = $membertype ;
}
header("Location: start.php");
} else {
echo mysqli_error();
}
} else {
header("Location: index.php");
?><script>alert('Wrong details, please fill in correct password and email');</script><?php
}
}
I am not asking you to build a script.. just little help please? (Thank you so so so so so much, as i am a self-learner, you don't have to say everything.. just a clue is enough for me)
may be you can try this code
<?php
require_once 'require.inc.php';
//session_start();
if (isset($_POST['btn-login']))
{
$uname = mysqli_real_escape_string($_POST['uname']);
$upass = mysqli_real_escape_string($_POST['upass']);
$search = mysqli_query($connection, "SELECT username, userid, password from $user_table WHERE username='$uname' AND password='$upass'");
$match = mysqli_fetch_assoc($search);
if ($match == 1 and $match['password'] == md5($upass))
{
$_SESSION['username'] = $match['userid'];
} else {
?>
<script>alert('Password or E-mail is wrong. If you havent registered, Please Register');</script>
<?php
}
}
if (isset($_SESSION['username']) or isset($match['userid'])){
header("Location:start.php");
}
if (isset($_POST['btn-signup']))
{
$name = mysqli_real_escape_string($_POST['name']);
$usern = mysqli_real_escape_string($_POST['username']);
$email = mysqli_real_escape_string($_POST['email']);
$password = mysqli_real_escape_string($_POST['password']);
$repassword = mysqli_real_escape_string($_POST['repassword']);
$name = trim($name);
$usern = trim($usern);
$email = trim($email);
$password = trim($password);
$repassword = trim($repassword);
$query = "SELECT email FROM $user_table WHERE email='$email'";
$result = mysqli_query($connection, $query);
$count = mysqli_num_rows($result);
$querytwo = "SELECT username FROM $user_table WHERE username='$usern'";
$resulttwo = mysqli_query($connection, $querytwo);
$counttwo = mysqli_num_rows($resulttwo);
if ($count == 0 AND $counttwo == 0)
{
if ($password == $repassword) {
if (mysqli_query($connection, "INSERT INTO $user_table(username, email, password, realname) VALUES ('$usern','$email','$password','$name')"))
{
?>
<script> alert ('Successfully registered'); </script>
<?php
}
}else {
?>
<script> alert ('The Password you entered, doesnt match.. Please fill in the same password'); </script>
<?php
}
}
else {
?>
<script> alert('Username or E-mail already exist'); </script>
<?php
}
}
?>
and this is for require.inc.php
<?php
global $username;
//require 'dconn.php';
session_start();
$_SESSION["username"] = $username;
$connection = mysqli_connect("localhost","root","", "test") or die(mysqli_error());
// Check Login
if (isset($_SESSION['username']) and isset ($match['userid']))
{
$Selection = "SELECT * FROM $user_table WHERE username='$username'";
$selectQuery = mysqli_query($connection, $Selection);
if ($selectQuery != false)
{
while ($fetchD = mysqli_fetch_assoc($selectQuery))
{
$usernn = $fetchD['username'];
$email = $fetchD['email'];
$uid = $fetchD['userid'];
}
} else {
echo mysqli_error();
}
}
?>
#suggestion, create session after user login and authorized then for each page start session and take session which you created and perform SQL queries using that session variable.
for example :
$_SESSION['user_name']=$row['username'];
for each page:
session_start();
$user_name=$_SESSION['user_name'];
SQL query
mysqli_query($con,"SELECT * FROM users where column_name='$user_name'");
I think you need to include dconn.php file in all files where you want to perform the mysql operation. If you have included it only in require.inc.php then you you it in all your other files.

"mysqli_num_rows" struggles with the output of "mysqli_query"

I made a simple Login Form there are some errors in the code I guess.
Everything is working fine but I'm struggling with the MySQL(mysqli) Query part.
But here is my code first:
<?php
session_start();
if(isset($_SESSION['acuser']))
{
redirectpage();
}
else
{
if($_POST)
{
if(isset($_POST['button']) && ($_POST['username']) && ($_POST['password']))
{
$db = 'datenbank';
$dbuser = 'root';
$dbpass = '';
$dbhost = 'localhost';
$connection = mysqli_connect($dbhost,$dbuser,$dbpass);
$selection = mysqli_select_db($connection,$db);
$username = mysqli_real_escape_string($connection,(htmlspecialchars($_POST['password'])));
$password = mysqli_real_escape_string($connection, (htmlspecialchars($_POST['password'])));
$password = md5($password);
if($connection)
{
if($selection)
{
$queryuser = "SELECT * FROM main WHERE Username = '$username'";
$result = mysqli_query($connection, $queryuser);
$checkuser = mysqli_num_rows($result);
if($checkuser)
{
$querypass = "SELECT * FROM main WHERE Username = '$username' AND Password ='$password'";
$resultpass = mysqli_query($connection,$querypass);
$checkpass = mysqli_num_rows($resultpass);
if($checkpass)
{
$data = mysqli_fetch_array ($resultpass);
$_SESSION["acID"] = $data["Id"];
$_SESSION["acUSERNAME"] = $data["Username"];
$_SESSION["acPASSWORD"] = $data["Password"];
$_SESSION["acEMAIL"] = $data["Email"];
}
// Some else stuff
?>
I guess there is something wrong with "mysqli_query()" and "mysqli_num_rows()"!
"Mysqli_num_rows()" can't handle the output of "mysqli_query()" somehow!
Maybe i will find an answer here
Not sure if this is the problem:
$username = mysqli_real_escape_string($connection,(htmlspecialchars($_POST['password'])));
is the username the same as the password in the database?

Login suddenly stopped working

I'm working on my school project and I need a simple login functionality. It was working 20 minutes ago but then I perhaps made some mistake. It doesn't show any error message. The database seems to be alright.
'jmeno' = name, 'heslo' = password
<?php $mysqli = new mysqli("localhost","admin","admin","uzivatele");
if(isset( $_POST['heslo']) && isset($_POST['jmeno'])){
$username = $_POST['heslo'];
$password = $_POST['jmeno'];
/* defends SQL injection */
// $username = stripslashes($username);
//$password = stripslashes($password);
//$password = mysqli_real_escape_string($mysqli, ($_POST['heslo']));
//$username = mysqli_real_escape_string($mysqli, $_POST['jmeno']);
$sqllogin = "SELECT * FROM prihlaseni WHERE jmeno = '".$username."' AND heslo = '".$password."' LIMIT 1";
$result = mysqli_query($mysqli, $sqllogin);
if (!$result) {
die(mysqli_error($mysqli));
}
$count = mysqli_num_rows($result);
if ($count == 1) {
session_start();
$_SESSION['loggedin'] = true;
header('Location: home.php');
}else {
echo "<script language='javascript'>alert('Wrong password!');</script>";
}
}
?>
I think you mixed post values. Try :
$username = $_POST['jmeno'];
$password = $_POST['heslo'];
I suggest debugging as follows:
<?php $mysqli = new mysqli("localhost","admin","admin","uzivatele");
if(isset( $_POST['heslo']) && isset($_POST['jmeno'])){
$username = $_POST['heslo'];
$password = $_POST['jmeno'];
/* defends SQL injection */
// $username = stripslashes($username);
//$password = stripslashes($password);
//$password = mysqli_real_escape_string($mysqli, ($_POST['heslo']));
//$username = mysqli_real_escape_string($mysqli, $_POST['jmeno']);
$sqllogin = "SELECT * FROM prihlaseni WHERE jmeno = '".$username."' AND heslo = '".$password."' LIMIT 1";
echo $sqllogin; //check the sql query string
$result = mysqli_query($mysqli, $sqllogin);
print_r($result);
if (!$result) {
die(mysqli_error($mysqli));
}
$count = mysqli_num_rows($result);
if ($count == 1) {
session_start();
$_SESSION['loggedin'] = true;
header('Location: home.php');
}else {
echo "<script language='javascript'>alert('Wrong password!');</script>";
}
}
?>
If sql string seems correct try querying the database directly and check output.
Probably there its not getting the $_POST vars, and not returning a valid $result.
Also I suggest you to not handle and save passwords like that but using hash functions like md5(string).

Requesting Username & Password In PHP Session

i tried to put username & password dynamically but
It doesnt work with stored username & password in DB and stays on same page....
really depressed.
<?php include "../db/db_connection.php";
$username = $_POST['txt_username'];
$pwd =$_POST["txt_pwd"];
if(empty($username) || $username == ""){
header("location:index.php?err_msg=1");
exit;
}
if(empty($pwd) || $pwd == ""){
header("location:index.php?err_msg=2");
exit;
}
$sql = "SELECT username,password FROM users WHERE username= '$username' and password= '$pwd'";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result)==1){
header("location:dashboard.php");
}
else{
header("location:index.php?err_msg=3");
}
if($_REQUEST['txt_username'] == $username && $_REQUEST['txt_pwd'] == $pwd){
$_SESSION['txt_username'];
$_SESSION['txt_pwd'];
header("Location:dashboard.php");
}
else{
header("Location:index.php");
}
?>`
Those lines doesn't nothing..
$_SESSION['txt_username'];
$_SESSION['txt_pwd'];
maybe:
$_SESSION['txt_username'] = $user;
$_SESSION['txt_pwd'] = ...;
?
You can try this, I am not sure if this is exactly what you are looking for...
<?php session_start();
$username = $_POST['txt_username'];
$pwd =$_POST["txt_pwd"];
if(empty($username) || $username == ""){
header("location:index.php?err_msg=1");
exit;
}
if(empty($pwd) || $pwd == ""){
header("location:index.php?err_msg=2");
exit;
}
$sql = "SELECT username,password FROM users WHERE username= '$username' and password= '$pwd'";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result)==1){
$_SESSION['txt_username'] = $username;
$_SESSION['txt_pwd'] = $pwd;
header("location:dashboard.php");
}
else{
header("location:index.php?err_msg=3");
}
header("Location:index.php"); // if it stays on the same page remove this line
?>
I restructured your code to look more clean.
Also I suggest you to avoid using mysql and start using mysqli (or PDO) to avoid SQL injection attacks.
<?php session_start();
if(isset($_SESSION['txt_username']) && !empty($_SESSION['txt_username'])) {
//If we enter here the user has already logged in
header("Location:dashboard.php");
exit;
}
if(!isset($_POST['txt_username'])) {
header("location:index.php?err_msg=1");
exit;
}
else if(!isset($_POST["txt_pwd"])) {
header("location:index.php?err_msg=2");
exit;
}
$username = $_POST['txt_username'];
$pwd = $_POST["txt_pwd"];
//We use MYSQL with prepared statements BECAUSE MYSQL IS DEPRECATED
$mysqli = new mysqli('localhost', 'my_bd_user', 'mi_bd_password', 'my_bd');
$sql = "SELECT 1 FROM users WHERE username= ? and password = ?";
$stmt = $mysql->prepare($sql);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
if(!empty($result)) {
//IF we enter here user exists with that username and password
$_SESSION['txt_username'] = $username;
header("location:dashboard.php");
exit;
}
else{
header("location:index.php?err_msg=3");
}
Try it.
I checked your code and found everything is correct .I wold like you to add connection file on this.
Like
$username = "root";
$password = "password";//your db password
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("db name",$dbhandle)
or die("Could not select Database");
Thanks
Try below code :
i have reviewed and changed your code :
<?php session_start();
mysqli_connect("locahost","username","password");
mysqli_select_db("database_name");
$username = trim($_POST['txt_username']);
$pwd = trim($_POST["txt_pwd"]);
if($username == ''){
header("location:index.php?err_msg=1");
exit;
}
if($pwd == ""){
header("location:index.php?err_msg=2");
exit;
}
$sql = "SELECT `username`,`password` FROM users WHERE `username`= '".$username."' and password= '".$pwd."'";
$result = mysqli_query($sql);
if(mysqli_num_rows($result)>0){
$_SESSION['txt_username'] = $username;
$_SESSION['txt_pwd'] = $pwd;
header("location:dashboard.php");
}
else{
header("location:index.php?err_msg=3");
}
?>

Categories