I have read all other PDO topic in stackoverflow and tried all the stuff, but still its not working, i don't know whats wrong
on the Edit/Change Password page
I am using this code
ob_start();
session_start();
require_once './../account/config.php';
$id = $_SESSION['id'];
if (isset($_POST["submit"])) {
$opwd = mysql_real_escape_string($_POST['oldpwd']);
$npass = mysql_real_escape_string($_POST['newpwd']);
$anpass = mysql_real_escape_string($_POST['renewpwd']);
$sql = "SELECT COUNT(*) AS count from users where id = :id";
try {
$stmt = $DB->prepare($sql);
$stmt->bindValue(":id", $id);
$stmt->execute();
$result = $stmt->fetchAll();
here, $result[0]["password"] is not fetching the result from table users and column password
I even tried $result["password"] but not working,
in other pages same method is working very perfect but here its not fetching result
So, even user puts correct old password, its returning Current Password is Incorrect
if($result[0]["password"] !== $opwd) {
$msg = "Current Password is Incorrect";
}
elseif($npwd !== $rnpwd) {
$msg = "New Passwords did not match.";
}
elseif (($result[0]["password"] === $opwd) && $npwd === $rnpwd) {
$sql = "UPDATE `users` SET (`password`, `retype`) = (:npswd , :anpwd) WHERE `id` = :id";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":npswd", $npass);
$stmt->bindValue(":anpwd", $anpass);
$stmt->bindValue(":id", $id);
$stmt->execute();
$msg = "Your Password is changed successfully";
$msgType = "success";
}
else {
$msg = "Error Occured. Please Contact us if you have some issue.";
}
}
catch (Exception $ex) {
echo $ex->getMessage();
}
}
Please guide me what am i missing here
Related
I'm currently working on a project and managed to get a working registration and login form. Upon registration, the user is emailed with a 5 character activation code and is asked to insert it on the user profile page in order to change the status from active:0 to active:1 and gains permission to the rest of the site.
For some reason the activation code just simply won't work :/
The following code is the PHP code written to activate the account, I am using PDO queries to connect to the database, but I tried using a mysqli query too but didn't seem to work.
<?php
session_start();
// Allow the config
define('__CONFIG__', true);
// Require the config
require_once "inc/config.php"; //possibly have to change the location
include_once "inc/classes/DB.php"; //possibly have to change location
include_once "inc/classes/Page.php";
include_once "inc/classes/User.php";
Page::ForceLogin();
//
//$email = filter_input(INPUT_POST['email'] );
//$username = Filter::String($_POST['username']);
//$skills = Filter::String($_POST['skills']);
//$email = filter_input(INPUT_POST['email'] );
//$username = filter_input(INPUT_POST['username'] );
$return=[];
$User = new User($_SESSION['user_id']);
$username = $User->username;
////Connection Variables
//$host = 'localhost';
//$user = 'root';
//$password = '';
//$db = 'mdb_';
////Creating mysql connection
//$conn = new mysqli($host,$user,$password,$db);
//$username = $User->username;
$activationCode = User::Find(INPUT_GET['activationCode']);
if(isset($_GET['activationCode'])) {
if(!empty($_GET['activationCode'])) {
$query = "SELECT * FROM users WHERE username='.$username.'";
$result = query($con, $query);
if(ocirowcount($result) > 0){
while($row = mysqli_fetch_array($result)){
if($_GET['activationCode'] == $row["activationCode"]){
$con->query ("UPDATE users SET active=1 AND credit=100 WHERE username = '.$username.'");
$return['error'] = 'Your account is now activated! You have earned 100 Time-banking credits.';
//header("Refresh:0");
}
else{
$return['error'] = 'Code incorrect, please try again';
}
}
}
echo json_encode($return, JSON_PRETTY_PRINT);
}
}
//$activationCode = filter_input(INPUT_GET, "activationCode" );
//if(isset($_GET['activationCode'])) {
// if(!empty($_GET['activationCode'])) {
// $query = "SELECT * FROM users WHERE username='$username'";
// $result = mysqli_query($conn, $query);
// if(mysqli_num_rows($result) > 0){
// while($row = mysqli_fetch_array($result)){
// if($_GET['activationCode'] == $row["activationCode"]){
// $sql = $conn->query ("UPDATE users SET active=1 AND credit=100 WHERE username = '$username'");
// $return['error'] = 'Your account is now activated! You have earned 100 Time-banking credits.';
// //header("Refresh:0");
// }
// else{
// $return['error'] = 'Code incorrect, please try again';
// }
// }
// }
// echo json_encode($return, JSON_PRETTY_PRINT);
// }
//}
//$activationCode = filter_input(INPUT_POST, "activationCode" );
//
// if(isset($_POST['activationCode'])) {
// $activationCode = Filter::String( $_POST['activationCode'] );
//
//
//
//
//
// $query = "SELECT * FROM users WHERE username='$username'";
// $result = mysqli_query($con, $query);
// if(mysqli_num_rows($result) > 0){
//
// while($row = mysqli_fetch_array($result)){
//
// if($_POST['activationCode'] == $row["activationCode"]){
//
//
// $activateUser = $con->query ("UPDATE `users` SET `credit` = :100, `active` = :1, WHERE `user_id` = :$user_id");
// //$sql = $con->query ("UPDATE users SET active=1, credit=100 WHERE username = '$username'");
//
// $return['error'] = 'Your account is now activated! You have earned 100 Time-banking credits.';
//
// header("Refresh:0");
// }
// else{
// $return['error'] = 'Code incorrect, please try again';
// }
//
// }
// }
//
// echo json_encode($return, JSON_PRETTY_PRINT);
//
//// }
// }
?>
The code below is the db class that creates the $con in PDO
class DB {
protected static $con;
private function __construct(){
try {
self::$con = new PDO( 'mysql:charset=latin1;host=host;port=****;dbname=mdb_', 'root', 'pass'); //change connection string
self::$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
self::$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
self::$con->setAttribute( PDO::ATTR_PERSISTENT, false );
self::$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (PDOException $e) {
echo "Could not connect todatabase."; exit;
}
}
public static function getConnection() {
//If this instance has not been started, start it.
if (!self::$con) {
new DB();
}
//Return the writeable db connection
return self::$con;
}
There are several issues here, from mixing database API's to possible SQL injection, string concatenation issues and incorrect SQL syntax in your UPDATE query.
If you're using PDO for your database connection, you need to remove all references to the oci* (which are for Oracle databases) and mysqli* (which is a different API and not compatible with PDO) functions, and use the PDO equivalents.
I will also remove $username from the queries and use prepared statements instead. $username may be coming from your own database, but I can't see how it got in there. If you do not have a limit on which characters a username can contain, and the username is properly escaped when it is inserted into your database, then it may contain single (or double) quotes that can still cause trouble in this code. Bottom line: if it was originally user input, it should never be trusted.
// I missed this in the code in your question
$con = DB::getConnection();
if (isset($_GET['activationCode'])) {
if(!empty($_GET['activationCode'])) {
// Note the placeholder ":username" -- PDO will fill that with
// $username for you (see $stmt->execute() below) and take care
// of adding quotes around it
$query = "SELECT * FROM users WHERE username = :username";
try {
$stmt = $con->prepare($query);
$stmt->execute(array(':username' => $username));
if ($stmt->rowCount() > 0) {
foreach ($stmt as $row) {
if ($_GET['activationCode'] == $row["activationCode"]) {
// note the syntax: "SET active=1, credit=100"
$update = $con->prepare("UPDATE users SET active=1, credit=100 WHERE username = :username");
$update->execute(array(':username' => $username));
$return['error'] = 'Your account is now activated! You have earned 100 Time-banking credits.';
//header("Refresh:0");
} else {
$return['error'] = 'Code incorrect, please try again';
}
}
}
} catch (PDOException $error) {
$return['error'] = (string)$error;
}
echo json_encode($return, JSON_PRETTY_PRINT);
}
}
Note that this can be somewhat optimised by just attempting the UPDATE query. For the sake of convenience, I'll also assume you only want the activation code to be able to be used on inactive accounts, which you aren't currently checking:
$con = DB::getConnection();
if (isset($_GET['activationCode']) && !empty($_GET['activationCode'])) {
$query = "UPDATE users SET active = 1, credit = 100 WHERE username = :username AND activationCode = :code AND active = 0";
try {
$stmt = $con->prepare($query);
$stmt->execute(array(
':username' => $username,
':code' => $_GET['activationCode']
));
if ($stmt->rowCount() > 0) {
$return['error'] = 'Your account is now activated! You have earned 100 Time-banking credits.';
} else {
$return['error'] = 'Code incorrect or account is already active, please try again';
}
} catch (PDOException $error) {
$return['error'] = (string)$error;
}
echo json_encode($return, JSON_PRETTY_PRINT);
}
For the last week a have been stuck on one part of my website, the register script. I have got it to create new users in the database which is fine however it when someone enters a duplicate user name that I have issues with.
The database is set up to not allow duplicated so if you try you get a lovely error printed on the web page and although functional doesn't look great.,
what I have been trying to do and have looked at many many examples of how to do it but it never works for me. I Would love some help and please don't be a jerk and say there are answers/ it's a duplicate because I have tried. If you don't want to help then move on :).
here is the code:
<?php
include 'pdo_connect.php';
if(!empty($_POST)) {
$uname = $_POST['uname'];
$upassword = password_hash($_POST['upassword'], PASSWORD_DEFAULT);
//here i want to search for the duplicate username and if none then carry on ar if match echo "alredy taken"
$query = 'INSERT INTO `users` ( `uname`, `password`) VALUES (?,?)'; //if duplicate exists returns a duplicate error.
$params = array($uname, $upassword);
$results = dataQuery($query, $params);
}
?>
UPDATE 1
<?php
include 'pdo_connect.php';
if(!empty($_POST)) {
$uname = $_POST['uname'];
$upassword = password_hash($_POST['upassword'], PASSWORD_DEFAULT);
//here i want to search for the duplicate username and if none then carry on ar if match echo "alredy taken"
try
{
$query = 'INSERT INTO `users` ( `uname`, `password`) VALUES (?,?)'; //if duplicate exists returns a duplicate error.
}
catch (Exception $e)
{
echo "username taken";
}
$params = array($uname, $upassword);
$results = dataQuery($query, $params);
}
?>
tried the try catch as suggested but same issue the server error is displayed on screen i think its because it still executes and it doesnt "crash".
here is the error i get: (when i try to register as admin which already exists)
error
UPDATE 2
same result :(
<?php
include 'pdo_connect.php';
if(!empty($_POST)) {
$uname = $_POST['uname'];
$upassword = password_hash($_POST['upassword'], PASSWORD_DEFAULT);
//here i want to search for the duplicate username and if none then carry on ar if match echo "alredy taken"
try
{
$query = 'INSERT INTO `users` ( `uname`, `password`) VALUES (?,?)'; //if duplicate exists returns a duplicate error.
$params = array($uname, $upassword);
$results = dataQuery($query, $params);
}
catch (Exception $e)
{
echo "username taken";
}
}
?>
UPDATE 2
<?php
include 'pdo_connect.php';
if(!empty($_POST)) {
$uname = $_POST['uname'];
$upassword = password_hash($_POST['upassword'], PASSWORD_DEFAULT);
//here i want to search for the duplicate username and if none then carry on ar if match echo "alredy taken"
try
{
$query = 'INSERT INTO `users` ( `uname`, `password`) VALUES (?,?)'; //if duplicate exists returns a duplicate error.
$params = array($uname, $upassword);
$results = dataQuery($query, $params);
}
catch (PDOException $e)
{
echo "username taken";
}
}
?>
still does the same :(
UPDATE 3
<?php
include 'pdo_connect.php';
if (!empty($_POST)) {
$uname = $_POST['uname'];
$upassword = password_hash($_POST['upassword'], PASSWORD_DEFAULT);
//here i want to search for the duplicate username and if none then carry on ar if match echo "alredy taken"
try {
$query = $ConString->prepare("SELECT * from users where uname = $uname ");
$query->execute([$uname]);
$results = $query->fetchall();
if (count($results) > 0) {
echo "username taken";
} else {
$query = 'INSERT INTO `users` ( `uname`, `password`) VALUES (?,?)';
$params = array($uname,$upassword);
$results = dataQuery($query, $params);
}
}
catch (Exception $e) {
echo "username taken";
}
}
?>
these 2 errors:
enter image description here
pdo_connect code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('USER', 'root');
define('PASS', 'pass');
function dataQuery($query, $params) {
$queryType = explode(' ', $query);
// establish database connection
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', USER, PASS);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
}
// run query
try {
$queryResults = $dbh->prepare($query);
$queryResults->execute($params);
if($queryResults != null && 'SELECT' == $queryType[0]) {
$results = $queryResults->fetchAll(PDO::FETCH_ASSOC);
return $results;
} else {
return $queryResults->rowCount();
}
$queryResults = null; // first of the two steps to properly close
$dbh = null; // second step tp close the connection
}
catch(PDOException $e) {
$errorMsg = $e->getMessage();
echo $errorMsg;
}
}
?>
Before insert you will need to run a select statement, select id or what ever from you users table that matches the username supplied on register, if the select statement return results then the username is taken otherwise run the insert.
<?php
include 'pdo_connect.php';
if (!empty($_POST)) {
$uname = $_POST['uname'];
$upassword = password_hash($_POST['upassword'], PASSWORD_DEFAULT);
//here i want to search for the duplicate username and if none then carry on ar if match echo "alredy taken"
try {
$query = $ConString->prepare("SELECT * from users where uname = ? ");
$query->execute([$uname]);
$results = $query->fetchall();
if (count($results) > 0) {
echo "username taken";
} else {
$query = 'INSERT INTO `users` ( `uname`, `password`) VALUES (?,?)';
$params = array($uname,$upassword);
$results = dataQuery($query, $params);
}
}
catch (Exception $e) {
echo "username taken";
}
}
?>
You will need to modify my code to match with your methods, because as it stand you have done your own sql functions.
found it!
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('USER', 'root');
define('PASS', 'Unhackable');
function dataQuery($query, $params) {
// what kind of query is this?
$queryType = explode(' ', $query);
// establish database connection
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', USER, PASS);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
}
// run query
try {
$queryResults = $dbh->prepare($query);
$queryResults->execute($params);
if($queryResults != null && 'SELECT' == $queryType[0]) {
$results = $queryResults->fetchAll(PDO::FETCH_ASSOC);
return $results;
} else {
return $queryResults->rowCount();
}
$queryResults = null; // first of the two steps to properly close
$dbh = null; // second step tp close the connection
}
catch(PDOException $e) {
$errorMsg = $e->getMessage();
echo "too slow, username already taken";
//echo $errorMsg;
}
}
?>
commented out echoing the error message and echoing a customised message, i know its not great but it does the job.
I am making a change password function. Currently It is just changing the password. But I want to amend it a bit. If email and password is valid then it should change the password, otherwise not. This is my code. Can anyone help me?
function CHANGE_PASSWORD($conn, $MSG)
{
$sql = $conn->prepare("UPDATE users SET password = ? WHERE email = ? AND password=?");
$sql->bind_param("sss", $newpass, $email, $password);
$email = $_REQUEST["EMAIL"];
$pass = $_REQUEST["PASSWORD"];
$newpass = $_REQUEST["NEW_PASSWORD"];
if ($sql->execute()) {
if($sql->affected_rows == 0) {
$json["STATUS"] = "FAIL";
$json["MESSAGE"] = "Invalid email / password";
} else {
$json["STATUS"] = "SUCCESS";
$json["MESSAGE"] = "Password Update Successful";
}
} else {
$json["STATUS"] = "ERROR";
$json["MESSAGE"] = "Please try again later.";
$json["ERROR"] = $sql->error_list;
}
$sql->close();
return json_encode($json);
#function ends
}
My Current URL looks like this
http://localhost/safespaces/server.php?REQUEST=CHANGE_PASSWORD&EMAIL=mr.aleem001%40gmail.com&PASSWORD=haioye&NEW_PASSWORD=12345
To fetch a row, use
$result = $sql->get_result();
$row = $result->fetch_assoc();
I Hope it Helps
am currently working on a project and i have the script for insertion.my table is called survey and the fields are id,username,password,province. the username is set to unique key. the insertion process is working fine without any duplicate entry but when i try to insert a duplicate entry at always shows me this error
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'bluff' for key 'username'
I know what this error mean, my problem is that how can i can if username already exist or not i want an alert message to pop up..
here is my code
class.user.php
public function username($username){
$stmt = $this->db->prepare("SELECT count(*) FROM tish_images WHERE username = :username");
$stmt->execute(array($username));
$number_of_rows = $result->fetchColumn();
if($number_of_rows >= 1) {
echo 'username does exist'; // or return so you get the value
} else {
echo 'username does not exist'; //also return?
}
}
public function create($username,$password,$province)
{
try
{
$stmt = $this->db->prepare("INSERT INTO tish_images(username,password,province) VALUES(:username, :password, :province)");
$stmt->bindparam(":username",$username);
$stmt->bindparam(":password",$password);
$stmt->bindparam(":province",$province);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
index.php
<?php
include_once 'DB.php';
$username = isset($_GET['username']) ? $_GET['username'] : '';
$password = isset($_GET['password']) ? $_GET['password'] : '';
$province = isset($_GET['province']) ? $_GET['province'] : '';
if(isset($_FILES['files'])){
$id = $_GET['id'];
$username = $_POST['username'];
$password = $_POST['password'];
$province = $_POST['province'];
if($crud->upload($id,$FILE_NAME,$FILE_SIZE,$FILE_TYPE,$username,$password,$province))
{
echo "<script type='text/javascript'>alert('Successfully Updated!');</script>";
}
else
{
echo "<script type='text/javascript'>alert('Updating Failed!');</script>";
}
}
if(isset($_GET['id']))
{
$id = $_GET['id'];
extract($crud->getID($id));
}
You should run a SELECT before performing the query to see if the username exists.
// count how many rows with user name exists
$checkUserStmt = $this->db->prepare("
SELECT count(1)
FROM tish_images
WHERE username = :username
");
$checkUserStmt->execute(array(":username" => $username));
// fetch the count result
if ($checkUserStmt->fetchColumn() > 0) {
// username already exists
} else {
// username available
} //if
A few notes.
You still might get a duplicate entry error if you have two users trying to register the same username at close interval.
You should hash the password see Secure hash and salt for PHP passwords
To check if username or email already exists. I added email in there as this is also useful. You don't want two users with the same email address. Well I wouldn't see the need for it. :)
Complete code added and up to date.
$query_check_user_name = $this->db_connection->prepare('SELECT user_name, user_email FROM users WHERE user_name=:user_name OR user_email=:user_email');
$query_check_user_name->bindValue(':user_name', $user_name, PDO::PARAM_STR);
$query_check_user_name->bindValue(':user_email', $user_email, PDO::PARAM_STR);
$query_check_user_name->execute();
$result = $query_check_user_name->fetchAll();
if ($result > 0) {
echo "Someone with that username/email already exists.";
} else {
//Continue with proccessing the form
}
OR
$query_check_user_name = $this->db_connection->prepare('SELECT user_name, user_email FROM users WHERE user_name=:user_name OR user_email=:user_email');
$query_check_user_name->bindValue(':user_name', $user_name, PDO::PARAM_STR);
$query_check_user_name->bindValue(':user_email', $user_email, PDO::PARAM_STR);
$query_check_user_name->execute();
$result = $query_check_user_name->fetchAll();
if ($result > 0) {
return true;
} else {
return false;
}
I've started a thread or two so far but nothing has got resolved. I'm not able to use the mysqlnd because i'm using a shared hosting account with godaddy.
All i need to do is check if my email address and/or username is in use; if they are in use throw and error, if not.. all is well.
Here is my code:
$input_errors = array();
if (!empty($_POST['username'])) {
$user = $_POST['username'];
} else {
$input_errors['username'] = "Must fill out username";
}
$email = filter_input(INPUT_POST, 'usermail', FILTER_VALIDATE_EMAIL);
if (false === $email) {
$input_errors['usermail'] = "Not a valid email address";
}
if(count($input_errors) > 0) {
print_r($input_errors); die();
}
$sql = "SELECT COUNT(*) as amount FROM people WHERE username = ?
OR email = ?";
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("ss", $user, $email);
$stmt->execute();
$results = $stmt->get_result();
$data = mysqli_fetch_assoc($results);
if ($data['amount'] > 0)
{
print "User already exists";
}
}
else {
$stmt = $mysqli->stmt_init();
if (!$stmt) {
echo "Init failed";
} else {
$cmd = "INSERT INTO people (username, email, sign_up_date) VALUES (?, ?, NOW() )";
if ($stmt->prepare($cmd)) {
$stmt->bind_param('ss', $user, $email );
$stmt->execute();
echo $stmt->affected_rows . " row(s) inserted";
$stmt->close();
} else {
echo "Prepare failed";
}
mysqli_close($mysqli);
}
}
bind_result() does not work.
Change your sql statement to the following:
$sql = "SELECT COUNT(*) as amount FROM people WHERE username = '".mysqli_real_escape_string($_POST['username'])."' OR email = '".mysqli_real_escape_string($email)."'";