Hi my test website wont save any kind of data in the database so when i register it wont save it to the database so i cant login. can someone explain what is wrong with the code and tell me how to fix it thanks!
heres code
Register code:
$reg = #$_POST['reg'];
//declaring variables to prevent errors
$fn = ""; //First Name
$ln = ""; //Last Name
$un = ""; //Username
$em = ""; //Email
$em2 = ""; //Email 2
$pswd = ""; //Password
$pswd2 = ""; // Password 2
$d = ""; // Sign up Date
$u_check = ""; // Check if username exists
//registration form
$fn = strip_tags(#$_POST['fname']);
$ln = strip_tags(#$_POST['lname']);
$un = strip_tags(#$_POST['username']);
$em = strip_tags(#$_POST['email']);
$em2 = strip_tags(#$_POST['email2']);
$pswd = strip_tags(#$_POST['password']);
$pswd2 = strip_tags(#$_POST['password2']);
$d = date("Y-m-d"); // Year - Month - Day
if ($reg) {
if ($em==$em2) {
// Check if user already exists
$u_check = mysql_query("SELECT username FROM users WHERE username='$un'");
// Count the amount of rows where username = $un
$check = mysql_num_rows($u_check);
//Check whether Email already exists in the database
$e_check = mysql_query("SELECT email FROM users WHERE email='$em'");
//Count the number of rows returned
$email_check = mysql_num_rows($e_check);
if ($check == 0) {
if ($email_check == 0) {
//check all of the fields have been filed in
if ($fn&&$ln&&$un&&$em&&$em2&&$pswd&&$pswd2) {
// check that passwords match
if ($pswd==$pswd2) {
// check the maximum length of username/first name/last name does not exceed 25 characters
if (strlen($un)>30||strlen($fn)>30||strlen($ln)>30) {
echo "The maximum limit for username/first name/last name is 30 characters!";
}
else
{
// check the maximum length of password does not exceed 25 characters and is not less than 5 characters
if (strlen($pswd)>30||strlen($pswd)<5) {
echo "Your password must be between 5 and 30 characters long!";
}
else
{
//encrypt password and password 2 using md5 before sending to database
$pswd = md5($pswd);
$pswd2 = md5($pswd2);
$query = mysql_query("INSERT INTO users VALUES ('','$un','$fn','$ln','$em','$pswd','$d','0','Write something about yourself.','','','no')");
die("<h2>Welcome to test</h2>Login to your account to get started");
}
}
}
else {
echo "Your passwords don't match!";
}
}
else
{
echo "Please fill in all of the fields";
}
}
else
{
echo "Sorry, but it looks like someone has already used that email!";
}
}
else
{
echo "Username already taken ...";
}
}
else {
echo "Your E-mails don't match!";
}
}
connect code
<?php
mysql_connect("localhost","root","") or die ("Cant Connect To DataBase!");
mysql_select_db("test") or die ("Cant Select DataBase");
?>
and the tabel
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`first_name` varchar(255) NOT NULL,
`last_name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(32) NOT NULL,
`sign_up_date` date NOT NULL,
`activated` enum('0','1') NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
<?php
// CHECK IF THE FORM HAS BEEN SUBMITTED
if (isset($_POST['REG'])) {
/* these are the columns to be filled
username
first_name
last_name
email
password
sign_up_date
activated
*/
// GATHER VARIABLES, as we are sure the form has been requested via $_POST there is no need to 'declare' variables
$first_name = trim($_POST['first_name']);
$last_name = trim($_POST['last_name']);
$username = trim($_POST['username']);
// JUST USING ONE EMAIL VARIABLE, BOTH EMAILS BEING THE SAME SHOULD BE CLIENT-VALIDATED
$email = trim($_POST['email']);
// THE SAME AS ABOVE WITH PASS
$password = trim($_POST['password']);
$date = trim($_POST['date']);
$acive = trim($_POST['acive']);
// THIS FUNCTION TESTS FOR EMPTY STRINGS, SELECTS SET TO 0 AND EMPTY ARRAYS
function test_valid() {
$args = func_get_args();
foreach ($args as $value) {
if ($value === 0 || $value == '' || empty($value)) {
return false;
} else {
$foo = true;
}
}
return $foo;
}
// MAKE THE TEST
if (test_valid($first_name, $last_name, $username, $email)) {
// CONTINUE TO THE DATABASE
// CONNECT TO THE DATABASE USING PDO
$conn = new PDO('mysql:host=YOURHOST;dbname=YOURDBNAME', 'YOURUSER', 'YOURPASS');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// PREPARE THE STATEMENT TO CHECK THE VALUES IN THE DATABASE
$stmt = $conn->prepare("SELECT id, username, email FROM users WHERE username = :username OR email = :email ORDER BY id DESC LIMIT 1");
// BIND THE PARAMETERS TO THE :thingy's
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->execute();
//get an array containing arrays<- these ones being the rows of the query
$result = $stmt->fetchAll();
if (empty($result)) {
$password = crypt($password, $username);
$stmt = $conn->prepare("INSERT INTO users VALUES ('', :username , :first_name , :last_name , :email , :password , NOW(), 0)");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':first_name', $first_name, PDO::PARAM_STR);
$stmt->bindParam(':last_name', $last_name, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->execute();
} else {
//there were matching rows, therefore the username or the e-mail were already registered
}
} else {
//there were invalid parameters in the form
}
} else {
// form was not submitted
}
?>
You should describe in more detail what you are trying to achieve, this may not be the perfect answer/solution/code, but it's a cleaner one and uses PDO'S bindParam to avoid SQL injections and PHP's crypt(), better than mdf5 See the post in thecodinglove
Also, a good place to start learning (I've used it) is Tutsplus with Jeffrey Way, the best beginner's PHP-MySQL tutorial I've seen.
It would also help to see what errors is throwing php with E_ALL
Hope this helps you in your test.
Related
I have made a login system which enables a user to sign in using a previously defined email and password, however in the testing section, I have noticed the passwords say they don't match although I know they are correct as I wrote the test one down as I made it. I cant seem to see why this is happening, I think it may be something to do with my hashing of the passwords but I don't know what.The login page check is from document, login.php:
if(empty($errors))
{
$sql = "SELECT accountID, password FROM users WHERE emails=?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$data['email']]);
if(!$row = $stmt->fetch())
{
// email didn't match
$errors['login'] = "Login failed. on email";
}
else
{
// email matched, test password
if(!password_verify($data['password'],$row['password']))
{
// password didn't match
$errors['login'] = "Login failed. on password";
}
else
{
// password matched
$_SESSION['user_id'] = $row['accountID'];
header('location: welcome.php');
die;
}
}
}
The insertion to the database with hashing is, from insert.php:
if (isset($_POST['name'])){
$name = $_POST['name'];
}
if (isset($_POST['email'])){
$email = $_POST['email'];
}
if (isset($_POST['password'])){
$pword = $_POST['password'];
}
if (isset($_POST['busName'])){
$busName = $_POST['busName'];
}
if (empty($name)){
echo("Name is a required field");
exit();
}
if (empty($email)){
echo ("email is a required field");
exit();
}
if (empty($pword)){
echo("You must enter a password");
exit();
}
$pword = password_hash($pword, PASSWORD_DEFAULT)."/n";
//insert html form into database
$insertquery= "INSERT INTO `cscw`.`users` (
`accountID` ,
`businessName` ,
`name` ,
`emails` ,
`password`
)
VALUES (
NULL , '$busName', '$name', '$email', '$pword'
);";
and on the web page i am shown from login.php, "Login failed. on password". If you need to see any more code please let me know.
It does not recognize $row['password'].
Be always organized with your query **
1)Prepare
2)Execute
3)Fetch
4)Close
5)THEN YOU EXPLOIT the fetched data.
The fetched data need to be sorted as shown with the returnArray function.
Hoping that there are UNIQUE emails and the $data array exists.Try this.
if(empty($errors))
{
$sql = "SELECT accountID, password FROM users WHERE emails=:emails";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':emails', $data['email']);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->CloseCursor();
$stmt=null;
/* Return the results is a more handy way */
function returnArray( $rows, $string )
{
foreach( $rows as $row )
{
return $row[ $string ];
}
}
if( empty($rows) )
{ // email didn't match
$errors['login'] = "Login failed. on email";
}
else
{ // email matched, test password
if( !password_verify( $data['password'], returnArray($rows,'password') ) )
{
// password didn't match
$errors['login'] = "Login failed. on password";
}
else
{
// password matched
$_SESSION['user_id'] = $row['accountID'];
header('location: welcome.php');
die;
}
}
}
The login Page is not finished the query is not inserting. Be carefull you might be vunerable to SQL injections because your do not escape user manipulated variables.(To strengthen security add a form validation, it will be great).
You have used $pword = password_hash($pword, PASSWORD_DEFAULT)."/n";
I removed ."/n" part. I seems that you are using a concatenation operator '.' to add /n add the end of the password_hash.
Your $insertquery is not finished and not readable. You don't need to insert backticks in your query. And no need to SELECT accountID it will autoincrement (See if A_I for accountID is ticked in your database).
Do something like this in your login page.
/* trim and escape*/
function escapeHtmlTrimed( $data )
{
$trimed = trim( $data );
$htmlentities = htmlentities( $trimed, ENT_QUOTES | ENT_HTML5, $encoding = 'UTF-8' );
return $htmlentities;
}
if ( isset( $_POST['name'] ) ){
$name = escapeHtmlTrimed( $_POST['name'] );
}
if ( isset($_POST['email']) ){
$email = escapeHtmlTrimed( $_POST['email'] );
}
if ( isset($_POST['password']) ){
$pword = escapeHtmlTrimed( $_POST['password'] );
}
if ( isset($_POST['busName']) ){
$busName = escapeHtmlTrimed( $_POST['busName'] );
}
if ( empty($name) ){
echo("Name is a required field");
exit();
}
if ( empty($email) ){
echo ("email is a required field");
exit();
}
if ( empty($pword) ){
echo("You must enter a password");
exit();
}
/*Remove this your adding "./n"*/
$pword = password_hash($pword, PASSWORD_DEFAULT);
//insert html form into database
$insertquery= "INSERT INTO users (businessName ,name ,emails,
password) VALUES (:busName , :name, :email , :pword)";
$stmt = $pdo->prepare($insertquery);
$stmt->bindParam(':busName', $busName);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':pword', $pword);
$stmt->execute();
$stmt->CloseCursor();
$stmt=null;
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;
}
Trying to handle the input from a check box as a boolean so that I can input the value amongst others into a database. The value is "mailingList" and i thought i had cracked it but it now just returns a pre defined error in my "catch" which should be unrelated. Below is the $_Post from the form
<?php
if (isset($_POST['register'])) {
$email = trim($_POST['email']);
$password = trim($_POST['pwd']);
$retyped = trim($_POST['conf_pwd']);
$firstname = trim($_POST['fname']);
$lastname = trim($_POST['lname']);
$company = trim($_POST['company']);
$mailinglist = trim($_POST['mailingListCheckbox']);
require_once('./includes/register_user_pdo.inc.php');
}
?>
then there is the related register_user_pdo.inc.php
<?php
require_once('./classes/CheckPassword.php');
$errors = array();
if (preg_match('/\s/', $email)) {
$errors[] = 'Email should not contain spaces.';
}
if (!isset($mailingList)) {
$mailingListValue = FALSE;
}
else {
$mailingListValue = TRUE;
}
$checkPwd = new Ps2_CheckPassword($password, 10);
$checkPwd->requireMixedCase();
$checkPwd->requireNumbers(2);
$checkPwd->requireSymbols();
$passwordOK = $checkPwd->check();
if (!$passwordOK) {
$errors = array_merge($errors, $checkPwd->getErrors());
}
if ($password != $retyped) {
$errors[] = "Your passwords don't match.";
}
if (!$errors) {
// include the connection file
require_once('./includes/connection.inc.php');
$conn = dbConnect();
// create a salt using the current timestamp
$salt = time();
// encrypt the password and salt with SHA1
$pwd = sha1($password . $salt);
// prepare SQL statement
$sql = 'INSERT INTO users (email, salt, pwd, lastName, firstName, company, mailingList)
VALUES (:email, :salt, :pwd, :lastName, :firstName, :company, :mailingList)';
$stmt = $conn->prepare($sql);
// bind parameters and insert the details into the database
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':salt', $salt, PDO::PARAM_INT);
$stmt->bindParam(':pwd', $pwd, PDO::PARAM_STR);
$stmt->bindParam(':lastName', $lname, PDO::PARAM_STR);
$stmt->bindParam(':firstName', $fname, PDO::PARAM_STR);
$stmt->bindParam(':company', $company, PDO::PARAM_STR);
$stmt->bindParam(':mailingList', $mailingListValue, PDO::PARAM_BOOL);
try {
$stmt->execute();
// check number of rows affected by previous insert
if ($stmt->rowCount() == 1) {
$success = "$email has been registered. You may now log in.";
}
}catch(PDOException $e){
if ($e->getCode() == 23000)
$errors[] = "Email is already in use. Please use another email address.";
else
$errors[] = 'Sorry, there was a problem with the database.';
}
}
?>
Any help would be much appreciated! Thanks in advance!
In your top segment of code you are defining
$mailinglist = trim($_POST['mailingListCheckbox']);
however in your second segment of code you are referencing
$stmt->bindParam(':mailingList', $mailingListValue, PDO::PARAM_BOOL);
You need to change your first part to
$mailingListValue = ....
EDIT
The above answer is wrong, actually it could be this :-
if (!isset($mailingList)) {
"L" is capitalised
I have this login and registration script from the net. Everything is working fine.
Objectives:
Usernames entered by the user will only be alphabets. If the username entered is not exist in the database, it will automatically add a number 1 on the username, example, user1.
Let's say the database have already had user1, user2, user3. Whenever a user entered user, it will then check what is the last incrementing number which in this case, it is 3, so it will then add into the database as user4.
Problems:
As I am trying to learn PDO as much as I could and it is still pretty difficult for me to understand. Also, I do not have any idea where should I start from.
Below are my current working code:
if (isset($_POST['submit'])) {
if(empty($_POST['username']) || empty($_POST['password'])){
$errors[] = 'All fields are required.';
}else if(!ctype_alpha($_POST['username'])){
$errors[] = 'Please enter only alphabet letters.';
}else{
if ($users->user_exists($_POST['username']) === true) {
$errors[] = 'That username already exists';
}
}
if(empty($errors) === true){
$username = htmlentities($_POST['username']);
$password = $_POST['password'];
$users->register($username, $password);
header('Location: register.php?success');
exit();
}
}
public function user_exists($username) {
$stmt = $this->db->prepare("SELECT COUNT(`id`) FROM `userinfo` WHERE `username`= ?");
$stmt->bindValue(1, $username, PDO::PARAM_STR);
try{
$stmt->execute();
$rows = $stmt->fetchColumn();
if($rows == 1){
return true;
}else{
return false;
}
} catch (PDOException $e){
die($e->getMessage());
}
}
public function register($username, $password){
$password = sha1($password);
$stmt = $this->db->prepare("INSERT INTO `userinfo` (`username`, `password`) VALUES (?, ?) ");
$stmt->bindValue(1, $username, PDO::PARAM_STR);
$stmt->bindValue(2, $password, PDO::PARAM_STR);
try{
$stmt->execute();
// mail($email, 'Please activate your account', "Hello " . $username. ",\r\nThank you for registering with us. Please visit the link below so we can activate your account:\r\n\r\nhttp://www.example.com/activate.php?email=" . $email . "&email_code=" . $email_code . "\r\n\r\n-- Example team");
}catch(PDOException $e){
die($e->getMessage());
}
}
Is there any kind souls out there can help me out on this? Letting me know where should I start and what should I do? Or the flow of the whole procedure in achieving my objectives.
Any help will be much appreciated! Thanks in advance.
Here is a example how to change your function to check if the user exist .. and which is the last index.
It is not pretty but will do the job and may be point you to the right ideas.
public function register($username, $password){
$password = sha1($password);
//check if the user exists and find first posible free index
$_username = $username;
if($this->db->query("SELECT * FROM `userinfo` WHERE `username` = 'user' ")){
$n = 1;
$max_index = 20;
while ($n < $max_index ) { //just to be safe
$_username = $username . $n;
if (!$this->db->query("SELECT * FROM `userinfo` WHERE `username` = '" . $_username . "' ")) {
break;
}
$n++;
}
if($n == $max_index){
die("Sorry ,there already (".$max_index.") entries of this username.");
}
}
//continue as normal just use $_username in the final query
$stmt = $this->db->prepare("INSERT INTO `userinfo` (`username`, `password`) VALUES (?, ?) ");
$stmt->bindValue(1, $_username, PDO::PARAM_STR);
$stmt->bindValue(2, $password, PDO::PARAM_STR);
try{
$stmt->execute();
// mail($email, 'Please activate your account', "Hello " . $username. ",\r\nThank you for registering with us. Please visit the link below so we can activate your account:\r\n\r\nhttp://www.example.com/activate.php?email=" . $email . "&email_code=" . $email_code . "\r\n\r\n-- Example team");
}catch(PDOException $e){
die($e->getMessage());
}
}
First of all you have to add a Sql-Wildcard like % _ * meaning see here to find all usernames they starts with "user" and have one or more charakter behind the "user"-string. Currently you only will get the username that excatly matchs the insert username.
But you could get some trouble by using the wrong wildcard, then
SELECT COUNT(id) FROM userinfo LIKE username = user%;
will always selct usernames like user1, user2, user3 but also something like userhorst..
To the pdo, the pdo help you to protect you system from sql injections. The prepare function sends only something like a query with wildcars for your parameter, thats means they send your statement without the parameters, to the Database. After this you send with the bindValue-function the single values to the Database. And finally you will excecute the statement. During this process the datapase can check each sended value for invalid signs.
Finally you have to check your if-statement. You will only get true when one user with the same name was in the database in all other cases (0,2,3,4,5,6,7) you get false.. But you want
if countUsers equal 0 then:
return false;
else
return true;
fi
Another part is you should thinking about using the sha1-hash, there are still better hashs to protect your passwords.
You can select all usernames like user* using:
SELECT username FROM `userinfo` WHERE username LIKE 'user%'
Next you should sort your results using asort:
asort($array_of_usernames);
then use substr or preg_match to get the number at the end of the username:
$number = substr($each_username, -1, 2) //within a foreach
Increment the number gotten then insert into database.
$new_username = "user" . $number++;
Thanks for the help guys!
Below are my current working code which I manage to tweak here and there based on the help given:
public function register($username, $password){
$stmt = $this->db->prepare("SELECT username FROM `userinfo` WHERE `username` LIKE :username");
$parse_username = "%".$username."%";
$stmt->bindValue(':username', $parse_username, PDO::PARAM_STR);
$stmt ->execute();
$user = $stmt->fetch();
$n = 1;
if($user){
$db_username = $user["username"];
$username_counter = preg_match("/".$username."(\d+)/", $db_username, $matches) ? (int)$matches[1] : NULL;
while ($n < $username_counter ) { //just to be safe
$new_username = $username . $n;
if (!$user) {
break;
}
$n++;
}
if($n == $username_counter){
$n++;
$new_username = $username.$n;
}
}else if(!$user){
$new_username = $username.$n;
}
$password = sha1($password);
$query = $this->db->prepare("INSERT INTO `userinfo` (`username`, `password`) VALUES (?, ?) ");
$query->bindValue(1, $new_username);
$query->bindValue(2, $password);
try{
$query->execute();
$_SESSION['new_username'] = $new_username;
// mail($email, 'Please activate your account', "Hello " . $username. ",\r\nThank you for registering with us. Please visit the link below so we can activate your account:\r\n\r\nhttp://www.example.com/activate.php?email=" . $email . "&email_code=" . $email_code . "\r\n\r\n-- Example team");
}catch(PDOException $e){
die($e->getMessage());
}
}
I am not sure that my way of coding is the best or professional, it is just based on my little logical knowledge of the flow. If there are any area where I can improve or rewrite, help me out if you wish to. =)
So my SELECT statement is selecting all from a row in the users table. There is a column in that row labeled "user_level" and I want to use the data from that column to differentiate between an admin and a guest. Is there a way to use "user_level" (and maybe bind it to a session variable) without me having to write another SELECT statement?
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
if (empty($username) or empty($password)) {
$error = 'All fields are required!';
} else {
$query = $pdo->prepare("SELECT * FROM users WHERE user_name = :name and
user_password = :password");
$query->bindValue(":name", $username, PDO::PARAM_STR);
$query->bindValue(":password", $password, PDO::PARAM_STR);
$query->execute();
$num = $query->rowCount();
if ($num == 1) {
//user entered correct details
$_SESSION['logged_in'] = true;
header('Location: index.php');
exit();
} else {
//user entered false details
$error = 'Incorrect details!';
}
}
}
You don't need no rowCount here.
as well as half of the duplicated and triplicated code.
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
$sql = "SELECT user_level FROM users WHERE user_name = ? and user_password = ?";
$stm = $pdo->prepare($sql);
$srm->execute(array($username,$password));
$level = $stm->fetchColumn();
if ($level !== FALSE) {
//user entered correct details
$_SESSION['user_level'] = $level;
header('Location: index.php');
exit();
}
}
$error = 'Incorrect details!';