I need help converting from mysql_query to PDO - php

I want to make my site as secure as possible so i need to convert everything i have to PDO. I've successfully done a few things but i ran into a road block on my Sign In page.
Heres my code:
<?php
//signin.php
include 'connect.php';
include 'header.php';
session_start();
echo '<h3>Sign in</h3>';
//first, check if the user is already signed in. If that is the case, there is no need to display this page
if(isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true)
{
echo 'You are already signed in, you can signout if you want.';
}
else
{
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
echo '<div class="formdivs" id = "logindiv"><form class = "homeforms" method="post" action="">
<label>Username:<input class="forminput" id="smallinput" type="text" name="user_name" /></label>
<label>Password:<input class="forminput" id="smallinput" type="password" name="user_pass"></label>
<input class = "formbutton" type="submit" name = "button" value = "Sign In!"/>
</form></div>';
}
else
{
$errors = array();
if(!isset($_POST['user_name']))
{
$errors[] = 'Missing Username.';
}
if(!isset($_POST['user_pass']))
{
$errors[] = 'Missing Password.';
}
if(!empty($errors))
{
echo 'Errors';
echo '<ul>';
foreach($errors as $key => $value)
{
echo '<li>' . $value . '</li>';
}
echo '</ul>';
}
else
{
//THIS IS WHERE MY PDO PROBLEM BEGINS-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|
$password = sha1($_POST['user_pass']);
$sql= "SELECT * FROM users WHERE user_name = :username AND user_pass = :password";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $_POST['user_name']);
$stmt->bindParam(':password', $password);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
if(true)
{
if(true)
{
$_SESSION['signed_in'] = true;
while($row = $stmt->fetch())
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_level'] = $row['user_level'];
}
header('Location: /forum.php');
exit;
}
}
}
}
}
include 'footer.php';
?>
My page loads the form but when i press my submit button it turns blank (except for my header and footer) which tells me my php has an error. (obviously)
I want my page to be able to run its error checking (to see if both boxes have input) then to execute upon button press. After i press the button i want it to echo an SQL error if there is one (in situations where the database is down etc) And then also echo if the user name or password does not exist in the database. (IE the select statement returns nothing).
At the moment i have "admin" and "password" just hardcoded in, because i dont think my bindparams statements worked.
EDIT: i should also state that none of my error checking works. If i try to run it with the boxes empty nothing is still shown.
EDIT: SOLUTION: I was using $pdo when i should have been using $DBH. I didnt realize the $pdo variable from the php manual was supposed to be the actual instance i created in my connect.php file. Thanks for your help everybody

You need the colon in your SQL string
$sql= "SELECT * FROM users WHERE user_name = :username AND user_pass = :userpass";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $_POST['user_name']);
$stmt->bindParam(':userpass', $password);
$stmt->execute();
no need for loop , since it's a single record:
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$row = $stmt->fetch();
//set your session
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_level'] = $row['user_level'];
Keep things simple
if(isset($_POST['submit']){
//form submitted, checking errors
$errors = array();
if(!isset($_POST['user_name']))
{
$errors[] = 'Missing Username.';
}
if(!isset($_POST['user_pass']))
{
$errors[] = 'Missing Password.';
}
if(!empty($errors))
{
echo 'Errors';
echo '<ul>';
foreach($errors as $key => $value)
{
echo '<li>' . $value . '</li>';
}
echo '</ul>';
exit();//error! let's exit
}else{
//No errors run the PDO query here
}
}else{
//no submission display the form
}

Related

Error on Login-Page "Warning: Trying to access array offset on value of type bool" [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed last year.
I am currently making a website for a school project and I am making a user registration system. Currently, the sign-up portion works perfectly with user data going into the MySQL database. However, my login-page seems to be broken. Every time I try to log-in I get the following error:
Warning: Trying to access array offset on value of type bool in D:\XAMPP\htdocs\hennorist\login.php on line 23
Attached is the PHP code in question:
<?php
require_once "config.php";
require_once "session.php";
$error = '';
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
$email = trim($_POST['email']);
$password = trim($_POST['password']);
//validate if email is empty
if (empty($email)) {
$error .= '<p class="error">Please enter email.</p>';
}
if (empty($error)) {
if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) {
$query->bind_param('s', $email);
$query->execute();
$row = $query->fetch();
if ($row) {
if (password_verify($password, $row['password'])) {
$_SESSION["userid"] = $row['id'];
$_SESSION["user"] = $row;
//Redirect user to welcome page
header("location: exclusive.php");
exit;
} else {
$error .= '<p class="error">The password is not valid.</p>';
}
} else {
$error .= '<p class="error">No user exists with that email address.</p>';
}
}
$query->close();
}
//Close connection
mysqli_close($db);
}
?>
Are you forced to work with the PDO driver? as a beginner it will be a little tricky for you but I would suggest you to work with MySQLi instead,
In your included file for connexion (guess config.php) to database make sure your connexion is instancing the PDO class as
$query = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
Then to close connexion use $query = null; instead of mysqli_close($db);
Assume you understood try executing the following code
<?php
require_once "config.php";
require_once "session.php";
$error = '';
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
$email = trim($_POST['email']);
$password = trim($_POST['password']);
//validate if email is empty
if (empty($email)) {
$error .= '<p class="error">Please enter email.</p>';
}
if (empty($error)) {
if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) {
$query->bind_param('s', $email);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
if ($row) {
if (password_verify($password, $row['password'])) {
$_SESSION["userid"] = $row['id'];
$_SESSION["user"] = $row;
//Redirect user to welcome page
header("location: exclusive.php");
exit;
} else {
$error .= '<p class="error">The password is not valid.</p>';
}
} else {
$error .= '<p class="error">No user exists with that email address.</p>';
}
}
}
//Close connection
$query=null;
}
?>

Why PHP authentication works incorrect?

I am newbie in PHP.
I have simple authentication script. It works incorrect: user "test" (100% existing in table in DB) can not pass auth (error text - "User is not found!").
Use PHP7, MySQL, connection method is PDO.
Need some help please.
$data = $_POST;
// check if button is pressed
if (isset($data['enter-auth'])) {
// check fileds
$errors = array();
if (trim($data['login_auth']) == '' ) {
$errors[] = 'Enter login';
}
if (($data['password_auth']) == '' ) {
$errors[] = 'Enter password';
}
// If all fields are filled, save user's data in vars
$login = $data['login_auth'];
$password = password_hash($data['password_auth'], PASSWORD_DEFAULT);
// ... and look in table
try {
if (empty($errors)) {
// Check if login and password exists in table
$stmt = $pdo->prepare("SELECT count(*) FROM users WHERE login=? AND password=?");
$stmt->execute([$login, $password]);
$count = $stmt->fetchColumn();
// If login and pwd found in table counter will be > 0, so ...
if ($count > 0) {
// ... then we can check if password is correct
if (password_verify($data['password_auth'], $password)) {
// if entered and stored passwords match, user is welcome
$_SESSION['auth_name'] = $data['login_auth'];
echo '<div style="color: green;">Welcome, '.$_SESSION['auth_name'].';
echo 'Exit';
header('Location: /a/index.php');
} else {
$errors[] = 'Password is incorrect';
echo '<p id="message">Wrong password!</p>';
}
} else {
$errors[] = 'User not found';
echo '<p id="message">User is not found!</p>';
}
} else {
echo '<div style="color: red;">'.array_shift($errors).'</div>';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
// close condition check if button is pressed
}
Notes:
I tryed debugging this script using var_dump.
If I use fetchAll() when searching in table, any entered ldin is accepted (even if there is no such user).
Used try/catch construction with debug aim, I've heard that in production it is deprecated because of security reason.
Found mistakes, rewrote the code according to https://phpdelusions.net/pdo_examples/password_hash
So, correct fragment is:
try {
if (empty($errors)) {
$stmt = $pdo->prepare("SELECT login, password FROM users WHERE login=?");
$stmt->execute([$login]);
$user = $stmt->fetch();
if ($user && password_verify($data['password_auth'], $user['password'])) {
$_SESSION['auth_name'] = $data['login_auth'];
echo '<div style="color: green;">Welcome, '.$_SESSION['auth_name'].';
echo 'Exit';
header('Location: /a/index.php');
} else {
$errors[] = 'Login or password error';
echo '<p id="message-auth">Login or password is incorrect!</p>';
}
} else {
echo '<div style="color: red;">'.array_shift($errors).'</div>';
}
} catch(PDOException $e) {
echo $e->getMessage();
}

Getting no result from query

I want to display the first name of the person that logged in to my website. This is the code of my login.php file which is included in one page of my website.
<?php
$connect = mysql_connect("localhost","root","") or die("Error");
mysql_select_db("jpnv_db") or die("Couldn't find db");
function login() {
$username = $_POST['username'];
$password = $_POST['password'];
$query = mysql_query("SELECT * FROM customers WHERE `username`='$username' AND `password`='$password'");
$names = mysql_query("SELECT contactFirstName FROM customers WHERE `username`='$username'");
if (empty($username)) {
$errors[] = 'Please fill in your username. Click here to try again.';
}
if (empty($password)) {
$errors[] = 'Please fill in your password. Click here to try again.';
}
if ($errors==true) {
foreach ($errors as $error) {
echo $error.'<br />';
}
} else {
if (mysql_num_rows($query)==true) {
echo $names['customers'];
} else {
echo 'Your username and/or password are incorrect. Click here to try again.';
}
}
}
?>
This is the result when the password is incorrect:
This is the result when I actually log in succesfully:
As you can see in my code, it should actually show the name of the person who logged in in the top bar. But however, it is completely empty. What am I doing wrong here?
You never fetch the results from the query and you need to ask for the correct column name from the query:
if (mysql_num_rows($query)==true) {
$name = mysql_fetch_assoc($names)
echo $name['contactFirstName']; // change the column name here
} else {...
You need to prevent SQL Injection or someone will make all of your data disappear.
Please, stop using mysql_* functions. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and use PDO.
function login() {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) || empty($password))
{
echo "You haven't filled username/password";
// redirect code here//
}
else
{
$query = mysqli_query("$con, SELECT * FROM customers WHERE `username`='$username' AND `password`='$password'");
if ($query && mysqli_num_rows($query)!=0) {
$row =mysqli_fetch_assoc($query);
echo "Customer name is : " . $row['customers']; // you need to specify columns in between ' ' to get it. Change it based on your need.
}
}
}
Note : You should migrate to Mysqli or PDO. $con in the code is the variable that holds db connection.
check this line of code. You are not identifying $name variable.
else {
//$names variable
if $(mysql_num_rows($query)==true) {
$names = mysql_fetch_all($query);
echo $names['customers'];
} else {
echo 'Your username and/or password are incorrect. Click here to try again.';
}
}

How to choose page using if else in mysql_num_rows

Please help me I want my program to choose a site if it has not yet username then it will proceed it to ch_uname.php. Then if the login credentials have already username then it will be preceded to index_profile.php. Thank you in advance.
if(mysql_num_rows($runcreds)> 0 ) //checking log in forms
{
if(mysql_num_rows($run_uname)>=1 ) //if username has already avalaible(proceed)
{
$_SESSION['Email_add']=$email;
echo "<script>window.open('modules/index_profile.php','_self')</script>";
}
if(mysql_num_rows($run_uname)<1)//choouse username if has not yet username
{
$_SESSION['Email_add']=$email;
echo "<script>window.open('forms/ch_uname.php','_self')</script>";
//modules/index_profile.php
}
}
else
{
echo "<script>alert('Admin details are incorrect!')</script>";
}
}
Here is a basic demonstration (using a PDO connection) of what I think you are looking for? I am assuming some stuff here because you don't give enough info before your code snippet:
session_start();
// I will use PDO because I cannot bring myself to use mysql_ in this demonstration
// Initiate connection (assigning credentials assumed)
$con = new PDO("mysql:host=$mysqlDB;dbname=$mysqlTable", $mysqlUser, $mysqlPass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT));
if(isset($_POST['login'])) {
$username = trim($_POST['username']);
// Stop if empty
if(empty($username)) {
// You can echo or assign to a variable to echo down the page
echo 'Username cannot be empty';
return;
}
// Set up prepared statement
$query = $con->prepare("select Email_add,password from `users` where username = :username");
$query->execute(array(":username"=>$username));
// Loop through returned
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
// If the loop comes up blank, assign false (0)
$result = (isset($result) && !empty($result))? $result:0;
// If username exists
if($result != 0) {
// I am assuming you have some form of super secure hash method for passwords...
$password = bcrypt($_POST['password']);
// If passwords match, create session
if($result[0]['password'] == $password) {
$_SESSION['Email_add'] = $result[0]['Email_add'];
// You probably don't need javascript to redirect
header('Location: modules/index_profile.php');
exit;
}
else {
// Password doesn't match
// You can echo or assign to a variable to echo down the page
echo 'Invalid Username/Password';
}
}
// This would mean the username doesn't exist
else {
header('Location: forms/ch_uname.php');
exit;
}
}

Issues with undefined index in php/mysql

I hope that I describe my problem properly. I have created a database for a cafeteria. This has the following tables: orders, members ISA manager and servers, products and categories. In the table orders I should insert features such as title,quantity,datetime,sum and user name of the corresponding server. I've managed to do so via php in my files posted before in this forum (follow the link: Insert data from textbox and checkbox into database ).
The web environment so far is consisted of :
a)index.php, members.php (these files are responsible for the login and the authentication of any kind of user, either the administrator or serves.
b)addorder_form.php and addorder.php as far the order form and the insert of the order details in database.
I cannot make my system print the username of each server for each order.
I tried something like this but I 've got the error of undefined index username :
<?php
session_start();
include_once("buzzcafe_fns.php");
include_once("members.php");
do_html_header("");
$conn = mysql_connect("localhost", "root", "");
$db=mysql_select_db("buzzcafe" ,$conn);
db_connect();
if (isset($_SESSION['username']){
if (isset($_POST['products'])) {
if (isset($_POST['quantity'])) {
foreach($_POST['products'] as $key => $products){
$quantity = isset($_POST['quantity'][$key])? $_POST['quantity'][$key]:'Not selected';
date_default_timezone_set('Europe/Athens');
$date = date('Y-m-d H:i:s');
$message[] = $products.' - x'.$quantity;
$insertOrder = mysql_query("INSERT INTO orders (datetime,title,quantity,username) VALUES('".$date."','".$products."','".$quantity."', '".$_SESSION['username']."')")or die(mysql_error());
echo $_SESSION['username'];
}
}
echo implode(',', $message);
echo "<br/>";
echo "<br />Record inserted";
echo "<br/>";
echo $date;
}
else { echo "You did not choose a quantity."; }
}else { echo "You did not choose any product."; }
}
?>
Why is username undefined?
A part of members.php:
<?php
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if ((!$username) || (!$password)) {
do_html_header('');
echo '<h3 style="color:#800000;">Please fill in both fields</h3><br><br></br></br>';
display_login_form();
}
else {
$sql = mysql_query('SELECT * FROM members WHERE username="'.$_POST['username'].'" AND password=sha1("'.$_POST['password'].'")') or die(mysql_error());
$login_check_member = mysql_num_rows($sql);
if($login_check_member > 0) {
while($row = mysql_fetch_array($sql)) {
$role = $row["role"];
$_SESSION['role'] = $role;
$us = $row["username"];
$_SESSION['username'] = $us;
$username = $_SESSION['username'];
}
}
I include this file in my addorder.php file.
Probably because it's not defined?
Seems people are a little more concerned about your SQL than anything -- but this may help you in the actual question.
Throw this in there before them nested conditions:
if (defined($_SESSION['username'])) {
echo 'Username is defined!';
}
else {
die('Username is undefined!');
}

Categories