mysqli_query() expects parameter 1 to be mysqli, boolean given [duplicate] - php

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
How do I display a MySQL error in PHP for a long query that depends on the user input? [duplicate]
(6 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 4 years ago.
Hey can you guys help me with this because I can't figure it out here are the errors.
[04-Nov-2018 15:21:52 UTC] PHP Warning: mysqli_connect(): (HY000/1045):
Access denied for user 'freeload_retain'#'vps28004.inmotionhosting.com'
(using password: NO) in /home/freeloadboard/public_html/insert.php on
line 7
[04-Nov-2018 15:21:52 UTC] PHP Warning: mysqli_select_db() expects
parameter 1
to be mysqli, boolean given in /home/freeloadboard/public_html/insert.php
on line 21
[04-Nov-2018 15:21:52 UTC] PHP Warning: mysqli_query() expects parameter
1 to be mysqli, boolean given in
/home/freeloadboard/public_html/insert.php on line 45
Program:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$con = mysqli_connect('##.##.###.##','freeload_retain','');
if(!$con)
{
echo "Not Connected to Server. ";
}
if(!mysqli_select_db($con, 'freeload_retain'))
{
echo "Database Not Selected. ";
}
$Companyname = $_POST['companyname'];
$Username = $_POST['username'];
$Password = $_POST['password'];
$Email = $_POST['email'];
$sql = "INSERT INTO clients (companyname, username, password, email)
VALUES ('$Companyname', '$Username', '$Password', '$Email')";
if(!mysqli_query($con, $sql))
{
echo "Not Inserted. ";
}
else
{
echo "Inserted. ";
}
?>
Hope you guys find out the answer soon!
Also I'm reusing this question because I can't wait another day to make another question but thanks for helping me out!

To answer your question: It's not working because you're wrapping the column names in brackets, remove these and it should work. You also have a typo. ($comapnyname = $_POST['companyname'];), should be $companyname.
However, there's a few other, bigger issues with your code. You're using the mysql functions, which are deprecated and completely removed from PHP7.
Next to that, you should use prepared statements and bind_param to prevent SQL injections, escaping strings will not accomplish this.
This what it would look like using prepared statements.
// ... Set your database connection variables
/*
* Create the database connection, notice the
* usage of mysqli instead of mysql
*/
$connect = new mysqli($host, $user, $password, $database);
/*
* The query, notice the usage of a question mark
* on the place of the variables to be inserted
*/
$sql = "INSERT INTO client (cname, tname, pname, ename) VALUES (?, ?, ?, ?)";
// Prepare the query using $connect->prepare()
$stmt = $connect->prepare($sql);
// Check if the query was prepared
if(!$stmt) {
// ... Handle your error
}
// Get $_POST variables
$companyname = $_POST['companyname'];
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if(!$stmt->bind_param('ssss', $companyname, $username, $password, $email)) {
// ... Handle your error
}
if(!$stmt->execute()) {
// ... Handle your error
} else {
echo 'Record inserted.';
}
It also seems that you're inserting the passwords into your database as clear-text, this is a big issue. You should hash them. Write two functions, one to hash the password and one to verify it when users log in.
The first function will return the password hash and the second one will return TRUE or FALSE if the password is correct or incorrect.
function hashPassword($password) {
return password_hash($password, PASSWORD_DEFAULT);
}
function verifyPassword($password, $hash) {
return password_verify($password, $hash);
}

Related

mysqli_query(): MySQL server has gone away [duplicate]

This question already has answers here:
MySQL error 2006: mysql server has gone away
(32 answers)
Closed 4 years ago.
I'm getting these errors:
Warning: mysqli_query(): MySQL server has gone away in (local db)
Warning: mysqli_query(): Error reading result set's header in (local db)
I am establishing a connection at first:
$connection = new mysqli($server, $user, $pass, $db) or die("unable");
Then this:
$sql = $connection->prepare("INSERT INTO comments (name,mail,homepage,comment,time) VALUES (?,?,?,?,?)");
$sql->bind_Param('sssss',$name,$mail,$homepage,$comment,$time);
$sql->execute();
if($sql){
if(!addPics($connection, $image_content, $mime, $time)){
//other code
}
addPics looks like this:
function addPics($connection, $image_content, $mime, $time){
$sql = $connection->prepare("INSERT INTO pictures (picture, mime, time) VALUES (?,?,?)");
$sql->bind_Param('sss',$image_content,$mime, $time);
$sql->execute();
if($sql){
return true;
} else {
return false;
}
Error occurs at the second sql->execute. My guess is that it's because I'm using the connection for several requests but my knowledge of PHP does not allow me to figure out a solution.
Thank you!
To demonstrate my comments
It would be wise to use backticks around certain column names ( or all ) if they have special meaning within SQL - such as name or time
$sql = $connection->prepare("INSERT INTO comments (`name`,`mail`,`homepage`,`comment`,`time`) VALUES (?,?,?,?,?)");
$sql->bind_Param('sssss',$name,$mail,$homepage,$comment,$time);
/* assign a variable to the `execute` method and test that var */
$result = $sql->execute();
if( $result ){
/* the statement is now finished with, close it */
$sql->close();
if(!addPics($connection, $image_content, $mime, $time)){
//other code
}

PHP MySQL Update Query Failing [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 6 years ago.
I'm trying to execute the following query to update a record in a table.
require "conn.php";
$user_name = $_POST["username"];
$code = $_POST["code"];
$name = $_POST["groupname"];
echo "$user_name, $code, $name";
$sql_update = "UPDATE users SET group = '$name' WHERE username = '$user_name'";
if ($conn->query($sql_update) === TRUE) {
echo "success";
}
else {
echo "fail";
}
The query fails and I'm not sure why. The connection is made and I'm able to echo the username code and name. Is there a reason why it's not working?
Your code is not secure
Look at this code with prepared statements
require_once("conn.php");
$user_name = $conn->real_escape_string($_POST["username"]);
$code = $conn->real_escape_string($_POST["code"]);
$name = $conn->real_escape_string($_POST["groupname"]);
$sql_update = $conn->prepare("update `users` set `group` = ? where `username` = ?");
$sql_update->bind_param("ss",$name,$user_name);
$sql_update->execute();
$sql_update->close();
$conn->close();
And conn.php file should be like this
$config = parse_ini_file('config.ini'); // Connection infos.
$conn = mysqli_connect('localhost',$config['username'],$config['password'],$config['db_name']);
if($conn === false) {
die("Something was wrong ! Please try again later."); // Error if connection not ok.
}
$conn->set_charset("utf8");
Create file outside the public_html folder named config.ini to write connection data
[db_connection]
username = username
password = password
db_name = dbname
This function binds the parameters to the SQL query and tells the database what the parameters are. The "sss" argument lists the types of data that the parameters are. The s character tells mysql that the parameter is a string.
The argument may be one of four types:
i - integer
d - double
s - string
b - BLOB
Learn more here

password_hash giving error: Strict standards: Only variables should be passed by reference [duplicate]

This question already has answers here:
What is the difference between bindParam and bindValue?
(7 answers)
Closed 6 years ago.
Edit: My issue has been resolved. I did not know or think of bindValue(), that is why I do not think this is a duplicate question. Thanks for the help!
I am learning how to register users with PHP and it seems like password_hash is giving me the "Only Variables should be passed by reference" error message. I've seen many people with the same error, but it does not seem to apply to my case (in my opinion).
connecting to database
$server = 'localhost';
$username ='root';
$password ='root';
$database = 'register_test';
try{
$conn = new PDO("mysql:host=$server;dbname=$database;" , $username, $password);
} catch(PDOException $e){
die ("Connection failed" . $e->getMessage());
}
Registering user
require 'database.php';
if(!empty($_POST['email']) && !empty($_POST['password'])):
$pass = $_POST['password'];
$email = $_POST['email'];
$sql = "Insert into user (email, password) values (:email, :password)";
$stmt = $conn->prepare($sql);
$stmt ->bindParam(':email', $email);
$stmt ->bindParam(':password', password_hash($pass, PASSWORD_BCRYPT)); //error showns here
if($stmt -> execute() ):
die('Success');
else:
die('Fail');
endif;
endif;
If you guys need more information please let me know.
Use PDOStatement::bindValue() instead of PDOStatement::bindParam().
From the docs:
Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.
So, your code becomes:
$stmt->bindValue(':email', $email);
$stmt->bindValue(':password', password_hash($pass, PASSWORD_BCRYPT));
The result of a function cannot be passed by reference when E_STRICT mode is enabled, without triggering a warning. By using bindValue() instead, we pass the return value of the function as a copy, basically.

How do I check if a user already exists in an SQL database? [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
I am trying to test a simple user account registration page for a project for class, and I am trying to create a check that will notify the user if their email is already in the database, and therefore will not add them to it again. Here's my PHP code.
<?php
$collegeid = mysql_real_escape_string('1');
$email = mysql_real_escape_string('abc#test.com');
$password = mysql_real_escape_string(md5('test1'));
$name = mysql_real_escape_string('Test Test');
$bday = mysql_real_escape_string('1900-01-01');
$class = mysql_real_escape_string('Freshman');
//echo "<p>Test</p>";
$servername = "localhost";
$username = redacted;
$serverpassword = redacted;
$dbname = redacted;
$conn = new mysqli($servername, $username, $serverpassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$checkquery = "SELECT * FROM Student WHERE Email = '$email'";
$insertquery = "INSERT INTO Student (CollegeID, Name, Birthday, Email, Classification, Password) VALUES ('$collegeid', '$name', '$bday', '$email', '$class', '$password')";
if (mysql_num_rows($conn->query($checkquery)) > 0)
{
echo "Error: Email already in use";
}
else
{
$conn->query($insertquery);
echo "Account Created.";
}
?>
However, it always tells me the account is created, regardless of whether or not that user is in the database.
You are mixing mysql and mysqli functions. You should not use mysql functions as they are deprecated and you seem to be using mysqli for almost everything except escaping your values and checking the number of found rows.
The problem is caused by your use of mysql_real_escape_string. When no mysql_* database connection is found, that returns false which is the equivalent of an empty string so you are checking for empty values in your database and everytime you don't find that, you add a new row.
To secure yourself against sql injection on mysqli, you should switch to prepared statements instead of using mysqli_real_escape_string.
Edit: It is also mysql_num_rows that is returning false in case of an error...

Warning: mysql_fetch_assoc() expects parameter 1 to be resource, object given [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
warning:mysql_fetch_array() expects parameter 1 to be resource, object given [duplicate]
(3 answers)
Closed last year.
I cant seem to figure out what I'am doing wrong. So when I submit my form I get Warning error and the
Notice: Undefined variable: dbusername in /Library/WebServer/Documents/ArturoLuna_Final/loginCheck.php on line 30
$username = $_POST['username'];
$password = $_POST['password'];
if($username&&$password)
{
require 'conn.php';
$query = "SELECT * FROM users WHERE username='$username'";
$result = $mysql->query($query) or die(mysqli_error($mysql));
$numrows = $result->num_rows;
if ($numrows!=0)
{
while($row = mysql_fetch_assoc($result))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
//check to see if they match!
if($username==$dbusername&&$password==$dbpassword)
{
echo "youre In!";
}
else
echo "incorrect password!";
}
else
die("that user is dead");
//echo $numrows;
}
else
echo ("Please Enter Username")
what can I be possibly doing wrong?
Change
while($row = mysql_fetch_assoc($result))
to
while($row = $result->fetch_assoc())
You missed an i off the function name, and mixed up OO and procedural style code, so you are mixing up mysql_* result resources and mysqli_result objects.
You're mixing traditional PHP MySQL functions mysql_* with the MySQLi interface. In this case, mysql_fetch_assoc() expects a resource handle created with mysql_query().
To retrieve the correct result, you'll need to use MySQLi's method:
$row = $result->fetch_assoc();
And while you're at it, you might want to consider making the code less susceptible to MySQL injection. Properly escape any user provided input before interpolating it into a query string, or better yet, use MySQLi parameter binding facilities.

Categories