This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(2 answers)
Closed 3 years ago.
After submitting something through my form I get the welcome part and then the mysql connection error because mysql is off, it goes away when I turn it on and then the boolean error. "Warning: mysqli_query() expects parameter 1 to be mysqli, boolean given in C:\xampp\htdocs\welcome.php on line 25"
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?><br>
Your password is <?php echo $_POST["password"]; ?><br>
You have purchased the <?php echo $_POST["sub_type"]; ?>
<?php
$mysqli_host = "localhost";
$mysql_username = "root";
$mysql_password = "123";
$site_db = "test";
$info_name = $_POST["name"];
$info_pass = $_POST["password"];
$info_email = $_POST["password"];
$sub_type = $_POST["sub_type"];
$con=mysqli_connect($mysqli_host,$mysql_username,$mysql_password,$site_db);
// Checks connection to twitch webpanel database and inserts registreation info
if (mysqli_connect_errno());
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO Users (Username, Password, Email, Subcription)
VALUES ('$info_name', '$info_pass', '$info_email', '$sub_type')");
?>
</body>
</html>
Most probably, you have a connection error in mysqli_connect. Wrong credentials or MySQL is down.
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
//you need to exit the script, if there is an error
exit();
}
if (mysqli_connect_errno());
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit(); // **this is missing**
}
mysqli_query($con,"INSERT INTO Users (Username, Password, Email, Subcription)
VALUES ('$info_name', '$info_pass', '$info_email', '$sub_type')");
Here is your bug:
if (mysqli_connect_errno());
There should be no semicolon on the end.
Also according to the documentation you should be using this to check for connection errors:
if (mysqli_connect_error())
But as I said in a comment, I recommend using PDO instead of mysqli. And make sure you properly escape values inserted into the database and encrypt the password with pbkdf2 or scrypt.
Related
This question already has answers here:
Fatal error: Call to undefined function mysqli_connect() in... while connecting PHP 5.4.22 and MySQL 5.5 with Apache 2.4.7
(5 answers)
Closed 3 years ago.
I am writing a simple registration code. I want to save username and password in db.
While running the page of registration.php on localhost I got this error.
Fatal error: Uncaught Error: Call to undefined function mysqli_connect() in C:\Users\Ammad Hassan\www\db.php:4 Stack trace: #0 C:\Users\Ammad Hassan\www\registration.php(10): require() #1 {main} thrown in C:\Users\Ammad Hassan\www\db.php on line 4
db.php is shown below
<?php
// Enter your Host, username, password, database below.
$con = mysqli_connect("localhost","root","","register");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Registration.php
<?php
require('db.php');
// If form submitted, insert values into the database.
if (isset($_REQUEST['username'])){
// removes backslashes
$username = stripslashes($_REQUEST['username']);
//escapes special characters in a string
$username = mysqli_real_escape_string($con,$username);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
$query = "INSERT into `users` (username, password)
VALUES ('$username', '".md5($password)."')";
$result = mysqli_query($con,$query);
if($result){
echo "<div class='form'>
<h3>You are registered successfully.</h3>
<br/>Click here to <a href='login.php'>Login</a></div>";
}
}else{
?>
I want to run this page so that I can enter in the form.
Check if mysqli library is enabled in your php.ini.
Also consider using PDO instead, it is better and not tied to MySQL.
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);
}
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Reference - What does this error mean in PHP?
(38 answers)
Closed 4 years ago.
as stated in my username, desperately need help so sorry if its a duplicate post!
I'm trying to do up a login page that redirects me to my home page if authentication fails so my input will cross check with the database(mysql) then output either successful or error. but the result always show error. im pretty sure that it didnt went into my 1st if checking statement.
As shown below is my code:
<?php
$servername = "localhost";
$username = "read";
$password = "projecttest";
$dbname = "test-member";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$password1 = $_POST["password"];
$username1 = $_POST["username"];
$chkpassword = " SELECT password FROM member WHERE password = $password1 ";
$chkusername = " SELECT username FROM member WHERE username = $username1";
if ($conn->query($chkpassword) == TRUE ) {
echo "successful log in"
?>
<INPUT TYPE="hidden" NAME="redirect"
VALUE="http://localhost/IPproject_test1/home.php">
<?php
}
else if ($conn->query($chkpassword) == FALSE ) {
echo "error";
}
$conn->close();
?>
The issue is your query.
Let's assume the user enters as password asdf1234. Your query would look like this:
SELECT password FROM member WHERE password = asdf1234
That will fail because MySQL thinks asdf1234 is a column. If you escape the string, it should work.
$chkpassword = "SELECT password FROM member WHERE password = '{$password}'"
So the query looks like this:
SELECT password FROM member WHERE password = 'asdf1234'
I still wouldn't check on == TRUE tho, but on !== null
This question already has answers here:
How can I get useful error messages in PHP?
(41 answers)
Closed 7 years ago.
I'm trying to prevent SQL injection using PDO, but I can't seem to connect. This is the working version - not SQL injection safe:
<html>
<head>
<title>Insert data into database</title>
</head>
<body>
<?php
session_start();
$_SESSION['name'] = $_POST['name'];
// Connect to database server
mysql_connect("localhost", "********", "********") or die(mysql_error());
// Select database
mysql_select_db("mydatabase") or die(mysql_error());
// The SQL statement is built
$strSQL = "INSERT INTO mytable(name) VALUES('" . $_POST["name"] . "')";
// The SQL statement is executed
mysql_query($strSQL) or die (mysql_error());
// Close the database connection
mysql_close();
echo "Your name is " . $_POST["name"] ;
?>
</body>
</html>
This is working just fine. I read these pages on how to use PDO to protect against SQL injection attacks:
http://www.w3schools.com/php/php_mysql_connect.asp
http://www.w3schools.com/sql/sql_injection.asp
and wrote the following code following the guideline:
<html>
<head>
<title>Insert data into database</title>
</head>
<body>
<?php
session_start();
$_SESSION['name'] = $_POST['name'];
$servername = "localhost";
$username = "********";
$password = "********";
try {
$conn = new PDO("mysql:host=$servername, dbname=mydatabase", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
echo "You have connected to the database server with PDO"
// The SQL statement is built
$stmt = $dbh->prepare("INSERT INTO mytable (name)
VALUES (:name)");
$stmt->bindParam(':name', $_POST['name']);
$stmt->execute();
// Close the database connection
mysql_close();
echo "Your name is " . $_POST["name"] ;
?>
</body>
</html>
But this code just gives me a blank page - no error message and nothing inserted into the database.
I also tried doing the connection as described in
http://www.stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php
but the result was the same - a blank page without error messages.
What am I doing wrong?
You're using the wrong variable for $stmt = $dbh->prepare
which should be $conn and not $dbh as per your connection.
Having used error reporting, would have signabled an undefined variable dbh notice/warning.
You also can't use mysql_close(); with PDO as you are mixing APIs, which you can't do.
See Example #3 Closing a connection of "Connections and Connection" in the manual http://php.net/manual/en/pdo.connections.php
Another thing session_start(); is best to be above anything. You may be outputting before header.
Edit: You forgot a semi-colon in this line:
echo "You have connected to the database server with PDO"
which should read as
echo "You have connected to the database server with PDO";
which will break your code.
Error reporting would also have caught that syntax/parse error.
http://php.net/manual/en/function.error-reporting.php
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
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...