Error prepare() on a non-object with mysql - php

I'm getting a PHP Fatal error: Call to a member function prepare() on a non-object in /Config/functions.php on line 30.
Functions.php
function login($email, $password, $mysqli) {
if ($stmt = $mysqli->prepare("SELECT *
FROM users
WHERE email = ?
LIMIT 1")) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
The $mysqli is getting it's data from a constants in another file which has been included
if (login($email, $password, $mysqli) == true) {
// Login success
header('Location: ../protected_page.php');
} else {
// Login failed
header('Location: ../login.php?error=1');
}

Do you mean something like this?
// Contents of constants.php
define("HOST", "localhost");
define("USER", "root");
define("PASS", "pass");
define("DATABASE", "test");
// End of constants.php
include('constants.php');
$mysqli = new mysqli(HOST, USER, PASS, DATABASE);
function login($email, $password)
{
if ($stmt = $mysqli->prepare("SELECT * FROM users WHERE email = ? LIMIT 1"))
{
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
}
}

Related

PDO Exception : Tried to bind parameter number 65536. SQL Server supports a maximum of 2100 parameters

I want to read user data. But the result showing like
Tried to bind parameter number 65536. SQL Server supports a maximum
of 2100 parameters.
and here is my code of login.php (test with hard code first)
<?php
header("Content-type: application/json");
include_once 'Database.php';
include_once 'master.php';
//$username = $_GET['username'];
//$password = $_GET['password'];
$username = "angela123";
$password = "admin123";
// get database connection
$database = new Database();
$db = $database->getConnection();
$login = new Master($db);
$stmt = $login->Login($username, $password);
?>
and here is function of Login with parameter username and password
public function Login($username,$password)
{
// select all query
try {
$sqlsrvquery = ("
EXEC [dbo].[GetAllAdmin2]
#username = ':username',
#password = ':password',
");
// prepare query statement
$stmt = $this->conn->prepare($sqlsrvquery);
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$admin_arr = array(
"username" => $row['username'],
"password" => $row['password'],
);
}
if ($row = 0) {
$admin_arr = array(
"status" => false,
"message" => "Invalid Get Data Admin!",
);
}
} catch (Exception $e) {
print_r($e->getMessage());
}
print_r(json_encode($admin_arr));
}
What's going on in this code? actually the result is working properly on SQL Server with SP
Here is the Login SP
ALTER Procedure [dbo].[GetAllAdmin2]
(
#username varchar(55),
#password varchar(55)
)
as
begin
SELECT username, password
FROM Admin
WHERE username = #username and password = #password
and status = 'Active';
END
When execute the SP, the output should be showing username and password
username password
angela123 admin123
And here is database.php
<?php
class Database
{
// specify your own database credentials
private $host = "DESKTOP-N550JK\SQLEXPRESS";
private $user = "sa";
private $database = "Library";
private $password = "sqlserver123";
public $conn;
// get the database connection
public function getConnection(){
try {
$this->conn = new PDO("sqlsrv:Server=" .$this->host . ";database=" . $this->database, $this->user, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $exception) {
echo "Connection error: " . $exception->getMessage();
die("Database Connection Error");
}
return $this->conn;
}
}
?>
any solution of this? thanks
You are using parameter binding in a wrong way and you need to remove the quotes around the placeholders (:username and :password). As is explained in the documetation, the statement template can contain zero or more named (:name) or question mark (?) parameter markers for which real values will be substituted when the statement is executed.
<?php
...
// Statement
$sqlsrvquery = "
EXEC [dbo].[GetAllAdmin2]
#username = :username,
#password = :password
";
$stmt = $this->conn->prepare($sqlsrvquery);
// Parameter bindings
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
// Statement execution
$stmt->execute();
...
?>
An additional example, using the ? parameter marker:
<?php
...
// Statement
$sqlsrvquery = "
EXEC [dbo].[GetAllAdmin2]
#username = ?,
#password = ?
";
$stmt = $this->conn->prepare($sqlsrvquery);
// Parameter bindings
$stmt->bindParam(1, $username, PDO::PARAM_STR);
$stmt->bindParam(2, $password, PDO::PARAM_STR);
// Statement execution
$stmt->execute();
...
?>

PHP/MySQL: Check if username exists

I'm a beginner in php and I want to check if the username entered already exists.
Here is my code.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if (isset($_POST['submit'])) {
include "connect.php";
ValidateUser();
}
function ValidateUser()
{
if (!empty($_POST['username']) AND !empty($_POST['password'])) {
$queryrow=mysqli_query("SELECT * FROM websiteusers WHERE username = '$_POST['username']'");
if ($rows=mysqli_num_rows($queryrow)=0) {
RegisterUser();
}
}
function RegisterUser() {
echo "works up to here";
}
?>
It doesn't even give me an error despite turning error reporting on.
Have you even initialized a mysqli_connect?
$Connection = mysqli_connect("host","user","pass","database");
Then pass it to a function which uses mysqli_query() by:
function foo ($DB){
mysqli_query($DB,"QUERY HERE");
// Do other stuff
return /* Whatever you wish to return here*/
}
foo($Connection);
What you are trying to achieve can be done very easily with the following code. A bigger concern is security. It is good practice to both sanitize your input every time the user has a chance to input text.
Also, using prepared query's will put yet another layer of security.
Although this isn't using your provided code directly, I believe it is good to teach good habits.
If you have any questions feel free to ask.
$username = $_POST['username']; <-- sanitize this
$message = null;
$mysqli = new mysqli("localhost", "user", "password", "database");
$stmt = $mysqli->prepare("SELECT username FROM websiteusers WHERE username=?");
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($usernamesql);
$stmt->fetch();
if ($stmt->num_rows() > 0) {
RegisterUser();
} else {
$message .= 'username already exists';
}
Later on when you require more items to be queried, or more results to be bound:
$stmt = $mysqli->prepare("SELECT username,password,other1,other2 FROM websiteusers WHERE username=?");
$stmt->bind_param('s', $username); <-- the "s" means the argument is a strings, if a argument is stored as an int use "i", but one character for each argument is required.
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($usernamesql);
$stmt->fetch();
Multiple Arguments:
$stmt = $mysqli->prepare("SELECT username,password,other1,other2 FROM websiteusers WHERE username=? AND authenticated=?");
$stmt->bind_param('si', $username,$isauthenticated); <-- second argument is a INT or BOOL
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($usernamesql,$passwordsql,$other1sql,$other2sql);
$stmt->fetch();
When your expecting multiple results, and lets say you want to dump them into arrays:
$userarray = array();
$stmt = $mysqli->prepare("SELECT username FROM websiteusers WHERE username=?");
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($usernamesql);
while($stmt->fetch()){
array_push($userarray, $usernamesql);
}
$userarray is now an array of all the results fetched from the database.
Here is the right way to do this:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if (isset($_POST['submit'])) {
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if(check_user($mysqli, $_POST['username']){
registerUser();
}else{
echo 'user exist, cannot register';
}
}
function check_user($conn, $username){
$query = "SELECT * FROM websiteusers WHERE username = ?";
if ($stmt = $conn->prepare($query)) {
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->close();
}
return $stmt->num_rows === 0;
}
function registerUser() {
echo "registering user ...";
}
Read up on prepared statement

Undeclared Variable mysqli

I'm having trouble with mysqli and prepared statements. I've just started learning mysqli an hour and am having trouble not understanding why I'm getting these two errors:
Notice: Undefined variable: mysqli in /opt/lampp/htdocs/lr/testingi.php on line 17
Fatal error: Call to a member function prepare() on a non-object in /opt/lampp/htdocs
/lr/testingi.php on line 17
I have a file that contains the database connection. Here it is.
$mysqli = new mysqli("localhost", "user", "password", "db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
Here is the test file that is reproducing the error.
session_start();
require_once 'core/database/connect.php';
function user_id_from_username ($username) {
if ($stmt = $mysqli->prepare("SELECT `user_id` FROM `users` WHERE `username` = ?"))
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($user_id);
echo $user_id;
$stmt->close();
}
$username = 'Jason';
user_id_from_username ($username);
Looks like you're not passing $mysqli into the user_id_from_username function.
2 quick options:
1. A global
function user_id_from_username ($username) {
global $mysqli;
if ($stmt = $mysqli->prepare("SELECT `user_id` FROM `users` WHERE `username` = ?"))
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($user_id);
echo $user_id;
$stmt->close();
}
2. a second parameter
function user_id_from_username ($mysqli, $username) {//..}
user_id_from_username($mysqli, $username);

Error when trying to check if email already exists in db

I am receiving this error when I try to check if an email already exists in the database and not sure why:
Fatal error: Call to a member function bind_param() on a non-object in ""
Here is my code:
$email = $_POST['email'];
//prepare and set the query and then execute it
$stmt = $conn2->prepare("SELECT COUNT (*) FROM users WHERE email = ?");
$stmt->bind_param('s', $email);
$stmt->execute();
// grab the result
$stmt->store_result();
// get the count
$numRows = $stmt->num_rows();
if( $numRows )
{
echo "<p class='red'>Email is already registered with us</p>";
}
else
//if we have no errors, do the SQL
I have a seperate database connection file:
function DB2($host='', $user='', $password='', $db='') {
/* Create a new mysqli object with database connection parameters */
$mysqli = new mysqli($host, $user, $password, $db);
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
return $mysqli;
}
Which is linked to this file using:
$conn2 = DB2();
You didn't say what language this is in. I'm assuming it's perl and dbi.
$email = $_POST['email'];
//prepare and set the query and then execute it
$stmt = $conn2->prepare("SELECT COUNT (*) FROM users WHERE email = ?");
$stmt->bind_param($email);
$stmt->execute();
should be
$email = $_POST['email'];
//prepare and set the query and then execute it
$stmt = $conn2->prepare("SELECT 1 FROM users WHERE email = ? fetch first row only");
$stmt->execute($email);
I don't know what store_result() is. I don't think it's part of DBI. You possibly want to do:
#found = $stmt->selectrow_array();
if ($#found) { #email was found }

Cannot get mysqli bind_param bind a variable

I am writing following code to fetch a row from table:
$query = "SELECT ........FROM ............WHERE........AND ID = ?";
$conn = new Connection();
$stmt = $conn->mysqli->prepare($query);
$stmt->bind_param('i', $_SESSION['id']);
$stmt->execute();
echo 'Num rows = '.$stmt->num_rows();
Here's the code for Connection();
define('SERVER', 'localhost');
define('USER', 'root');
define('PASS', 'xxx');
define('DB', 'xxx');
class Connection{
var $mysqli = null;
function __construct(){
try{
if(!$this->mysqli){
$this->mysqli = new MySQLi(SERVER, USER, PASS, DB);
if(!$this->mysqli)
throw new Exception('Could not create connection using MySQLi', 'NO_CONNECTION');
}
}
catch(Exception $ex){
echo "ERROR: ".$e->getMessage();
}
}
}
If I echo the query and run it on Navicat with ID equal to the value of $_SESSION['id'], it does return me a row. But on the web-page, it show output as:
Num rows = 0
What's wrong with the code? Plz note that echo $_SESSION['id'] displays the value.
Thanks
Store your result set with store_result(), then access $stmt->num_rows as a property, not a method. (don't use ())
$query = "SELECT ........FROM ............WHERE........AND ID = ?";
$conn = new Connection();
$stmt = $conn->mysqli->prepare($query);
$stmt->bind_param('i', $_SESSION['id']);
$stmt->execute();
// Call store_result() before accessing num_rows()
$stmt->store_result();
// And access num_rows as a property, not a method
echo 'Num rows = '.$stmt->num_rows;

Categories