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

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.

Related

Getting a value from sql table for a certain user using sessions

How to get the value of the column 'ProfilePicture' for the current user (which is stored in a session) from a database and save it into a variable?
Here is an example of a possible structure for the query:
if($email="iahmedwael#gmail.com" show 'ProfilePicture' value for that username) //declare a variable to save the value of ProfilePicture
<?php
$posted = true;
if (isset($_REQUEST['attempt'])) {
$link = mysqli_connect("localhost", "root", "", 'new1') or die('cant connect to database');
$email = mysqli_escape_string($link, $_POST['email']);
$password = mysqli_escape_string($link, $_POST['Password']);
$query = mysqli_query($link, " SELECT *
FROM 360tery
WHERE Email='$email'
OR Username= '$email'
AND Password='$password' "
) or die(mysql_error());
$total = mysqli_num_rows($query);
if ($total > 0) {
session_start();
$_SESSION['email'] = $email;
header('location: /html/updatedtimeline.html');
} else {
echo "<script type='text/javascript'>alert('Wrong username or Password!'); window.location.href='../html/mainpage.html';</script>";
}
}
For security purposes, it's my recommendation that you use PDO for all your database connections and queries to prevent SQL Injection.
I have changed your code into PDO. It should also get the value from the column ProfilePicture for the current user and save it to the variable $picture
Note: you will need to enter your database, name and password for the database connection.
Login Page
<?php
session_start();
$posted = true;
if(isset($_POST['attempt'])) {
$con = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'pass');
$email = $_POST['email'];
$password = $_POST['Password'];
$stmt = $con->prepare("SELECT * FROM 360tery WHERE Email=:email OR Username=:email");
$stmt->bindParam(':email', $email);
$stmt->execute();
if($stmt->rowCount() > 0) {
$row = $stmt->fetch();
if(password_verify($password, $row['Password'])) {
$_SESSION['email'] = $email;
header('location: /html/updatedtimeline.html');
}else{
echo "<script type='text/javascript'>alert('Wrong username or Password!'); window.location.href='../html/mainpage.html';</script>";
}
}
}
?>
User Page
<?php
session_start();
$con = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'pass');
$stmt = $con->prepare("SELECT ProfilePicture FROM 360tery WHERE username=:email OR Email=:email");
$stmt->bindParam(':email', $_SESSION['email']);
$stmt->execute();
if($stmt->rowCount() > 0) {
$row = $stmt->fetch();
$picture = $row['ProfilePicture'];
}
?>
Please let me know if you find any errors in the code or it doesn't work as planned.

PHP prepared statement doesn´t work on webserver

Hello i have a problem with following code on my website:
<?php
session_start();
include '../databaseConnector.php';
$uid = mysqli_real_escape_string($connector, $_POST['uid']);
$pwd = mysqli_real_escape_string($connector, $_POST['pwd']);
$stmt = $connector->prepare("SELECT * FROM nutzer WHERE uid=?");
$stmt->bind_param("s", $username);
$username = $uid;
$stmt->execute();
$result = $stmt->get_result();
$row = mysqli_fetch_assoc($result);
$hash_pw = $row['pwd'];
$dehash = password_verify($pwd, $hash_pw);
if($dehash == 0)
{
header("Location: ../loginscreen.php?error=pwwrong");
exit();
}else{
$stmt2 = $connector->prepare("SELECT * FROM nutzer WHERE uid=? AND pwd=?");
$stmt2->bind_param("ss", $username2, $password2);
$username2 = $uid;
$password2 = $hash_pw;
$stmt2->execute();
$result = $stmt2->get_result();
$stmt->close();
if(!$row =$result->fetch_assoc())
{
echo "Your username or password is incorrect!";
} else{
$_SESSION['id'] = $row['id'];
$_SESSION['uid'] = $row['uid'];
$_SESSION['email'] = $row['email'];
$_SESSION['first'] = $row['first'];
$_SESSION['last'] = $row['last'];
}
header("Location: ../loginscreen.php"); // go to page after signing in
}
The prepared statements work perfectly on XAMPP on my localhost but when i upload them on my webserver there is nothing happening after logging in. It is just a blank screen. My webserver is running on PHP 5.6 if that is important.
Just for anybody who will see this in the future. I saw that my hoster doesn´t support MYSQLnd which is required for the get_result() function. I just wrote it different with fetch() and bind_result(). There are many solution examples in the web.

PHP password verify

I cannot verify a password using password_verify. I used BCRYPT for password hashing. Help me find mistake in this code and how do I bind variables in the below select statement:
<?php
if (isset($_POST['submit'])) {
// echo "ok";
$con = connect();
$email = $_POST['email_id'];
$pass_word = $_POST['pass_word'];
if ($con) {
$query = mysqli_query($con,"select * from login where email_id='".$email."'");
$rows = mysqli_num_rows($query);
if ($query) {
$row = mysqli_fetch_assoc($query);
if ($row) {
$hash = $row['password'];
if (password_verify($pass_word,$hash) {
echo '<strong>Successful' ;
} else {
echo "Invalid Password";
}
}
}
} else {
die("Connection Error");
}
}
?>
missing parenthesis:
change here
if(password_verify($pass_word,$hash)
to
if(password_verify($pass_word,$hash))
Extended as request:
"select * from login where email_id='".$email."'";
becomes
"select * from login where email_id= ?";
which is passed to the $mysqli::prepare:
$stmt = $con->prepare("SELECT * FROM login WHERE email_id= ?");
$stmt->bind_param( "s", $email); // "ss' is a format string, each "s" means string
$stmt->execute();
$stmt->bind_result($email);// then fetch and close the statement
need a closed parenthes here in
if(password_verify($pass_word,$hash)
also your query is exposed to sql injection try to prepare it and bind the parameter with
$query=$conn->prepare($con,"select * from login where email_id=?");
$query->bind_param('s',$email); //change 's' with 'i' if you are expecting an integer
$query->execute()//to execute the query
Use this for bind param
$stmt = $con->prepare("select * from login where email_id=?");
$stmt->bind_param("s", $email);
$stmt->execute();

Having trouble with PDO queries

Can someone please take a look at this block of code? I am very new to the PDO method, for some reason this keeps causing a 500 error whenever I submit.
I have narrowed it down to this:
Could it be this part? $hash = $stmt['hash'];
if(empty($response['error'])){
$stmt = $db->prepare("SELECT * FROM Login WHERE username= :username"); // Prepare the query
// Bind the parameters to the query
$stmt->bindParam(':username', $username);
//Carry out the query
$stmt->execute();
$hash = $stmt['hash'];
$affectedRows = $stmt->rowCount(); // Getting affected rows count
if($affectedRows != 1){
$response['error'][] = "No User is related to the Username";
}
if(password_verify($password, $hash))
{
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $stmt['ID'];
}
else
{
$response['error'][] = "Your password is invalid.";
}
}
If you need more info please ask I will be happy to supply anything I can.
You need to fetch the result of the query to have it accessible. I'm not sure this is your issue, I'd think $hash would just be set to Resource Id#x, not what you want but not a 500. Here's how to fetch (http://php.net/manual/en/pdostatement.fetch.php) though
$stmt = $db->prepare("SELECT * FROM Login WHERE username= :username"); // Prepare the query
// Bind the parameters to the query
$stmt->bindParam(':username', $username);
//Carry out the query
$stmt->execute();
//if you will only be getting back one result you dont need the while or hashes as an array
while($result = $stmt->fetch(PDO::FETCH_ASSOC)){
$hashes[] = $result['hash'];
}
Here's a thread on enabling error reporting PHP production server - turn on error messages
Also you don't have to bind to pass values with the PDO. You also could do
$stmt = $db->prepare("SELECT * FROM Login WHERE username= ?"); // Prepare the query
$stmt->execute(array($username));
Your code is really messy. Just to help you with start point:
if (empty($response['error'])) {
if (isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $db->prepare("SELECT * FROM Login WHERE username= :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$hash = $row['hash'];
if(password_verify($password, $hash)) {
$_SESSION['username'] = $username;
$_SESSION['userid'] = $stmt['ID'];
} else {
$response['error'][] = "Your password is invalid.";
}
} else {
$response['error'][] = "No User is related to the Username";
}
} else {
$response['error'][] = "Username is not set!";
}
}

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.

Categories