error with prepare() function - php

I have this login page that I writes it while watching a tutorial on Udemy. His code works properly, but in my code (the same), I have the following error:
Fatal error: Call to a member function prepare() on a non-object
This is the code:
<?php
//$var = 'This is our first web app page';
//echo $var;
//Connection Variables:
$dbhost = "localhost";
$dbname = "graphic_db";
$dbuser = "root";
$dbpass = "root";
//Connection to SQL:
$conn = new PDO("mysql:host=$dbhost; dbname=$dbname", $dbuser, $dbpass);
//Error messagin enabled:
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Adding a character set:
$conn = exec("SET CHARACTER SET utf8mb4");
$user = '';
$pass = '';
$sum = 0;
$error_msg = "Please type a username and a password";
if(isset($_POST['login_submit']))
{
//Start a session:
session_start();
$user = $_POST['username'];
$pass = $_POST['password'];
if(empty($user) && empty($pass))
{
echo $error_msg;
$pass = '';
}
if(empty($user) || empty($pass))
{
echo $error_msg;
$user = '';
$pass = '';
}
if(!empty($user) && !empty($pass))
{
//SQL:
$query = $conn->prepare("SELECT * FROM login WHERE user = :u AND password= :p LIMIT 1");
$query->bindParam(":u", $user);
$query->bindParam(":p", $pass);
//Execute query:
$query->execute();
$number_rows = $query->fetch(PDO::FETCH_NUM);
if($number_rows>0)
{
echo $user;
$_SESSION = $user;
$_SESSION = $pass;
header("Location: /pages/home.php");
}
else
{
echo "Invalid username or password";
header("Location: index.php");
}
//echo $user;
}
}
if(!isset($_POST['login_submit']))
{
echo "Login button not clicked";
}
?>

You destroy the $conn object with this statement:
$conn = exec("SET CHARACTER SET utf8mb4");
Replace it by:
$conn->exec("SET CHARACTER SET utf8mb4");
Note that from PHP 5.3.6 onwards, you can set the character set in the connection string, like this:
$conn = new PDO("mysql:host=$dbhost; dbname=$dbname; charset=utf8", $dbuser, $dbpass);
The separate exec call is then no longer necessary.

Related

SQL Login System

I coded this login system, but whenever I try to log in with the only username and password included in my database table, I get redirected to index.php?error=sqlerror. I checked the code for spelling mistakes but there are none. Could this be a problem with the database connection? I use MAMP. I have checked the database and it displays the Success message so it seems to be working. Do you know what I am doing wrong? Thank you!
DATABASE CONNECTION (file name: dbh.inc.php)
$servername = "127.0.0.1";
$dBUsername = "root";
$dBPassword = "";
$dBName = "gallerydatabase";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);
if (!$conn) {
echo "Error: Unable to connect to MySQL.";
}
echo "Success";
mysqli_close($conn);
?>
LOG-IN PHP CODE (file name: login.inc.php)
if (isset($_POST['login-submit'])) {
require 'dbh.inc.php';
$mailuid = $_POST['mailuid'];
$password = $_POST['pwd'];
if (empty($mailuid) || empty($password)) {
header ("Location: ../index.php?error=emptyfields");
exit();
}
else {
$sql = "SELECT * FROM users WHERE uidUsers=?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header ("Location: ../index.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $mailuid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
$pwdCheck = password_verify($password, $row['pwdUsers']);
if ($pwdCheck == false) {
header ("Location: ../index.php?error=wrongpwd");
exit();
}
else if ($pwdCheck == true) {
session_start();
$_SESSION['userId'] = $row['idUsers'];
$_SESSION['userUid'] = $row['uidUsers'];
header ("Location: ../index.php?login=sucess");
exit();
}
else {
header ("Location: ../index.php?error=wrongpwd");
exit();
}
}
else {
header ("Location: ../index.php?error=nouser");
exit();
}
}
}
}
else {
header ("Location: ../index.php");
exit();
}
I think the problem is in your file dbh.inc.php, you create the connection $conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName); and later you close it as well mysqli_close($conn);.
So by the time you come to use $conn in login.inc.php your connection is closed. What you need to do is write a function in dbh.inc.php that returns a live connection (don't call close), use that to do your DB queries / insert and after that close the connection.
A reusable database class can be written (functional style) as follows
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
trait DBInfo {
protected $servername = "127.0.0.1";
protected $username = "root";
protected $password = "";
protected $dbname = "gallerydatabase";
}
class Database{
use DBInfo;
function __construct() {}
function connection(){
$conn = new mysqli($this->servername, $this->username,
$this->password, $this->dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else{
$conn->autocommit(FALSE);
return $conn;
}
}
function select($sql, $fn2bind_takestmt, $fn2process_row_return_result){
try{
$result = array();
$conn = $this->connection();
$stmt = $conn->prepare($sql);
$fn2bind_takestmt($stmt);
$stmt->execute();
$rowset = $stmt->get_result();
while ($row = $rowset->fetch_assoc()) {
$obj = $fn2process_row_return_result($row);
array_push($result, $obj);
}
}catch(Exception $e) {
$result = NULL;
throw $e;
}finally{
if(isset($rowset))$rowset->close();
if(isset($stmt))$stmt->close();
if(isset($conn))$conn->close();
}
return $result;
}
// You can introduce functions for insert, update and delete as well
}
?>
and then for database selects for example login check
<?php
function allow_login($user, $pwd){
$sql = "SELECT count(*) rec_count FROM users WHERE uidUsers=? and pwdUsers=?"
$db = new Database();
$result = $db->select($sql,
function($stmt) use($user, $pwd){
$stmt->bind_param("ss", $user, $pwd);
},
function($row){
if($row['rec_count'] > 0){// or whatever
return TRUE;
}
return FALSE;
}
);
if(isset($result)){
return $result[0];
}
return $result;
}
?>

My PHP login system still Logging in even if the password or username is incorrect

Still loggin in even if the username and password is incorrect and also logins even if the value is null
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "login";
$conn = mysqli_connect($hostname, $username, $password, $dbname);
if (!$conn) {
die ("unable to connect");
}
if ($_POST) {
$uname = $_POST ["username"];
$pass = $_POST ["password"];
$sql = "SELECT * FROM users WHERE username = '$uname' AND password = '$pass' LIMIT 1 ";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1){
include("graph.php");
} else {
echo "Incorrect";
}
}
?>
First of all and very important it that you are open to SQL Injection attack, so you should use prepared statements, here is how should use your code, but instead of echo "Incorrect"; you should render different answer for each case:
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "login";
$conn = mysqli_connect($hostname, $username, $password, $dbname);
if (!$conn) {
die ("unable to connect");
}
if (isset($_POST["username"]) && isset($_POST["password"])) { // Check if you have posted data via POST
$uname = $_POST["username"];
$pass = $_POST["password"];
$sql = "SELECT * FROM users WHERE username = ? AND password = ? LIMIT 1 ";
if($stmt = $conn->prepare($sql)) { // Check for MySQL errors
$stmt->bind_param('ss', $uname, $pass);
if ($stmt->execute()) {
$stmt->close();
include("graph.php");
} else { // There is a problem with your SELECT // bind params
echo "Incorrect";
}
} else { // You should handle mysql errors here
echo "Incorrect";
}
} else { // You don't have POST data
echo "Incorrect";
}
?>
Prepared statements
Like #Kuya notice you have and many other problems, there is a lot of tutorials in Google about implementation of login system.
You must check the post request with isset() in php like this :
<?php
if (isset($_POST["username"] && isset($_POST["password"]))) {
//..... Your code here
}else {
echo "Incorrect password or username";
}
?>

Why does my script not return a record from mySQL?

I am building a login portal with mySQL and PHP
I have this file (dbc.php):
<?php
class db_connect {
protected $DB_SERVER = "localhost";
protected $DB_USERNAME = "root";
protected $DB_PASSWORD = "";
protected $DB_DATABASE = "mydb";
public function connect() {
$conn = new mysqli($this->DB_SERVER, $this->DB_USERNAME, $this->DB_PASSWORD, $this->DB_DATABASE);
if(mysqli_connect_errno()) {
die("Connection failed: ". mysqli_connect_errno());
}
return $conn;
}
}
?>
Then my actual PHP script (login.php) takes a POST from the login page:
<?php
//include database connection
include("dbc.php");
session_start();
//put post values into variables
$username = $_POST['username'];
$password = $_POST['password'];
//create db connector object
$db = new db_connect();
$conn = $db->connect();
//select correct db
mysqli_select_db($conn,”mydb”);
$username = mysqli_real_escape_string($conn,$username);
$query = "SELECT password FROM mydb.users WHERE username = '$username'";
$result = mysqli_query($conn,$query);
if(mysqli_num_rows($result) == 0)
{
header('Location: sorry.html');
}
$pwhash = $result;
if (password_verify($password, $pwhash)) {
header('Location: welcome.php');
} else {
header('Location: sorry.html');
}
?>
This never returns a value which is odd.
Any help appreciated!
$result holds a MySQLi response resource, not a string or array.
You need to change this line:
$pwhash = $result;
To this:
$pwhash = mysqli_fetch_assoc($result)['password'];

PDO/PHP LoginScript ending in error 500 using MAMP

I've been trying for a while now to get my loginscript working and i can't seem to find the issue, either im just blind or there's something else going on here.
It doesn't matter if i input the correct credentials or not into the form, i still end up getting a lovely error 500.
Any ideas?
The DB connect funtion:
function db_connect() {
if i move this column-->
$server = 'localhost';
$uname = 'root';
$passw = 'password';
$datab = 'database';
/* check connection */
try{
$conn = new PDO("mysql:host=$server;dbname=$datab;", $uname, $passw);
} catch(PDOException $e) {
die( "Connection failed: " . $e->getMessage());
}
<---
return $conn; /added this as suggested, still returns NULL.
}
The login file:
include('../lib/functions.php'); //This is correct!
db_connect();
<-- HERE, it works -->
Earlier had an issue where my password hash during register was faulty, so password_verify($_POST['password'], $results['passw'])had no effect, always returning false even with correct input.
if(!empty($_POST['username']) && !empty($_POST['password'])):
$records = $conn->prepare('SELECT uname,passw FROM users WHERE uname = :user AND passw = :pass');
$records->bindparam(':user', $_POST['username']);
$records->bindparam(':pass', $_POST['password']);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0 && password_verify($_POST['password'], $results['passw']) && $_POST['username'] == $results['uname']) //Also tried removing the &&-->username area incase two and statements were wrong without any luck {
die('It works!');
} else {
die('OR NOT!');
}
endif;
Your db_connect() function defines $conn in it's own scope. So, variable $conn is local. And after db_connect() ends executing $conn just disappears.
Outside this function $conn is simply NULL.
Return $conn to outer scope from your function:
function db_connect() {
$server = 'localhost';
$uname = 'root';
$passw = 'password';
$datab = 'database';
/* check connection */
try{
$conn = new PDO("mysql:host=$server;dbname=$datab;", $uname, $passw);
} catch(PDOException $e) {
die( "Connection failed: " . $e->getMessage());
}
return $conn; // here
}
And in your script:
include('../lib/functions.php'); //This is correct!
$conn = db_connect();
// other codes

MySQLi Query not Returning Results properly

I'm trying to switch my website over to MySQLi and I'm following the W3schools MySQLi guide to do so. I've hit a roadblock, though. I have a function to check if a specified user is an admin on the site. I've put echo in various spots to find where the issue is, and I've figured out that it most likely doesn't see the user. $username is set to the variable $user. Here's the whole code block (part of connect.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "lark";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
session_start();
if(!isset($_SESSION["user_login"])) {
$user = "";
} else {
$user = $_SESSION["user_login"];
}
//functions
function isAdmin($username) {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "lark";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql_get_is_admin = "SELECT * FROM users WHERE username='$username' LIMIT 1";
$get_is_admin = mysqli_query($conn, $sql_get_is_admin);
if(mysqli_num_rows($get_is_admin) > 0) {
echo "num_rows";
while ($row = mysqli_fetch_assoc($get_is_admin)) {
$is_admin_bool = $row['admin'];
echo "while";
if($is_admin_bool == 0){
return false;
} elseif ($is_admin_bool == 1) {
return true;
}
}
} else {
echo "not found.";
}
}
?>
Here's the code I used to test the $user variable:
<?php
include("connect.php");
?>
<div class="main">
<h1>Welcome back, <?php echo $user; ?></h1>
foo
<?php
/*if(isAdmin($user) == true) {
echo "<div style='display: table-cell;' class='rightcell'>
<h3 style='color: #000;'>Admin Tools</h3>
<a href='userlist.php' target='_blank'>Userlist</a>
</div>";
} else {
} */
echo isAdmin($user);
?>
</div>
I also had to reconnect to the database or else I'd get this error on the site:
Notice: Undefined variable: conn in C:\xampp\htdocs\lark\connect.php on line 33
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\lark\connect.php on line 33
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\lark\connect.php on line 35 not found.
If I fix it so there's no error, it just says "not found."
the $conn variable is not defined in your function, example:
function isAdmin($username) {
global $conn;
..................
}
You don't have $conn in your function, it is commented out.
function isAdmin($username) {
/*$servername = "localhost";
$username = "root";
$password = "";
$dbname = "lark";
$conn = mysqli_connect($servername, $username, $password, $dbname);*/

Categories