Undeclared Variable mysqli - php

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);

Related

Error: call to a member function bind_param() , when doing 2nd bind_param()

I got the error
Fatal error: Uncaught Error: Call to a member function bind_param() on boolean
on this line:
$stmt->bind_param("i", $r);
Is my query prepared correctly?
I checked the name of the table and columns and they are correct
$stmt = $conn->prepare("UPDATE db_control SET cve_usuario=? WHERE cve_control=1");
$stmt->bind_param("i", $r);
heres my whole code:
<?php
$servername = "localhost";
$username = "usuario";
$password = "usuario";
$database = "proyectofinal";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("SELECT cve_usuario FROM db_control");
if($stmt->execute())
{
$stmt->bind_result($r);
if($stmt->fetch()){
echo $r;
}
$r = $r + 1;
echo "<br>" . $r;
$stmt = $conn->prepare("UPDATE db_control SET cve_usuario=? WHERE cve_control=1");
$stmt->bind_param("i", $r);
if($stmt->execute())
{
/*do something*/
}
}
?>
From the documentation of mysqli::prepare:
Return Values
mysqli_prepare() returns a statement object or FALSE if an error occurred.
You should check that the prepare call succeeded with a strict check ($stmt !== FALSE), though a simple if ($stmt) works in this specific case also.
If you want to know what made your prepare call fail, you can check the error code / message:
$stmt = $conn->prepare("...");
if ($stmt) {
// bind parameters, execute statement, etc
} else {
echo "MySQLi error: " . $conn->error;
}
I solved it! Forgot to close the connection before preparing the 2nd query.
That do the trick! Thanks

Uncaught Error: Call to a member function query() on null

I got stuck for hours in the code below. I don't know how I can fix this error.
Notice: Undefined variable: mysqli in D:\xampp\htdocs\recon\register.php on line 19
Fatal error: Uncaught Error: Call to a member function query() on null in D:\xampp\htdocs\recon\register.php:19 Stack trace: #0 {main} thrown in D:\xampp\htdocs\recon\register.php on line 19
<?php
$conn = new mysqli('localhost', 'root', '', 'user');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$uname = $_POST['uname'];
$psw = $_POST['psw'];
$options = [
'cost' => 12,];
$hashedpassword= password_hash($psw, PASSWORD_BCRYPT, $options);
$result = $mysqli->query("SELECT username FROM registration WHERE username = '$uname'");
$row_count = $result->num_rows;
if($row_count == 1) {
echo 'User already exists, try another one.'; }
else {
$query = "INSERT INTO user (username, password) VALUES(?, ?)";
$statement = $mysqli->prepare($query);
$statement->bind_param('ss', $uname, $hashedpassword);
if($statement->execute())
{
print 'Success! Last inserted record : ' .$statement->insert_id .'<br />';
}
else
{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
}
?>
You are declaring instance of mysqli called $conn. This represents your connection to DB. You should call methods on variable $conn and not on (undefined) variable $mysqli. So ie. your line 19 should be:
$result = $conn->query("SELECT username FROM registration WHERE username = '$uname'")
Also to prevent SQL-Injection on your queries/web-pages you should use prepared statements EVERYWHERE(including SELECT).
you get this error if you spell constructor incorrectly.
For instance, correct syntax of constructor in php,
__construct(){}
You might have mistakenly written,
__contruct(){}
Similarly, check for other functions.

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

Error prepare() on a non-object with mysql

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();
}
}

PHP Prepared Statement/Bind Param Code Crashing

Can someone explain why this gives me a 500 internal server error? I tried adding some sql injection protection and I'm not sure what I'm doing wrong. Should I be doing this in an object oriented style instead of procedural?
<?php
$conn = mysqli_connect($host, $user, $pwd)or die("Error connecting to database.");
mysqli_select_db($conn, $db) or die("Couldn't select the database.");
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = mysqli_stmt_init($conn);
$query = "SELECT * FROM Users WHERE email=? AND password=?";
mysqli_stmt_prepare($stmt, $query) or die("Failed to prepare statement.");
mysqli_stmt_bind_param($stmt, "ss", $username, $password);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$count = mysqli_num_rows($result);
if($count == 1){
//Log in successful
}
else {
//Wrong Username or Password
}
mysqli_close($conn);
?>
mysqli_stmt_get_result is available in PHP 5.3, but I am running 5.1. Also, the mysqlnd driver must be installed for this call to work.
For more information, see Call to undefined method mysqli_stmt::get_result

Categories