class Users {
public $username = null;
public $password = null;
public $salt = "Zo4rU5Z1YyKJAASY0PT6EUg7BBYdlEhPaNLuxAwU8lqu1ElzHv0Ri7EM6irpx5w";
public function __construct( $data = array() ) {
if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( >$data['username'] ) );
if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( >$data['password'] ) );
}
}
public function storeFormValues( $params ) {
$this->__construct( $params );
}
public function register() {
$correct = false;
try {
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "INSERT INTO users(username, password) VALUES(:username, :password)";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();
return "Registration Successful <br/> <a href='index.php'>Login Now</a>";
}catch( PDOException $e ) {
return $e->getMessage();
}
}
}
I would like to check if a user already exist in my database, because it lets me create accounts with same username anytime.
Thanks.
I would recommend a few things to help here.
1) Make your username column unique in the database. This would prevent usernames that are not unique from being inserted.
2) Once you have a unique index on username, attempt the insert, and check for success on the insert. Since you can get the error code from mysql, if the query was not successful and the error code is due to a duplicate value...throw the username already exists error.
This is the basic idea of how to return if the username exists.
public function username($username)
{
$sth = $this->db->prepare("SELECT id, username FROM table WHERE username = ?");
$sth->execute(array($username));
$row = $sth->fetch();
if(username == $row['username'])
{
do code here since username does not exist
} else {
echo 'username already exists';
}
}
$sell= mysql_query("select * from `signup` where emailid='$email'");
$cntc=mysql_num_rows($sell);
if($cntc==0) {
$sql=mysql_query("INSERT INTO `signup`(`firstname`,`lastname`,`emailid`,`dob`,`companyname`,`phoneno`,`password`) VALUES ('$name','$lastname','$email','$dob','$comname','$phone','$pass')");
if($sql) {
echo'inserted successfully';
}
} else {
echo'Email is already exist. ';
}
Related
I know what this error means, but I don't know why it is showing. I've checked names of variables, names of PDO variables, names of tables in database and still nothing.
If I copy insert into phpMyAdmin, it runs perfectly. If I change all variables from $this-> to 'abcd' it gives me the same error.
I really don't know what it is going on ...
Error:
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
Code:
class Users {
public $username = null;
public $password = null;
public $useremail = null;
public $steam_id = null;
public $salt = "Zo4rU5Z1YyKJAASY0PT6EUg7BBYdlEhPaNLuxAwU8lqu1ElzHv0Ri7EM6irpx5w";
public function __construct( $data = array() ) {
if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( $data['username'] ) );
if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( $data['password'] ) );
if( isset( $data['useremail'] ) ) $this->useremail = stripslashes( strip_tags( $data['useremail'] ) );
if( isset( $data['steam_id'] ) ) $this->steam_id = stripslashes( strip_tags( $data['steam_id'] ) );
}
public function storeFormValues( $params ) {
//store the parameters
$this->__construct( $params );
}
public function register() {
$correct = false;
try {
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql1 = "SELECT * FROM users WHERE user_name = :username LIMIT 1";
$polacz1 = $con->prepare( $sql1 );
$polacz1->bindValue( "username", $this->username, PDO::PARAM_STR );
$polacz1->execute();
$row = $polacz1->fetch();
$sql2 = "SELECT * FROM users WHERE user_email = :useremail LIMIT 1";
$polacz2 = $con->prepare( $sql2 );
$polacz2->bindValue( "useremail", $this->useremail, PDO::PARAM_STR );
$polacz2->execute();
$row1 = $polacz2->fetch();
$sql3 = "SELECT * FROM users WHERE steam_id = :steam_id LIMIT 1";
$polacz3 = $con->prepare( $sql2 );
$polacz3->bindValue( "steam_id", $this->steam_id, PDO::PARAM_STR );
$polacz3->execute();
$row2 = $polacz3->fetch();
if($row == NULL){
if($row1 == NULL){
if($row1 == NULL){
$checksum = bin2hex(mcrypt_create_iv(22, MCRYPT_DEV_URANDOM));
$sql = "INSERT INTO users(user_name, user_email, user_pass, steam_id, email_hash) VALUES(:username, :useremail, :password, :steamid, :emailhash)";
$polacz = $con->prepare( $sql );
$polacz->bindValue( ":username", $this->username, PDO::PARAM_STR );
$polacz->bindValue( ":useremail", $this->useremail, PDO::PARAM_STR );
$polacz->bindValue( ":password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$polacz->bindValue( ":steamid", $this->steam_id, PDO::PARAM_STR );
$polacz->bindValue( ":emailhash", $checksum, PDO::PARAM_STR );
$polacz->execute();
return '<div class="alert alert-success" role="alert">Zostałeś pomyślnie zarejestowany. Sprawdź podany adres email i aktywuj swoje konto!</div>';
//return "Rejestracja przebiegła pomyślnie, możesz się zalogować.";
} else return '<div class="alert alert-danger" role="alert">Podany steam ID już istnieje.</div>';
}
else
{
return '<div class="alert alert-danger" role="alert">Podany e-mail już istnieje.</div>';
}
}
else
{
return '<div class="alert alert-danger" role="alert">Podany użytkownik już istnieje.</div>';
}
}catch( PDOException $e ) {
return $e->getMessage();
}
}
}
Hi I am trying to get value from userID column in my table inside the sessein array.
in my register class I have the following code:
<?php
class Users {
public $username = null;
public $password = null;
public $salt = "Zo4rU5Z1YyKJAASY0PT6EUg7BBYdlEhPaNLuxAwU8lqu1ElzHv0Ri7EM6irpx5w";
public function __construct( $data = array() ) {
if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( $data['username'] ) );
if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( $data['password'] ) );
}
public function storeFormValues( $params ) {
//store the parameters
$this->__construct( $params );
}
public function userLogin() {
$success = false;
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();
$valid = $stmt->fetchColumn();
if( $valid ) {
$success = true;
$_SESSION['userID'] = $user->user_id;
}
for which syntaxis I am not very sure that it will sessionize the UserID value of the logged user.
and in the login where the array is created I have
<?php
session_start();
include_once("config.php"); //include the settings/configuration
?>
<?php
//else look at the database and see if he entered the correct details
} else {
session_start();
$usr = new Users;
$usr->storeFormValues( $_POST );
if( $usr->userLogin() ) {
header( 'Location: cursos.php' ) ;
$_SESSION["loggedIn"] = true;
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$_SESSION['userID'] = $_POST['userID'];
but it gives me every time NULL result how to fix it ?
first of all if you're posting the form you should use $_POST['userID'] and first check it if you retrieving the value in your $_POST['userID'] then you have to start session like this
session_start();
$_SESSION['userID'] = $_POST['userID']
but the first one code i understand you're using codeigniter or OOP $user->user_id the first $user is your variable and second one is user_id which may be your access modifier also check $user->user_id it has value then do same
session_start();
$_SESSION['userID'] = $user->user_id;
Hello I am posting maybe 4th question about this issue but nobody can help me so far, so let's start from the begining, what I need is simple I need to: Set userID variable from column name "userID' inside table named "users" into the Sessions array: $_SESSION['userID']
here is my login page code:
<?php
session_start();
include_once("config.php"); //include the settings/configuration
?>
<?php if( !(isset( $_POST['login'] ) ) ) { ?>
<?php
//else look at the database and see if he entered the correct details
} else {
session_start();
$usr = new Users;
$usr->storeFormValues( $_POST );
if( $usr->userLogin() ) {
header( 'Location: cursos.php' ) ;
$_SESSION["loggedIn"] = true;
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
and here is my user class which operates the function login:
public function userLogin() {
$success = false;
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
$success = true;
if ($result!==false) { // Check there is a match
$_SESSION['userID']= $result['userID'];
}
$success = true;
$con = null;
return $success;
}catch (PDOException $e) {
echo $e->getMessage();
return $success;
The code is working fine I just want to add addition to it which will get the userID value from the column of the users table inside the database ans store it to the $_SESSION['userID'] after user is loged in.
So any idea how to reach this goal in my code ? thanks!
If you just want the UserID from the table, you're going to have to do a $stmt->fetch() to load it first, then you can store it in your SESSION.
So after the execute in function userLogin() do:
$result = $stmt->fetch(PDO::FETCH_ASSOC);
If the user was found $result will then contain all of the fields from the users table. So:
if ($result!==false) { // Check there is a match
$_SESSION['userID']= $result['userID'];
}
I'm in the process of learning PHP and MySQL.
I would like from the script to recognize a specific name and redirect it to admin.php. For example "if Username is Brian redirect him to admin.php, if the username is everything except Brian, redirect him to account.php".
Both Brian and the other persons must be registered in the database to be able to login. I thought on redirect based on MySQL user id, but I don't know how to write the code. Or if you know another simple solution.
Here is the script:
<?php
class Users {
public $username = null;
public $password = null;
public $salt = "";
public function __construct( $data = array() ) {
if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( $data['username'] ) );
if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( $data['password'] ) );
}
public function storeFormValues( $params ) {
//store the parameters
$this->__construct( $params );
}
public function userLogin() {
$success = false;
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT userID FROM users WHERE username='username' AND password= :password AND userTypeId = 1 LIMIT 1";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();
$valid = $stmt->fetchColumn();
if( $valid ) {
$success = true;
}
$con = null;
return $success;
}catch (PDOException $e) {
echo $e->getMessage();
return $success;
}
}
And this is the script from index.php (where the user writes his name and password)
<?php
} else {
$usr = new Users;
$usr->storeFormValues( $_POST );
if( $usr->userLogin() ) {
echo "Welcome";
} else {
echo "Incorrect Username/Password";
}
}
?>
Rather than recognizing a name (which you would have to parse) I believe it would be more efficient (and easier to implement) if you instead direct by user number (or whatever you're calling your primary key).
So if your user name is "Brian" and is the first user, with user number 1 then point to your table where the 1 is located, assuming it's stored as the integer 1 and not the string "1" instead.
Computers generally have an easier time dealing with integers rather than arrays. You can do it by string, but it's always going to be more work for you and the machine.
As far as redirecting goes, upon logging in, just do a check:
if user number is equal to [Brian's user number] then redirect to admin.php
else redirect to account.php
(Also you'll want to make sure that admin.php requires Brian be the logged in user, or anybody else could just navigate there manually)
The method $user->userLogin should return the id of current login user when successful login and return FALSE when failure login . then redirect to a admin.php or or account.php depend the returned id
First, try to fetch username and correct binding name for username:
$sql = "SELECT username FROM users WHERE username = :username AND ...
instead of:
$sql = "SELECT userID FROM users WHERE username='username' AND ...
//^ //^
Also just return fetched username on successful status. It returns a single column from the next row of a result set or FALSE if there are no more rows.
return $stmt->fetchColumn();
And then check logged in username by if condition to redirect desired page:
$usr = new Users;
$usr->storeFormValues( $_POST );
$username = $usr->userLogin();
if( $username !== false ) {
if(strtolower($username) == "brian"){
header("Location: admin.php");
} else {
header("Location: account.php");
}
} else {
echo "Incorrect Username/Password";
}
I have an earlier post here
But NONE of those answers worked. So here's my entire class code:
<?php
session_start();
class Mysql {
private $conn;
function __construct() {
$this->conn = new PDO('mysql:host=***;dbname=***;charset=UTF-8','***','***') or
die('There was a problem connecting to the database.');
}
function verify_Username_and_Pass($un, $pwd) {
$query = "SELECT Username
FROM Conference
WHERE Username = :un AND Password = :pwd";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(':un', $un);
$stmt->bindParam(':pwd', $pwd);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// User exist
$stmt->bindColumn('First Name', $firstName);
$_SESSION["FirstName"] = $firstName;
die($_SESSION["FirstName"]);
return true;
$stmt->close();
}
else {
// User doesn't exist
//die("failure");
return false;
$stmt->close();
}
}
}
?>
I've tried fetch, i've tried bind_result, etc and none of them print the correct value on the die statement. Now this worked when i stored username in session and tried to print that. What is wrong with the code?
You aren't calling the code in the snippet. What's the call procedure?
You aren't retrieving Conference.First Name only Conference.Username so you should be getting a warning unless you're not displaying errors. You probably want
"SELECT * FROM Conference...."
or
"SELECT FirstName From Conference WHERE Username = :un AND Password = :pwd";
It's possibly Conference.FirstName.
die(); is not very useful for debugging. Try var_dump($_SESSION["FirstName"]); die();
I have looked at your code, and made a working version on my own server. If you have any questions, feel free to ask.
class Mysql
{
private $conn;
public $error;
public $username;
function __construct()
{
try {
$this->conn = new PDO( 'mysql:host=localhost;dbname=****', 'root', '****' );
$this->conn->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
}
catch ( Exception $e ) {
$this->error = $e->getMessage();
}
}
function verify_Username_and_Pass( $un, $pwd )
{
$query = "SELECT Username
FROM Conference
WHERE Username = :un AND Password = :pwd";
$stmt = $this->conn->prepare( $query );
if( !$stmt ) {
$this->error = $this->conn->errorInfo();
return false;
}
$stmt->bindParam( ':un', $un );
$stmt->bindParam( ':pwd', $pwd );
$stmt->execute();
if ( $stmt->rowCount() > 0 ) {
// User exist
$this->username = $stmt->fetchColumn();
return true;
}
else {
// User doesn't exist
return false;
}
}
}
session_start();
$db = new Mysql();
if( !$db->error ) {
if( $db->verify_Username_and_Pass ( 'user', 'test' )) {
$_SESSION["FirstName"] = $db->username;
}
else
echo 'Unknown user';
}
var_dump( $db );
The script will output this:
Unknown user
object(Mysql)#1 (3) {
["conn":"Mysql":private]=> object(PDO)#2 (0) { }
["error"]=> array(3)
{ [0]=> string(5) "42S02"
[1]=> int(1146)
[2]=> string(39) "Table 'xxxx.Conference' doesn't exist" }
["username"]=> NULL }