"Notice: Undefined variable" in PHP. How can I fix it? [duplicate] - php

This question already has answers here:
mysqli_prepare() expects parameter 1 to be mysqli
(3 answers)
Closed 1 year ago.
I have a registration form here. I am a dummy in PHP (this is PHP for an Android app). It worked, but I found that I can register with the same username and email, so I added functions to check the database for the same username and prevent that, as I am dummy, I get this error when trying to register -
Notice: Undefined variable: con in /storage/ssd1/448/5907448/public_html/Register.php on line 27
Warning: mysqli_prepare() expects parameter 1 to be mysqli, null given in /storage/ssd1/448/5907448/public_html/Register.php on line 27
Warning: mysqli_stmt_bind_param() expects parameter 1 to be mysqli_stmt, null given in /storage/ssd1/448/5907448/public_html/Register.php on line 28
Warning: mysqli_stmt_execute() expects parameter 1 to be mysqli_stmt, null given in /storage/ssd1/448/5907448/public_html/Register.php on line 29
{"success":true}
My PHP code
<?php
$response = array();
if (!isset($_POST["username"], $_POST["email"], $_POST["password"])) {
$response['success'] = false;
$response['Error'] = "No needed data";
echo json_encode($response);
exit(0);
}
ob_start();
$con = mysqli_connect("host", "username", "password", "database");
ob_end_clean();
if (!$con) {
$response['success'] = false;
$response['Error'] = "Error Connecting" . PHP_EOL;
$response['Error'] .= "Error Code: " . mysqli_connect_errno() . PHP_EOL;
$response['Error'] .= "Error: " . mysqli_connect_error() . PHP_EOL;
echo json_encode($response);
exit(0);
}
function registerUser() {
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO user (username, email, password) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement, "sss", $username, $email, $password);
mysqli_stmt_execute($statement);
}
function usernameAvailable() {
global $con, $username;
$statement = mysqli_prepare($con, "SELECT * FROM user WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
$count = mysqli_stmt_num_rows($statement);
mysqli_stmt_close($statement);
if ($count < 1){
return true;
}
else {
return false;
}
}
$response["success"] = false;
if (usernameAvailable()){
registerUser();
$response["success"] = true;
}
echo json_encode($response);
?>
PS: Connection data changed to default.

Add your variable $con to the parameters of your functions that need access to the database i.e. registerUser() and usernameAvailable()

You referenced a global, $con, and it’s returning undefined. Ensure that it has a value by debugging it using print_r or other alternatives. Due to it returning undefined no functions are running.
Although it is bad practise to reference a global variable, I would recommend either setting up a function that returns the $con variable or passing it.
function returnCon(){
$con = mysqli_connect("host", "username", "password", "database");
return $con
}
You can then use
$con = returnCon();

Related

Warning: mysqli_stmt_init() expects parameter 1 to be mysqli, null given [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 2 years ago.
I'm making a chat feature for a site and am not good with PHP:
<?php
if (isset($_POST['send'])) {
require 'database.php';
$input = $_POST['input'];
} else {
$sql = "INSERT INTO chatsys (chat) VALUES (?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("index.html?error=sqlerror");
exit();
} else {
mysqli_stmt_bind_param($stmt, "sss", $input);
mysqli_stmt_execute($stmt);
header("index.html?request=success");
exit();
}
}
{
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
And database code:
<?php
$servername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "chatsys";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
?>
This results in:
Notice: Undefined variable: conn in C:\Users\John Doe\Desktop\server\htdocs\php\message\chat.php on line 11
Warning: mysqli_stmt_init() expects parameter 1 to be mysqli, null given in C:\Users\John Doe\Desktop\server\htdocs\php\message\chat.php on line 11
Warning: mysqli_stmt_prepare() expects parameter 1 to be mysqli_stmt, null given in C:\Users\john doe\Desktop\server\htdocs\php\message\chat.php on line 12
What have I done wrong?
First of all, don't blame PHP because it is a powerful and easy to use server side language, try to get close and you will love it.
Second you have unneccessary if else, and also passing extra parameters to bind param, while you just have only one to pass.
<?php
if (isset($_POST['send'])) {
require 'database.php';
$input = $_POST['input'];
$sql = "INSERT INTO chatsys (chat) VALUES (?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("index.html?error=sqlerror");
exit();
}
//No need to else here because if error happens you get back and exit.
mysqli_stmt_bind_param($stmt, "s", $input);
mysqli_stmt_execute($stmt);
header("index.html?request=success");
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
You are overcomplicating your code. You do not need all these braces or if statements. You do not need to check the return value of mysqli calls if you enable error reporting.
<?php
// If value was posted to the server
if (isset($_POST['send'])) {
// include mysqli connection
require 'database.php';
// perform prepared statement. (prepare/bind/execute)
$stmt = $conn->prepare("INSERT INTO chatsys (chat) VALUES (?)");
$stmt->bind_param("sss", $_POST['input']);
$stmt->execute();
// redirect on success
header("index.html?request=success");
exit();
}
and your connection file:
<?php
$servername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "chatsys";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);
$conn->set_charset('utf8mb4'); // always set the charset

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.

g: mysql_query(): supplied argument is not a valid MySQL-Link resource [duplicate]

This question already has an answer here:
"Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource"
(1 answer)
Closed 7 years ago.
Here is my connect.php
class DB_class {
protected function dblogin() {
if(!defined('DB_CONNECTED')) {
$DB = 'mydb';
$USER='myuser';
$PASS='mypass';
$HOST='localhost';
//$link = #mysql_pconnect($HOST,$USER,$PASS) or die("DB connect error");
$link=#mysql_connect($HOST,$USER,$PASS) or die("DB connect error");
mysql_select_db($DB, $link);
mysql_query("SET NAMES 'utf8'");
return $link;
}
}
function dbclose() {
mysql_close();
}
function dbfree($result) {
mysql_free_result($result);
}
}
and here is my insert.php code
require('connect.php');
$name = $_POST['FIRSTNAME'];
$name2 = $_POST['SURNAME'];
$email = $_POST['EMAIL'];
$phone = $_POST['PHONE'];
$mailing_list = $_POST['MAILING_LIST'];
$enquiryMessage = $_POST['MESSAGE'];
$DB = new DB_class();
$link = $DB->dblogin();
$sql = "INSERT INTO user (DATE_REG, FIRSTNAME, SURNAME, NICK, EMAIL, ACCESS,user.GROUP ,MAILING_LIST)
VALUES ('".date('Y-m-d H:i:s')."', '$name', '$name2', '$email', '$email', 0, 4, '$mailing_list')";
// $query = mysql_query($conn, $sql, MYSQLI_USE_RESULT);
var_dump(mysql_query($sql,$link));
I'm getting error "g: mysql_query(): supplied argument is not a valid MySQL-Link resource".
Thanks for help in advance.
First of all, you're using an extension that is deprecated from php 5.5.0.
The correct way to create a connection is by using MySQLi
An example above all:
<?php
$mysqli_port = ini_get("mysqli.default_port");
$mysqli_socket = ini_get("mysqli.default_socket");
$dbConn = new mysqli($dbHost, $dbUser, $dbPwd, $dbName, $mysqli_port, $mysqli_socket);
if(mysqli_connect_error())
{
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
}
Anyway, the method dblogin you declared in your class has not to be declared as protected, because it returns a fatal error. Remove protected from within you function declaration to make it work.

PHP: Errors in my code, mainly mysqli_fetch_assoc() expects parameter mysqli_result, object given [duplicate]

This question already has answers here:
mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement
(2 answers)
Closed 1 year ago.
Can somebody help me fix my code?
I am trying to access a database of password hashes and use them to validate the user login, but I get a couple of errors.
<?php
$servername="localhost";
$username = "*****";
$password = "*******";
$dbname = "*****";
$conn = new mysqli($servername,$username,$password,$dbname);
if($conn->connect_error){
die("Connection to database failed: ".$conn->connect_error);
}
$uname=mysqli_real_escape_string($conn, $_POST['entered_username']);
$pw=mysqli_real_escape_string($conn, $_POST['entered_password']);
$stmt=$conn->prepare("SELECT username,password,password_hash FROM users WHERE username=?");
$stmt->bind_param('s',$uname);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($result);
$stmt->fetch();
if(!$stmt){
echo $conn->connect_error();}
if($stmt){
echo 'Connection successful';}
$found=FALSE;
while($row=mysqli_fetch_assoc($stmt))
{
if($password_verify($pw,$row['password_hash'])) {
$found=TRUE;
}
}
if($found){
echo "You have successfully logged in as ".$uname."!";
}
else {
echo "Login as ".$uname." failed!";
}
$stmt->close();
$conn->close();
?>
What I get as output:
Warning: mysqli_stmt::bind_result(): Number of bind variables doesn't
match number of fields in prepared statement in
/****/login3.php on line 27
Connection successful
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result,
object given in /****/login3.php on line 37
Login as admin failed!
Thanks guys! It works now! I changed the bind_result statement and got rid of the fetch statement. Apparently, $stmt is of type mysqli_stmt, not mysqli_result and the mysqli_stmt class doesn't have a method fetch_assoc() defined for it.
$stmt=$conn->prepare("SELECT username,password_hash FROM users WHERE username=?");
$stmt->bind_param('s',$uname);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($user,$password_hash);
$found=FALSE;
while($stmt->fetch())
{
if(password_verify($pw,$password_hash)) {
$found=TRUE;
}
}
You are mixing it up. Try with -
$stmt=$conn->prepare("SELECT username,password,password_hash FROM users WHERE username=?");
$stmt->bind_param('s',$uname);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($result);
if(!$stmt){
echo $conn->connect_error();}
if($stmt){
echo 'Connection successful';}
$found=FALSE;
while($row=$stmt->fetch_assoc();)
{
if($password_verify($pw,$row['password_hash'])) {
$found=TRUE;
}
}
you have to bind the columns, as it has to match number of fields requiring:
check this out:
<?php
$servername="localhost";
$username = "*****";
$password = "*******";
$dbname = "*****";
$conn = new mysqli($servername,$username,$password,$dbname);
if($conn->connect_error){
die("Connection to database failed: ".$conn->connect_error);
}
$uname=mysqli_real_escape_string($conn, $_POST['entered_username']);
$pw=mysqli_real_escape_string($conn, $_POST['entered_password']);
$stmt=$conn->prepare("SELECT username,password,password_hash FROM users WHERE username=?");
$stmt->bind_param('s',$uname);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($username,$password,$password_hash);
$stmt->fetch();
if(!$stmt){
echo $conn->connect_error();}
if($stmt){
echo 'Connection successful';}
$found=FALSE;
while($row=mysqli_fetch_assoc($stmt))
{
if($password_verify($pw,$password_hash)) {
$found=TRUE;
}
}
if($found){
echo "You have successfully logged in as ".$uname."!";
}
else {
echo "Login as ".$uname." failed!";
}
$stmt->close();
$conn->close();
?>

Why am i getting a fatal error? [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 9 years ago.
Here is the snippet of code that is causing the error.
public function storeUser($email, $password) {
require_once 'include/user.config.inc.php';
$uuid = uniqid('', true);
//echo $uuid;
$hash = $this->hashSSHA($password);
//echo $hash;
$encrypted_password = $hash["encrypted"]; // encrypted password
//echo $encrypted_password;
$salt = $hash["salt"]; // salt
//echo $salt;
$query = "INSERT INTO user_table (unique_id, email_id, encrypted_password, salt, created_at) VALUES ( :uuid, :email, :encrypted_password, :salt, NOW()) ";
$query_params = array(
':uuid' => $uuid,
':email' => $email,
':encrypted_password' => $encrypted_password,
':salt' => $salt
);
try {
//These two statements run the query against the database table.
$stmt = $db -> prepare($query);
$result = $stmt -> execute($query_params);
} catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error! Problem with first query!";
die(json_encode($response));
}
}
I am getting an error:
Notice: Undefined variable: db
Fatal error: Call to a member function prepare() on a non-object
It seems that $query and $query_params is causing the problem but I don't know why. It seems right to me.
Here's the other snippet of code
if ($db->isUserExisted($email)) {
// user is already existed - error response
$response["error"] = 2;
$response["error_msg"] = "User already exist";
echo json_encode($response);
} else {
$db->storeUser($email, $password);
}
Taking a guess here...
require_once only includes the file once, ever*. You have probably required that file before elsewhere, it's not getting loaded again, your $db variable is nowhere to be found.
* In the current script execution.
You never initialize your $db object.
You need something like the following before "$stmt = $db -> prepare($query);"
$db = new mydbclass();

Categories