mysqli_stmt_get_result() replacing - php

here's my code I use on my local "development" server, but unfortunately my remote server doesn't support mysqli native driver - how is it possible to replace mysqli_stmt_get_result();?
CODE:
$query = "SELECT * FROM class WHERE email = ? AND password = ?";
$stmt = mysqli_prepare($connect,$query);
mysqli_stmt_bind_param($stmt,'ss',$nickname,$password);
mysqli_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
include("year_tester.php");
if(mysqli_num_rows($result) != ""){
$_SESSION['loggedIn'] = true;
$_SESSION['loginName'] = $nickname;
$_SESSION['classIdentify'] = $rocnik.".".$className;
header('Location: index.php');
}

...is it acceptable to rewrite it in PDO? :p
$pdoh=new PDO("mysql:host=127.0.0.1;dbname=testdb;charset=utf8",
$mysqldb_username,$mysqldb‌​_password,
array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));
$query = "SELECT * FROM class WHERE email = ? AND password = ?";
//$stmt = mysqli_prepare($connect,$query);
$pdosh=$pdoh->prepare($query);
//mysqli_stmt_bind_param($stmt,'ss',$nickname,$password);
//i feel sorry for the guy writing the garabage collector :(
$pdosh->bindParam(1,$nickname, PDO::PARAM_STR);
$pdosh->bindParam(2,$password, PDO::PARAM_STR);
//mysqli_execute($stmt);
$pdosh->execute(); //using ERRMODE_EXCEPTION right?
//$result = mysqli_stmt_get_result($stmt);
//$row = mysqli_fetch_assoc($result);
$row=$pdosh->fetch();
require("year_tester.php");
if($pdosh->rowCount()>0/*mysqli_num_rows($result) != ""*/){
$_SESSION['loggedIn'] = true;
$_SESSION['loginName'] = $nickname;
$_SESSION['classIdentify'] = $rocnik.".".$className;
header('Location: index.php');
}

Related

Get certain value from database category

I want only verified accounts logging in to my website and therefore I've set up and a category called Verification which can either be 0(not verified) or 1(verified) in PHPMyAdmin. Ive gotten it to work so that it changes the value when the account is verified but I cant figure out how to check if the account's "Verification" is 1 or 0. I tried doing this but with no success:
What I've tried
$test = "SELECT Verification FROM users WHERE Verification = 1 AND users_uid = $uid";
if($test == false){
$test = null;
header("location: ../LoginPage.php?error=accountNotVerified");
exit();
}
And here is the whole code if this helps to clear anything up for you.
The whole code(This code works fine but doesn't check if the account is verified)
<?php
class Login extends Dbh{
protected function getUser($uid, $pwd){
$stmt = $this->connect()->prepare('SELECT users_pwd FROM users WHERE users_uid = ? OR users_email = ?;');
if(!$stmt->execute(array($uid, $pwd))){
$stmt = null;
header("location: ../LoginPage.php?error=stmtfailed");
exit();
}
if($stmt->rowCount()==0){
$stmt = null;
header("location: ../LoginPage.php?error=usernotfound");
exit();
}
$pwdHashed = $stmt->fetchAll(PDO::FETCH_ASSOC);
$checkPwd = password_verify($pwd,$pwdHashed[0]["users_pwd"]);
if($checkPwd ==false){
$stmt = null;
header("location: ../LoginPage.php?error=wrongpassword");
exit();
}
elseif($checkPwd == true){
$stmt = $this->connect()->prepare('SELECT * FROM users WHERE users_uid = ? OR users_email = ? AND users_pwd = ?;');
//HERE IS WHERE I WANT TO IMPLEMENT THE CODE WRITTEN ABOVE BUT IN A WORKING VERSION
//HERE IS WHERE I WANT TO IMPLEMENT THE CODE WRITTEN ABOVE BUT IN A WORKING VERSION
//HERE IS WHERE I WANT TO IMPLEMENT THE CODE WRITTEN ABOVE BUT IN A WORKING VERSION
if(!$stmt->execute(array($uid, $uid, $pwd))){
$stmt = null;
header("location: ../LoginPage.php?error=stmtfailed");
exit();
}
}
if($stmt->rowCount()==0){
$stmt = null;
header("location: ../LoginPage.php?error=usernotfound");
exit();
}
$user = $stmt->fetchAll(PDO::FETCH_ASSOC);
session_start();
$_SESSION["userid"] = $user[0]["users_id"];
$_SESSION["useruid"] = $user[0]["users_uid"];
$stmt = null;
}
}
In conclusion, I want to check whether or not the "Verfication"-value is 1 or 0 in my database.
You may change password check
from
$stmt = $this->connect()->prepare('SELECT users_pwd FROM users WHERE users_uid = ? OR users_email = ?;');
...
$pwdHashed = $stmt->fetchAll(PDO::FETCH_ASSOC);
$checkPwd = password_verify($pwd,$pwdHashed[0]["users_pwd"]);
if($checkPwd ==false){
$stmt = null;
header("location: ../LoginPage.php?error=wrongpassword");
exit();
}
to
$stmt = $this->connect()->prepare('SELECT users_pwd, verification FROM users WHERE users_uid = ? OR users_email = ?;');
...
$dbData = $stmt->fetchAll(PDO::FETCH_ASSOC);
$verification = $dbData[0]["verification"]
$checkPwd = password_verify($pwd,$dbData[0]["users_pwd"]);
if($checkPwd === false || $verification !== 1){
$stmt = null;
if($checkPwd === false) {
header("location: ../LoginPage.php?error=wrongpassword");
} else {
header("location: ../LoginPage.php?error=notverified");
}
exit();
}
That will check password and verification status.

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.

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 PDO Logging Into Account

<?php
function login($database, $username, $password) {
$query = "SELECT * FROM `users` WHERE username=':username'";
$query = $database->prepare($query);
$query->execute(array(':username' => $username));
$rowcount = $query->rowCount();
if($rowcount == 1){
$row = mysql_fetch_array($query);
$dbPass = $row["password"];
if($password == $dbPass){
session_start();
$dbId = $row["id"];
$dbUser = $row["username"];
$dbEmail = $row["email"];
$dbFirstname = $row["firstname"];
$dbLastname = $row["lastname"];
//Register Session Variables
$_SESSION['id'] = $dbId;
$_SESSION['username'] = $dbUser;
$_SESSION['email'] = $dbEmail;
$_SESSION['name'] = $dbFirstname." ".$dbLastname;
return true;
} else
return false;
} else
return false;
}
?>
This is a PHP code snippet from a project I am globally converting to PDO. This is the functions.php file for the login page. Obviously it is not fully converted to PDO so don't criticize that, but basically in the login.php file I have it access this method, and pass the database(which is required in), the username, and the password from the form. I setup a basic query to find all users with the username input of the form. Then i prepare, and execute the query. I then need a row count, so I setup a $rowcount variable running the rowCount() method on the query, but the code does not move past there. The rowcount is == 0 when I echo it out so it won't proceed to the following if statement. Am I doing something wrong with the PDO or something? Or the rowCount(). My suspicion is that perhaps I am calling the rowCount() too late, so I tried moving it up before I execute the $query but no luck. Thank you!
___EDIT___
<?php
session_start();
function login($database, $username, $password) {
$query = "SELECT * FROM `users` WHERE username=':username'";
$query = $database->prepare($query);
$query->execute(array(':username' => $username));
if($query->rowCount()){
$row = $query->fetch();
echo $row;
$dbPass = $row["password"];
if($password == $dbPass){
$dbId = $row["id"];
$dbUser = $row["username"];
$dbEmail = $row["email"];
$dbFirstname = $row["firstname"];
$dbLastname = $row["lastname"];
//Register Session Variables
$_SESSION['id'] = $dbId;
$_SESSION['username'] = $dbUser;
$_SESSION['email'] = $dbEmail;
$_SESSION['name'] = $dbFirstname." ".$dbLastname;
return true;
} else {
return false;
}
} else {
return false;
}
}
?>
Don't mix pdo and mysql_ functions together. NEVER!
Don't store password in plain text. NEVER! Instead try Password_compat !
First:
Is to replace
$row = mysql_fetch_array($query);
with
$query->fetchAll(PDO::FETCH_ASSOC)
Second:
session_start() should appear at the top of your script, not inside your function.
Third:
Is to replace
$rowcount = $query->rowCount();
if($rowcount == 1){
//
}
with this:
if($query->rowCount()){}
Fourth:
This is BAD!!
return true;
} else
return false;
} else
return false;
}
Always, use a complete delimiter. You are instilling a bad-codding practice, that will haunt you for life.
Simple do
if($foo){
if(){
//do something
}else if{
//do something
}else{
//do something
}
}
Fifth:
~Not good, but definitely better that your approach.
function small_query(pdo $pdo, $query, array $value){
$stmt = $pdo->prepare($query);
$stmt->execute($value);
return $stmt->fetchAll();
}
$pdo = new PDO('mysql:host=localhost; dbname=foo', 'root', 'pass');
$result = small_query($pdo, "SELECT * FROM users WHERE name = ?", array($_POST['name']))
EDIT.
Since you seem to love your code so much, I have done it your way. Try this:
<?php
session_start();
function login($database, $username, $password){
$query = "SELECT * FROM users WHERE username = ?";
$stmt = $database->prepare($query);
$stmt->execute(array($username));
if($stmt->rowCount()){
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$_SESSION["id"] = $result["id"];
$_SESSION["username"] = $result["username"];
$_SESSION["email"] = $result["email"];
return true;
}else{
return false;
}
}

How to successfully rewrite old mysql-php code with deprecated mysql_* functions? Part II

Continuing from this topic where we explained most problems with PDO How to successfully rewrite old mysql-php code with deprecated mysql_* functions? now about understanding prepared statements... So in order to get remove mysql_* strings there are some examples so my question for all and other users may this find helpfull which solution is the best ... so example of old "made up* code:
in config.php:
$db = new dbConn('127.0.0.1', 'root', 'pass', 'people', 'login');
in login.php
$db->selectDb("login");
$query = mysql_query("SELECT * FROM account WHERE id='".$_session["id"]."' LIMIT 1");
$result = mysql_fetch_array($query);
$_session["id"] is defined when login actually, so now we have several options to do so:
In config.php:
$db_people = new PDO('mysql:host=127.0.0.1;dbname=people;charset=UTF-8', 'root', 'pass');
$db_login = new PDO('mysql:host=127.0.0.1;dbname=login;charset=UTF-8', 'root', 'pass');
And in login.php 1):
$stmt = $db_login->prepare("SELECT * FROM account WHERE id=? LIMIT 1");
$stmt->execute(array($_session["id"]));
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
Or this one is better when exclude query? Or the previous one is better?
And in login.php 2):
$query = "SELECT * FROM account WHERE id=? LIMIT 1";
$parameters = array($_session["id"]);
$statement = $db_login->prepare($query);
$statement->execute($parameters);
$results = $statement->fetch(PDO::FETCH_ASSOC);
And this login form:
public function login($user, $password)
{
global $web, $db;
if (!empty($user) && !empty($password))
{
$user = $web->esc($user);
$password = $web->doHash($user, $password);
$db->selectDb('login');
$qw = mysql_query("SELECT * FROM account WHERE username='".$user."' AND pass_hash='".$password."'");
if (mysql_num_rows($qw) > 0)
{
$result = mysql_fetch_array($qw);
$_session['name'] = $result['username'];
$_session['id'] = $result['id'];
return true;
}
else
return false;
}
else
return false;
}
Transfered into this form:
public function login($user, $password)
{
global $web, $db_login;
if (!empty($user) && !empty($password))
{
$user = $web->esc($user);
$password = $web->doHash($user, $password);
$stmt = $db_login->prepare("SELECT * FROM account WHERE username=? AND pass_hash=?");
$stmt->execute(array($user, $password));
$rows = $stmt->rowCount();
if ($rows > 0)
{
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$_session['name'] = $result['username'];
$_session['id'] = $result['id'];
return true;
}
else
return false;
}
else
return false;
}
Is it ok or again do separate query or maybe do it in complete different way? Thank you all.
Also when there is multiple stmt should I use different name for it? For example I use stmt once and make a result1 after I do stmt second with result2 should I choose different name also for stmt variable or only result name is ok to be different?
OK so solution login.php 1) seems to be ok simple and no rush.
Also the login page seems to be working fine and therefore it should be according to every rules and ok :)

Categories