Is it necessary to pre-defined variables in prepared statement? - php

I have the following prepared statement:
$stmt = $conn->prepare("SELECT * FROM `users` WHERE user LIKE ? ");
$stmt->bind_param("s", $filtered_form['user']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $user, $pass, $first, $last, $type, $email);
$stmt->fetch();
$stmt->close();
}
if ($pass === $filtered_form['pass']) {
$_SESSION['id'] = $id;
$_SESSION['user'] = $user;
$_SESSION['first'] = $first;
$_SESSION['last'] = $last;
$_SESSION['email'] = $email;
$_SESSION['type'] = $type;
header("Location:index.php");
exit;
} else {
return "Incorrect password";
}
however Visual Studio says there is a problem that the variables $id, $user, $pass, $first, $last, $type, $email are not defined. I added the variables like this:
$stmt = $conn->prepare("SELECT * FROM `users` WHERE user LIKE ? ");
$stmt->bind_param("s", $filtered_form['user']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
$id = "";
$user = "";
$pass = "";
$first = "";
$last = "";
$type = "";
$email = "";
$stmt->bind_result($id, $user, $pass, $first, $last, $type, $email);
$stmt->fetch();
$stmt->close();
}
if ($pass === $filtered_form['pass']) {
$_SESSION['id'] = $id;
$_SESSION['user'] = $user;
$_SESSION['first'] = $first;
$_SESSION['last'] = $last;
$_SESSION['email'] = $email;
$_SESSION['type'] = $type;
header("Location:index.php");
exit;
} else {
return "Incorrect password";
}
And the problem goes away. Upon reviewing the PHP documentation, I cant find examples where the variables must be defined first, yet visual studio still shows it as an error. Any idea why this is?

Nope, it is not necessary when variables are passed by reference, which is the case here. So it's Visual Studio who is wrong here.
However, you are using obsoleted techniques here, and can get rid of these false positive warnings and reduce the amount of code at once:
$stmt = $conn->prepare("SELECT * FROM `users` WHERE user = ? ");
$stmt->bind_param("s", $filtered_form['user']);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
if ($row and password_verify($filtered_form['pass'], $row['pass']) {
$_SESSION['user'] = $row;
header("Location:index.php");
exit;
} else {
return "Incorrect password";
}
as you can see, get_result() gives you a much better result (pun not intended) than store_result(), letting you to store the user information in a single variable, so it won't litter the $_SESSION array.
And num_rows() proves to be completely useless (as it always happens).
An important note: you should never ever store passwords in plain text. Alwas shore a hashed password instead.

Related

prepared statements in if else statement

Everthing seems to work except inserting data stmt.
I've added closing the connection and adding closing the statement.
$error = $user = $pass = "";
if (isset($_SESSION['user'])) destroySession();
if (isset($_POST['user']))
{
$user = sanitizeString($_POST['user']);
$pass = sanitizeString($_POST['pass']);
if ($user == "" || $pass == "")
$error = 'Not all fields were entered<br><br>';
else
{
$stmt = $connection->prepare('SELECT * FROM members WHERE user=?');
$stmt->bind_param('s', $user);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows)
$error = 'That username already exists<br><br>';
else
{
$hashedPwd = password_hash($pass, PASSWORD_DEFAULT);
$stmt = $connection->prepare("INSERT INTO members (user, pass) VALUES (?,?)");
$stmt->bind_param("ss", $user, $hashedPwd);
$stmt->execute;
$stmt->close();
die('<h4>Account created</h4>Please Log in.</div></body></html>');
}
}
}
$connection->close();
I can expect the code to recognize if a user exists. However, I can not expect the database to be updated with a new user.
Placing error_reporting(E_ALL); at the top of the page will show that there is problem with the $stmt->execute;
$stmt->execute; should be stmt->execute();

MYSQLI Object oriented, what's wrong with my script?

I'm trying to do an execution of a query and see if it goes well, but right now it doesn't enter the IF or ELSE.
I had it on mysqli procedural and all worked flawlessy now I'm trying to change it to object oriented and it won't enter inside if/else.
if(isset($_POST['submit']))
{
$email = $_POST["email"];
$password = md5($_POST["password"]);
$query = "SELECT * FROM Users WHERE Email=? AND Password=?";
$stmt = $conn->prepare($query);
$stmt->bind_param('ss', $email,$password);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows == 1)
{
?>
<script type="text/javascript">
alert("INSIDE");
</script>
<?php
$row = $result->fetch_assoc();
if(isset($_POST['remember']))
{
$_SESSION["remember"] = "1";
}
$_SESSION["username"] = $row['Username'];
$_SESSION['check'] = "1";
$_SESSION['ID'] = $id;
$_SESSION['permission'] = $row['Admin'];
header("Location: dashboard.php");
exit;
}
else
{
?>
<script type="text/javascript">
alert("Credentials Are Wrong!");
</script>
<?php
exit;
}
$stmt->close();
}
Thank you all.
You should be using
$stmt->bind_result($col1, $col2 ...);
and
$result = $stmt->fetch();
in order to access the data from the query, rather than
$conn->query($stmt);
(an example is provided at https://secure.php.net/manual/en/mysqli-stmt.fetch.php). Note that for this to work you will need to specify the column names you want to fetch from the database, rather than using * in your SQL query, and for each column data is fetched from in the query, you should have a variable for in the fetch() parameters, so for example, something as follows should work (note these may not match the names of your database columns):
$email = $_POST["email"];
$password = md5($_POST["password"]);
$stmt = $conn->prepare("SELECT ID, Name FROM Users WHERE Email=? AND Password=?");
$stmt->bind_param('ss', $email, $password);
$stmt->execute();
$stmt->bind_result($id, $name);
$stmt->fetch();
$stmt->close();
echo $id . ': ' . $name;
Updated Answer
You are very close. Use $result = $stmt->get_result(); instead of $result = $stmt->query; to check to see if the query returned a result or not.
$email = $_POST["email"];
$password = md5($_POST["password"]);
$query = "SELECT * FROM Users WHERE Email = ? AND Password = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param('ss', $email, $password);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows !== 0){
if(isset($_POST['remember'])){
$_SESSION["remember"] = "1";
}
$_SESSION['check'] = "1";
$_SESSION['ID'] = $row['ID'];
header("Location: dashboard.php");
exit();
}else{
echo
'<script type="text/javascript">
alert("Credentials Are Wrong!");
</script>';
exit();
}
$stmt->close();
As several have already stated in their comments do not use MD5 for password hashes. PHP has it's own built in functions for handling passwords. Please research Password_has() and Password_verify(). Spend the time to research and implement these now instead of later. It will save you time.

Prepared statement for login function PHP

I am trying to write a parametrised login function in PHP.
The function should get the $id and $pass bind and execute statement and return an associative array from the database with $id, $password, $user_first_name.
Checking for user id and password validation, if true the session should start and set the session with the username from the database.
For some reason I can't get this working. Any suggestions?
Thanks!
public function logIn($id, $password)
{
$stmt = $this->link->prepare("SELECT user_id, user_name, user_password FROM Users WHERE user_id = ? ");
$stms->bind_param('i', $user_id);
if ($stmt->execute())
{
$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$dbuser_id = $row['user_id'];
$dbpassword = $row['user_password'];
$dbuser_first_name = $row['user_first_name'];
}
if($id == $dbuser_id and $password == $dbpassword)
{
session_start();
$_SESSION['session_user_first_name'] = $dbuser_first_name;
}
else
{
session_unset();
echo "Credentials do not match";
}
}
}
You have
$stms->bind_param('i', $user_id);
But your function signature is:
public function logIn($id, $password)
So you probably want:
$stms->bind_param('i', $id);
Have a look at $stms->bind_param('i', $user_id);:
stms should be stmt
$user_id should be $id
...

php login script not giving expected result, or any

i have a php login script which is accessed with a simple form:
<?php
session_start();
try{
$user = 'root';
$pass = null;
$pdo = new PDO('mysql:host=localhost; dbname=divebay;', $user, $pass);
if(isset($_SESSION['loggedin'])){
echo "1"; //already logged in
}
else{
$username = $_POST['username'];
$password = sha1($_POST['password']);
$ucheck = $pdo->prepare('SELECT * FROM user WHERE username = ?');
$ucheck->bindValue(1, $username);
$ucheck->execute();
if($ucheck->fetch(PDO::FETCH_OBJ)){
$stmt = $pdo->prepare('SELECT * FROM user WHERE username = ? AND password = ?');
$stmt->bindValue(1, $username);
$stmt->bindValue(2, $password);
if($stmt->fetch(PDO::FETCH_OBJ)){
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION['username'] = $row['username'];
$_SESSION['loggedin'] = 'YES';
$_SESSION['location'] = $row['location'];
echo "2"; //logged in
}
else{
echo "3"; //password incorrect
}
}
else{
echo "4"; //user does not exist
}
}
}catch(PDOException $e){
echo $e->getMessage();
}
?>
but when i attempt to run it using an account that i just created and have confirmed to exist within the database, i get no response from this script. i would expect it to echo 2 given that the login information is correct, but i get nothing
can anyone suggest what ive done wrong here?
It looks like you forgot to execute() the statement:
if($ucheck->fetch(PDO::FETCH_OBJ)){
$stmt = $pdo->prepare('SELECT * FROM user WHERE username = ? AND password = ?');
$stmt->bindValue(1, $username);
$stmt->bindValue(2, $password);
// Execute it!!!
if ($stmt->execute()) {
$row = $stmt->fetch(PDO::FETCH_OBJ);
if ($row) {
// And don't call fetch() again, since you would already have advanced
// the record pointer in the first fetch() above. If one record was returned,
// this one would always be FALSE.
//$row = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION['username'] = $row['username'];
$_SESSION['loggedin'] = 'YES';
$_SESSION['location'] = $row['location'];
echo "2"; //logged in
}
// else execute failed...
}
are you sure session.use_cookies = 1 in php.ini?
please make sure have name is PHPSESSION cookie.

says there are errors mysqli

this is so that I come from Denmark and use google translate because I'm bad at English so hope that it can be in level with, however, this is how my MySQLI code to go right down to the last words, and says there are errors . I've tried to write it right password and email in, but it can not be bothered to work at all in some way it keeps making mistakes, how can it be?
<?php
session_start();
include("include/database/db.php");
if($stmt = $mysqli->prepare("SELECT id, djnavn, hemmelig, rank FROM `brugere` WHERE `email` = ? AND `password` = ?"))
{
$stmt->bind_param('ss', $email, $password);
$email = $_POST['email'];
$password = sha1($_POST['password']);
$stmt->execute();
$stmt->bind_result($id, $djnavn, $hemmelig, $rank);
$stmt->fetch();
$count_res = $stmt->num_rows;
$stmt->close();
if($count_res > 0) {
$_SESSION["logged_in"] = true;
$_SESSION["user_id"] = $id;
$_SESSION["djnavn"] = $djnavn;
$_SESSION["hemmelig"] = $hemmelig;
$_SESSION["rank"] = $rank;
if($rank == 0)
{
echo "Your can not log in!";
}
if($rank == 1)
{
echo "Ok, members you can log in now!";
}
if($rank == 2)
{
echo "Ok, Admin you can log in now!";
}
}
else {
echo 'fail her: ' . $mysqli->error;
}
}
?>
Can you help me on it!!
First of all it's notification and it occurs because you don't define $email and $password before you use them.
$email = $_POST['email'];
$password = sha1($_POST['password']);
cut and paste them befor you bind params:
$stmt->bind_param('ss', $email, $password);

Categories