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.
Related
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
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();
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.
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
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);