php mysql prepare statement not working [duplicate] - php

This question already has answers here:
Fatal error: Call to a member function prepare() on a non-object in
(2 answers)
Closed 6 years ago.
I'm currently learning php and mysql and am trying to build an authentication webpage where the user registers and is able to log in to a member protected page. The registration process works fine but for some reason I'm getting this error in my login execution script.
Fatal error: Call to a member function prepare() on a non-object in /homepages/8/d459264879/htdocs/tymbi_reg/login_exec.php on line 40
Line 40 is here if($stmt = $mysqli->prepare("SELECT * FROM member WHERE username=? AND password =?"))
I've been trying hard to find where the problem is without any success.
This is the code that I'm using in my login script
<?php
session_start();
require_once('connection.php');
$errmsg_arr = array();
$errflag = false;
$username = $_POST['username'];
$password = $_POST['password'];
if($username == '') {
$errmsg_arr[] = 'Username missing';
$errflag = true;
}
if($password == '') {
$errmsg_arr[] = 'Password missing';
$errflag = true;
}
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: index.php");
exit();
} else {
if($stmt = $mysqli->prepare("SELECT * FROM member WHERE username=? AND password =?"))
{
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$stmt->store_results();
if($stmt->num_rows > 0)
{
$SESSION['username'] = $username;
header("Location: home.php");
}
else
{
$error['alert'] = "Username or password are incorrect";
}
}
}
?>
Here's my connection.php code
<?php
$con=new mysqli("test","test","test","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
And yes, I have replaced the test values with my details

make sure you have $mysqli defined properly
$mysqli = new mysqli('host','user','pass','database_name');

You haven't defined $mysqli - your connection. That is why it's not working.
Unless it's defined in connection.php. Could you try var_dump $mysqli and see what you get?

$link = mysqli_connect("localhost", "user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
this helps in reading the connection error.
or you can also use
try
{
//your connection
}catch(Exception $e)
{
echo $e->getMessage();
}

I would recommend going all-in on using the Mysqli object and not mixing in the procedural functions. You would have caught your error earlier if you had written the connection logic like so:
$con = new mysqli("host","user","pass","db");
if ($mysqli->errno)
{
echo "Failed to connect to MySQL: " . $mysqli->error;
}
The OP declared the connection as $con and later tried to access it as $mysqli. mysqli_connect_errno() reports that $con is ok, but $mysqli->errno will fail because $mysqli is not an object at that point, because he named the the connection $con not $mysqli

Related

No database selected PHP login

Im trying to create a Login but everytime I type my credentials and click on Login, I get "No database selected"
Here is my PHP code
<?php define('DB_HOST', 'localhost');
define('DB_NAME', 'phplogin');
define('DB_USER','adminuser');
define('DB_PASSWORD','adminuser');
$con=mysql_connect(DB_HOST,DB_USER, "")
//$mysql_select_db = 'phplogin'
//or die("Failed to connect to MySQL: " . mysql_error());
//$db=mysql_select_db(DB_NAME,$con)
or die("Failed to connect to MySQL: " . mysql_error());
$ID = $_POST['user']; $Password = $_POST['pass'];
function SignIn()
{ session_start();
if(!empty($_POST['user']))
{ $query = mysql_query("SELECT * FROM phplogin where userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error()); $row = mysql_fetch_array($query) or die(mysql_error()); if(!empty($row['userName']) AND !empty($row['pass']))
{ $_SESSION['userName'] = $row['pass']; echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE..."; } else { echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY..."; } } } if(isset($_POST['submit'])) { SignIn(); } ?>
Where is the mistake?
Kind regards
newbie
You forgot to pass the variable $con as the link parameter.
mysql_select_db('database', $con) or die(mysql_error());
Use pdo for prevent sql injection.
You mistake this
mysql_select_db('database', $con) or die(mysql_error());
Mysql not available in php7. You can use mysqli or pdo.
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
I would really recommend you to use classes, methods and most importantly PDOs.
The use of "unescaped" mysqli is very insecure and vulnerable due to SQL injections.
Also, when storing passwords into your DB, hash them using the PHP function password_hash($password, PASSWORD_DEFAULT); This will generate a hash string that you can store in your DB.
That SignIn with the use of PDO and password_hash() and password_verify() to verify the password would look the following:
Class DataBase (DB) (db.php)
class DB {
private $error;
private $db;
function Conn()
{
try {
$this->db = new PDO('mysql:host=localhost;dbname=phplogin;', 'adminuser', 'adminuser'); //second adminuser is password
return $this->db; //Returns PDO object
}
catch(PDOException $ex){
return $ex->getMessage();
}
}
}
Your login.php (login.php)
require_once('db.php');
$db = new DB(); //Create instance of DB class
$conn = $db->Conn(); //Call Conn() method of DB class
$username = $_POST["user"];
$password = $_POST["pass"];
$statement = $conn->prepare("SELECT * FROM phplogin where userName = :user");
$statement->execute(array(":user"=>$username)); //For :user in SQL query it enters the username you entered in the login form (bind param)
$row = $statement->fetch(); //Returns the row from DB
//password_verify() checks if the password you've enteres matches the hash in the DB
//$row["pass"] is the hash you get returned from the SQL query aboth
if(password_verify($password, $row["pass"])){
return true; //Or echo "success"
}
else{
return false; //Or echo "Wrong username/password"
}
I hope I was able to help you :)

mysqli_query() & mysqli_real_escape_string() expects parameter 1 to be mysqli, null given [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 6 years ago.
im writing a login procedure, but im stuck at the this error and can't come up with a solution to fix it.
error: Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in the same goes for mysqli_query(). i already know that $connection is the problem because of other posts + the error asks for a msqli object.
i have a file where you where can call a funtion to open or close the db connection in includes/controller/dbcontroller.php. which contains the following code.
<?php
function openDBConnection(){
//1. create database connection
define("DB_SERVER","localhost");
define("DB_USER","root");
define("DB_PASS","");
define("DB_NAME","IppaSpil");
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
// test if connection occured
if(mysqli_connect_errno()){
echo "err: ".$connection;
die("Database connection failed: ".
mysqli_connect_error().
"(" . mysqli_connect_errno . ")"
);
}
}
function closeConnection(){
//close database connection
mysqli_close($connection);
}
?>
Then i have a file logincontroller which handles the login request. this file is also located in includes/controller/LoginController.php. this contains the following code.
<?php require_once("../session.php");?>
<?php require_once("DatabaseController.php");?>
<?php require_once("../functions.php");?>
<?php require_once("../validation_functions.php");?>
<?php
openDBConnection();
if (isset($_POST['login'])) {
$username = $_POST["username"];
$password = $_POST["password"];
//validations
$required_fields = array("username", "password");
validate_presences($required_fields);
if (empty($errors)){
$found_user = attempt_login($username, $password);
if ($found_user) {
// Succesa
redirect_to("profile_page.php");
} else {
//Failure
$_SESSION["failedlogin"] = "Username or password is wrong.";
echo"wrong pass";
closeConnection();
//redirect_to("login_page.php");
}
} else{
echo $errors;
$_SESSION["errors"] = $errors;
closeConnection();
//redirect_to("login_page.php");
}
}else{
//prob get request
closeConnection();
redirect_to("login_page.php");
}
?>
The last file that is part of this procedure is a functions file. this file includes all kinds of functions. but 2 of them are important for my procedure.
the file is located in includes/functions.php. and this is the code. i get 2 errors in this file. the line where it gives the error are marked with a ||.
function attempt_login($username, $password) {
$admin = find_user_by_username($username);
if ($admin) {
// found admin, now check password
if (password_check($password, $admin["password"])) {
// password matches
return $admin;
} else {
// password does not match
return false;
}
} else {
// admin not found
return false;
}
}
function find_user_by_username($username) {
global $connection;
$safe_username = mysqli_real_escape_string($connection, $username); ||
$query = "SELECT * ";
$query .= "FROM user ";
$query .= "WHERE username = '{$username}' ";
$query .= "LIMIT 1;";
$user_query = mysqli_query($connection, $query); ||
confirm_query($user_query);
if($user = mysqli_fetch_assoc($user_query)) {
return $user;
} else {
return null;
}
}
i suspect that the global $connection variable cant be accessed, but i dont know why...
Thank you in advance!
The problem is that $connection is defined in the scope of the function openDBconnection().
Even though you try to access it with
global $connection
this doesn't work.
a little test:
<?php
function test() {
$a = "test";
return $a;
}
test(); // run it, but don't take the return
//$a = test();
function test2() {
global $a;
echo $a; // doesn't show anything - $a is NULL
}
test2();
?>
If I uncomment //$a = test(); I get a result, because now $a is in global scope.
So you got the possibility to return $connection at the end of the function openDBconnection() and then assign it to a global in your script:
// end of openDBconnection
return $connection;
// where you establish connection in your script:
$connection = openDBconnection();
BUT it's not good practice to use globals. It would be better to pass that connection to your functions:
function attempt_login($username, $password, $connection) {
$admin = find_user_by_username($username, $connection);
....
}
function find_user_by_username($username, $connection) {
....
}

I can't run my PHP program and I received several errors

This is the image of the warning I got
I am new and I really want to learn PHP.
<?php
include 'mysql.conf.php';
if(isset($_POST['submit']))
{
if(!empty($_POST['user']) && !empty($_POST['password']))
{
$user = $_POST['user'];
$password = $_POST['password'];
$select = "SELECT * FROM admin where user=$user && password=$password";
$sql=mysql_query($select) or die(mysql_error());
if($sql)
{
echo "Login";
}
else
{
echo "Cannot Login";
}
}
}
?>
Below is my code for the mysql.conf.php
<?php
$name = "localhost";
$user = "root";
$pass = "gasamul";
$connect = mysql_connect($name, $user, $pass) or die(mysql_error());
$db = "portfolio";
if($connect)
{
$db = mysql_select_db($db) or die(mysql_error());
if($db)
{
//echo 'Database Connect';
}
}
else
{
echo 'Database can\'t connect';
}
?>
The name of my database is portfolio. I also named my table admin.
Since the error is stating clear that mysql_* extension is already deprecated and it is suggesting that you use mysqli_* or PDO extension.
Lets try the first option - mysqli_*. We establish first the connection to your database in mysql.conf.php:
$connect = new mysqli("localhost", "root", "gasamul", "portfolio");
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
Then, we can proceed with logintest.php:
include 'mysql.conf.php';
if(isset($_POST['submit']) && !empty($_POST['user']) && !empty($_POST['password']))
{
if($stmt = $con->prepare("SELECT * FROM admin WHERE user = ? AND password = ?")){ /* PREPARE YOUR QUERY */
$stmt->bind_param("ss", $_POST['user'], $_POST['password']); /* BIND THESE TWO VARIABLES TO THE QUERY ABOVE RESPECTIVELY; s STANDS FOR strings */
$stmt->execute(); /* EXECUTE THE QUERY */
$stmt->store_result(); /* STORE THE RESULT */
$noofrows = $stmt->num_rows; /* GET THE NUMBER OF RESULT */
if($noofrows > 0){ /* CHECK IF RESULT IS MORE THAN 0 */
echo "Login";
} else {
echo "Cannot Login";
}
$stmt->close(); /* CLOSE THE PREPARED STATEMENT */
}
}
You can also check out password_hash() for securing your password in your database.

PHP bindParam not working - blindValue is not the solution

I can't figure this out. I've googled it and a lot of answers refer to blindValue as the solution but I've also tried that with no luck.
The problem is that the SELECT statement is returning zero records but it should return one record. If I hard code the values into the SQL statement it works but passing them in as parameters isn't. Can some one please help me out with this? Thanks.
<?php
function checklogin($email, $password){
try
{
// Connection
$conn;
include_once('connect.php');
// Build Query
$sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = :email AND Password = :password';
// $sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = "a" AND Password = "a"';
// Prepare the SQL statement.
$stmt = $conn->prepare($sql);
// Add the value to the SQL statement
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
// Execute SQL
$stmt->execute();
// Get the data in the result object
$result = $stmt->fetchAll(); // $result is NULL always...
// echo $stmt->rowCount(); // rowCount is always ZERO....
// Check that we have some data
if ($result != null)
{
// Start session
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Search the results
foreach($result as $row){
// Set global environment variables with the key fields required
$_SESSION['UserID'] = $row['pkUserID'];
$_SESSION['Email'] = $row['Email'];
}
echo 'yippee';
// Return empty string
return '';
}
else {
// Failed login
return 'Login unsuccessful!';
}
$conn = null;
}
catch (PDOexception $e)
{
return 'Login failed: ' . $e->getMessage();
}
}
?>
the connect code is;
<?php
$servername = 'localhost';
$username = 'admin';
$password = 'password';
try {
// Change this line to connect to different database
// Also enable the extension in the php.ini for new database engine.
$conn = new PDO('mysql:host=localhost;dbname=database', $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo 'Connected successfully';
}
catch(PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
I'm connecting to mySQL. Thanks for the help,
Jim
It was a simple but stupid error.
I had a variable called $password also in the connect.php file which was overwriting the $password that I was passing to the checklogin.
Jim

Parsing Json From PHP to Xcode(Swift) with Mysql query

Morning All,
Im after a bit of advice/help with the below issue.
i have tried looking around and google'ing but I still don't understand where I'm going wrong. Please forgive me as I'm a complete noob at this.
some of you may have seem this code before but I'm want to adapt it. Once the user logs in i want to get the user ID from the MySQL Database and send that to swift in the JSON but i can't get it to work, i have tried putting the query in different places with no luck, JSON is completely new to me :(
Ideally > user logs in> swift sends JSON to verify>JSON-PHP verified by MySQL > PHP - JSON reply with success AND user id from the db.
Any Help would be amazing !!
<?php
header('Content-type: application/json');
require("conn.php");
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
$db_name = '***';
$db_user = '***';
$db_password = '***';
$server_url = 'localhost';
$mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
} else {
if ($stmt = $mysqli->prepare("SELECT username FROM users WHERE username = ? and password = ?")) {
$password = md5($password);
/* bind parameters for markers */
$stmt->bind_param("ss", $username, $password);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($id);
/* fetch value */
$stmt->fetch();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
if ($id) {
error_log("User $username: password match.");
echo '{"success":1, "ID":0}';
} else {
error_log("User $username: password doesn\'t match.");
echo '{"success":0,"error_message":"Invalid Username/Password"}';
}
}
} else {
echo '{"success":0,"error_message":"Invalid Username/Password."}';
}
}else {echo '{"success":0,"error_message":"Invalid Data."}';
}
?>

Categories