PHP | SQL - mysqli_stmt_prepare fails and connected to the database - php

I'm trying to execute a parameterized query to update some stuff in the database.
The problem is that it mysqli_stmt_prepare fails.
The require is used to connect to the database.
require 'includes/dbInclude.php';
if ($codeQuery > 0){
$confirmationUsername = $_GET['confirmationUsername'];
$active = "active";
$noCode = "";
$insertSql = "UPDATE users SET accountStatus = ? WHERE username = $confirmationUsername";
$insertSql2 = "UPDATE users SET confirmationCode = ? WHERE username = $confirmationUsername";
$statement = mysqli_stmt_init($connection);
$statement2 = mysqli_stmt_init($connection);
if (!mysqli_stmt_prepare($statement, $insertSql)){
header("Location: registerComplete.php?error=sqlError1");
exit();
}
elseif (!mysqli_stmt_prepare($statement2, $insertSql2)){
header("Location: registerComplete.php?error=sqlError2");
exit();
}
else{
mysqli_stmt_bind_param($statement, "s", $active);
mysqli_stmt_execute($statement);
mysqli_stmt_bind_param($statement2, "s", $noCode);
mysqli_stmt_execute($statement2);
}
}
dbInclude.php contains:
<?php
//connection variables
$serverName = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "ecglive";
//connection
$connection = mysqli_connect($serverName, $dbUsername, $dbPassword, $dbName);
//connection error
if(!$connection){
die("There was an error connceting to the database: " . mysqli_connect_error());
}
And where I used it works. I alos tried copy that code to this one just to see if there was any problem connecting to the database. It isn't.
It always goes on the first error if, where it says sqlError1 and if I delete it, then it goes to the sqlError2.
Did I make any mistake?

You need to bind the username in addition to the accountstatus to help mitigate SQL injection.
require 'includes/dbInclude.php';
if ($codeQuery > 0){
$confirmationUsername = $_GET['confirmationUsername'];
$active = "active";
$noCode = "";
$insertSql = "UPDATE users SET accountStatus = ? WHERE username = ?";
$insertSql2 = "UPDATE users SET confirmationCode = ? WHERE username = ?";
$statement = mysqli_stmt_init($connection);
$statement2 = mysqli_stmt_init($connection);
if (!mysqli_stmt_prepare($statement, $insertSql)){
exit(header("Location: registerComplete.php?error=sqlError1") );
} elseif (!mysqli_stmt_prepare($statement2, $insertSql2)){
exit(header("Location: registerComplete.php?error=sqlError2") );
} else{
mysqli_stmt_bind_param($statement, "ss", $active,$confirmationUsername);
mysqli_stmt_execute($statement);
mysqli_stmt_bind_param($statement2, "ss", $noCode,$confirmationUsername);
mysqli_stmt_execute($statement2);
}
}

This code uses a very strange style, and one that's far more verbose than necessary. Here's a more minimal form of same:
require 'includes/dbInclude.php';
// Enable exception reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
if ($codeQuery > 0) {
try {
// Prepare one query that sets both properties.
$stmt = $connection->prepare('UPDATE users SET accountStatus=?,confirmationCode=? WHERE username=?');
// Bind parameters directly form the source, no variables needed.
$stmt->bind_param('ss', 'active', '', $_GET['confirmationUsername']);
// Attempt to execute
$stmt->execute();
}
catch (Exception $e) {
// Error handling here...
header("Location: registerComplete.php?error=sqlError2");
exit();
}
}
You're really not doing a lot here, so there's no reason for that code to be so verbose.
That being said, if this is a registration system for some kind of user access control layer and this isn't an academic project you should stop working on this code before you create a huge mess. Writing your own access control layer is not easy and there are many opportunities to get it severely wrong.
Any modern development framework like Laravel comes with a robust authentication system built-in. This is a solved problem and there's no need for you to try and re-invent the wheel here.
At the absolute least follow recommended security best practices and never store passwords as plain-text or a weak hash like SHA1 or MD5.

Related

Query is TRUE when its not

Please be gentle with me i have just recently trying to learn PHP/SQL.
The problem is that the first query is ALWAYS TRUE when it shouldn't (base on what i know).
The query simply state to get the 'username' where betakey=$betakey provided by user. The fact that my datebase columns is still empty except column betakey doesn't make that query statement true at all.
Please help, maybe i am missing some knowledge on this.
<?php
header('Access-Control-Allow-Origin: *');
$firstName = $_GET['rfirstname'];
$lastName = $_GET['rlastname'];
$username = $_GET['rusername'];
$password = $_GET['rpass'];
$betakey = $_GET['rkey'];
$host="localhost"; // Host name
$db_username="**"; // Mysql username
$db_password="**"; // Mysql password
$db_name="**"; // Database name
$conn = mysqli_connect("$host", "$db_username", "$db_password","$db_name");
if (!$conn){
die ("Error: ".mysqli_connect_error());
}
$query1 = "SELECT username='$username' FROM users2 WHERE betakey='$betakey';";
$result_1 = mysqli_query($conn,$query1);
if(mysqli_num_rows($result_1) > 0){
echo 'Beta key is used';
}else{
$query2 = "UPDATE users2 SET firstName='$firstName',lastName='$lastName',username='$username',password='$password' WHERE betakey='$betakey'";
echo 'Registration Successful';
}
mysqli_close($conn);//Close off the MySQL connection to save resources.
?>
You have plenty of problems in your code. Let me help you fix some of them
You should learn how to properly open mysqli connection. You need to enable error reporting and set the correct charset.
You should never concatenate PHP variables into SQL query. Always use parameterized prepared statements instead of manually building your queries.
Your first SQL query has an error. username='$username' is meaningless and wrong. If all you want to do is check existence use COUNT(1) or something similar.
Here is my take on your fixed code:
<?php
header('Access-Control-Allow-Origin: *');
$firstName = $_GET['rfirstname'];
$lastName = $_GET['rlastname'];
$username = $_GET['rusername'];
$password = $_GET['rpass'];
$betakey = $_GET['rkey'];
$host = "localhost"; // Host name
$db_username = "**"; // Mysql username
$db_password = "**"; // Mysql password
$db_name = "**"; // Database name
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($host, $db_username, $db_password, $db_name);
$conn->set_charset('utf8mb4');
$stmt = $conn->prepare("SELECT COUNT(username) FROM users2 WHERE betakey=?");
$stmt->bind_param('s', $_GET['rusername']);
$stmt->execute();
$result_1 = $stmt->get_result();
$used = $result_1->fetch_row()[0];
if ($used) {
echo 'Beta key is used';
} else {
$stmt = $conn->prepare("UPDATE users2 SET firstName=?, lastName=?, username=?, password=? WHERE betakey=?");
$stmt->bind_param('sssss', $firstName, $lastName, $username, $password, $betakey);
$stmt->execute();
echo 'Registration Successful';
}

PDO Username validation if already exists

I have a problem with register form.My form works properly but whenever i try to insert username that already exists it doesn't shows any error.
here is my php register file:
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=dblogin", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_POST['submit'])) {
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$user_pass = $_POST['user_pass'];
$hash = password_hash($user_pass, PASSWORD_DEFAULT);
$stmt = $con->prepare("SELECT user_name FROM users WHERE user_name = :user_name");
if($stmt->rowCount() > 0){
echo "exists!";
}
else{
$insert = $conn->prepare("INSERT INTO users (user_name,user_email,user_pass) values(:user_name,:user_email,:user_pass)");
$insert->bindparam(':user_name',$user_name);
$insert->bindparam(':user_email',$user_email);
$insert->bindparam(':user_pass',$hash);
$insert->execute();
}
}
catch(PDOException $e)
{
echo "connection failed";
}
?>
Thanks for your support
You are not executing the select statement. You need to bind params and execute the select statement, try this after the select statemnt.
$stmt->bindparam(':user_name',$user_name);
$stmt->execute();
public function usernameCheck($username)
{
$sql = "SELECT * FROM $this->table where username = :username";
$query = $this->pdo->prepare($sql);
$query->bindValue(':username', $username);
$query->execute();
if ($query->rowCount() > 0) {
return true;
} else {
return false;
}
}
use this one in your project hope it will work... :)
missing } in if statement
if (isset($_POST['submit'])) {
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$user_pass = $_POST['user_pass'];
$hash = password_hash($user_pass, PASSWORD_DEFAULT);
$stmt = $con->prepare("SELECT user_name FROM users WHERE user_name = :user_name");
if($stmt->rowCount() > 0){
echo "exists!";
}
}else{
}
I notice 4 things (2 of which have been mentioned by others):
First and smallest is you have a spelling error ($con instead of $conn) - don't worry it happens to the best of us - in you first $stmt query which means your select-results becomes NULL instead of 0 - so you rowCount find that it is not over 0 and moves on without your error message
Second you forgot to bind and execute the parameters in your first $stmt query which gives the same result for your rowCount results
Third always clean your variables even when using prepared statements - at a bare minimum use
$conn->mysql_real_escape_string($variable);
and you can with advantage use
htmlspecialchars($variable);
And fourth since you are not doing anything with the database (other than looking) you could simplify your code by simply writing:
$stmt = $conn->query("SELECT user_name FROM users WHERE user_name = '$user_name' LIMIT 1")->fetch();
as I said - no need to bind or execute in the first query
and as a general rule - don't use rowCount - ever - if you have to know the number of results (and in 99% of cases you don't) use count(); but if you as here just want to know if anything at all was found instead use:
if ( $stmt ) {
echo "exists!";
} else {
// insert new user as you did
}
Edit:
Also - as a side note - there are a few things you should consider when you initially create your connection...
Ex:
// Set variables
$servername = "localhost";
$username = "***";
$password = "***";
$database = "***";
$charset = 'utf8'; // It is always a good idea to also set the character-set
// Always create the connection before you create the new PDO
$dsn = "mysql:host=$servername;dbname=$database;charset=$charset";
// Set default handlings as you create the new PDO instead of after
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // And add default fetch_mode
PDO::ATTR_EMULATE_PREPARES => false, // And ALWAYS set emulate_prepares to false
];
// And now you are ready to create your new PDO
$conn = new PDO($dsn, $username, $password, $opt);
Just a suggestion... happy trails

PHP not posting onto mySQL database

This code should check for existing usernames and if there isn't one, it should create a new one. No matter what it won't add. Additionally, as you can see in the code it only echoes 'here' and doesn't echo 'not here'.
<?php
$password = "hey";
$username = "hi";
require "conn.php";
//$password = $_POST["password"];
//$username = $_POST["username"];
echo 'here';
$result = $conn->query("SELECT * FROM UserData WHERE username ='$username' ", MYSQLI_USE_RESULT);
echo 'not here';
if ($result) {
if($result->num_rows === 0)
{
$stmt = $conn->prepare("INSERT INTO UserData (username,password) VALUES (:username,:password)");
$params = array(
':username' => $username,
':password' => $password
);
$stmt->execute($params);
}
}
?>
This is the connection code:
<?php
//$db_name = "xxx";
//$mysql_username = "xxx";
//$mysql_password = "xxx";
//$server_name = "xxx";
// Create connection
$conn = new mysqli("xxx","xxx","xxx","xxx");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Changes:
<?php
require "conn.php";
echo "debug 1";
$stmt = $conn->prepare("SELECT * FROM UserData WHERE username = ?");
$stmt->bind_param('s', /*$_POST["username"]*/ $username );
$username = 'hi';
$stmt->execute();
$stmt->store_result();
echo "debug 2";
if ($stmt->num_rows == 0){ // username not taken
echo "debug 3";
$stmt2 = $conn->prepare("INSERT INTO UserData (username, password) VALUES (?, ?)");
$password =(/*$_POST["password"]*/ "hey");
$username =(/* $_POST["username"]*/ "hi");
$stmt2->bind_param('s',$username);
$stmt2->bind_param('s',$password);
$stmt2->execute();
if ($stmt2->affected_rows == 1){
echo 'Insert was successful.';
}else{ echo 'Insert failed.';
var_dump($stmt2);
}
}else{ echo 'That username exists already.';}
?>
This code gets through all of the debugs but for some reason, it is still not inserting.
Replace this line
$result = **$mysqli->**query("SELECT * FROM UserData WHERE username ='$username' ", MYSQLI_USE_RESULT);
with following
$result = **$conn->**query("SELECT * FROM UserData WHERE username ='$username' ", MYSQLI_USE_RESULT);
The mysqli and PDO interfaces must not be mixed. Here the database connection and the SELECT query are both using the mysqli interface. But the second INSERT query is attempting to use the PDO interface, as evidenced by the use of named placeholders, and also the passing of a data array directly to execute(). The latter two features are not supported by mysqli, hence the code fails at the second query. Also, note that the second query is using prepared statements, while the first one is not. Again, different approaches should not be mixed together.
Also it appears that passwords are being stored as plain text, with no security. The proper approach is to use the password_hash function.
Just ensure that the database field has enough width (say 80-120 characters or more) to handle the current bcrypt hash, plus allow some more for future changes.
Staying with the mysqli interface (and with password_hash), the code could go something like this:
$stmt = $conn->prepare("SELECT * FROM UserData WHERE username = ?");
$stmt->bind_param('s', $_POST["username"]);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 0){ // username not taken
$stmt2 = $conn->prepare("INSERT INTO UserData (username, password) VALUES (?, ?)");
$password = password_hash($_POST["password"], PASSWORD_DEFAULT);
$stmt2->bind_param('s', $_POST["username"]);
$stmt2->bind_param('s', $password);
$stmt2->execute();
if ($stmt2->affected_rows == 1)
echo 'Insert was successful.';
else echo 'Insert failed.';
}
else echo 'That username exists already.';
Note that the above approach would not be suitable for a high-traffic site, where there is a chance condition of another user trying to INSERT the same username, during the brief interval of time between the SELECT and INSERT database queries. That would require a different approach, like ensuring the subject database field is set to UNIQUE (which is good practice anyway), and then testing for violation of that UNIQUE field upon attempted duplicate insertion.
Assuming database and INSERT permissions are all set up OK and it is still not inserting, try enhancing the error-reporting.
Ensure the following are at the top of the page:
ini_set('display_errors', true);
error_reporting(E_ALL);
And put the following before the first query:
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL;
Then try again.

password_verify having a few issues hopefully someone can help me

So im making a login for a game system that uses a JSON string to read back the files, however when I Hash the password and try login it doesn't work however when the password is unhased it works fine, I think the problem lies with the password verify part.
Im just unsure where to place it if someone could guide me in the right direction that will be amazing...
So the issue is when I send the $password example test5 it only reads as test 5 and not this $2y$10$viov5WbMukXsCAfIJUTUZetGrhKE9rXW.mAH5F7m1iYGfxyQzQwD.
This was the original Code
<?php
include("dbconnect.php");
/////// First Function To Get User Data For Login
if($_GET["stuff"]=="login"){
$mysqli = new mysqli($DB_host, $DB_user, $DB_pass, $DB_name);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/////// Need to Grab Username And Password
$username = $_GET["user"];
$password = $_GET["password"];
$query = "SELECT username, password, regkey, banned FROM users WHERE username='$username' and password='$password'";
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->bind_result($username, $password, $regkey, $banned);
while ($stmt->fetch()) {
echo "{";
echo '"result": "success",';
echo '"regkey": "' . $regkey . '",';
echo '"banned": "' . $banned . '"';
echo "}";
}
$stmt->close();
}
$mysqli->close();
}
Then I tried This
<?php
include("dbconnect.php");
/////// First Function To Get User Data For Login
if($_GET["stuff"]=="login"){
$mysqli = new mysqli($DB_host, $DB_user, $DB_pass, $DB_name);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/////// Need to Grab Username And Password
$username = $_GET["user"];
$password = $_GET["password"];
$GetPassword = "SELECT password FROM users WHERE username='$username'";
$data = mysqli_query($GetPassword);
if(password_verify($password, $data['password'])) {
$query = "SELECT username, password, regkey, banned FROM users WHERE username='$username' and password='$password'";
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->bind_result($username, $password, $regkey, $banned);
while ($stmt->fetch()) {
echo "{";
echo '"result": "success",';
echo '"regkey": "' . $regkey . '",';
echo '"banned": "' . $banned . '"';
echo "}";
}
$stmt->close();
}
} else {
// password is in-correct
}
$mysqli->close();
}
$data = mysqli_query($GetPassword);
^^^---mysqli result handle/object
if(password_verify($password, $data['password'])) {
^^^^^^^^^^^^---no such element in mysqli
You never fetched your data results, so you're comparing the entered password against a non-existent element of the $data result object/handle.
You need
$row = mysqli_fetch_assoc($data);
password_verify(..., $row['password']);
Most likely you're running with error_reporting and display_errors disabled, meaning you'd never see the "undefined index" warnings that PHP would ave been throwing everytime you ran this code. Those settings should NEVER be off on a devel/debug system.
And note that you're vulnerable to sql injection attacks, so your "security" system is anything but -it's entirely useless and trivially bypassable.
There are several issues with your code, such as:
This statement $data = mysqli_query($GetPassword) is wrong. mysqli_query() expects first argument to be your connection handler, so it should be,
$data = mysqli_query($mysqli, $GetPassword);
Look at this statement, if(password_verify($password, $data['password'])) { ...
mysqli_query(), on success, returns a result set, so you can't get the password using $data['password']. First fetch the row from the result set and then get the password, like this,
$row = mysqli_fetch_assoc($data);
if(password_verify($password, $row['password'])) { ...
Look at the following query,
$query = "SELECT username, password, regkey, banned FROM users WHERE username='$username' and password='$password'";
This query won't return any rows because of this WHERE condition, ...password='$password'. So the solution is, instead using two separate queries, use only one query to validate the password and retrieve relevant data. The solution is given down below.
Your queries are susceptible to SQL injection. Always prepare, bind and execute your queries to prevent any kind of SQL injection.
If you want to build a json string then instead of doing echo "{"; echo '"result": "success",'; ..., create an array comprising of all the relevant data and then json_encode the array.
So the solution would be like this:
// your code
$username = $_GET["user"];
$password = $_GET["password"];
// create a prepared statement
$stmt = mysqli_prepare($mysqli, "SELECT username, password, regkey, banned FROM users WHERE username=?");
// bind parameters
mysqli_stmt_bind_param($stmt, 's', $username);
// execute query
mysqli_stmt_execute($stmt);
// store result
mysqli_stmt_store_result($stmt);
// check whether the SELECT query returned any row or not
if(mysqli_stmt_num_rows($stmt)){
// bind result variables
mysqli_stmt_bind_result($stmt, $username, $hashed_password, $regkey, $banned);
// fetch value
mysqli_stmt_fetch($stmt);
if(password_verify($password, $hashed_password)){
echo json_encode(array('result' => 'success', 'regkey' => $regkey, 'banned' => $banned));
}else{
// incorrect password
}
}else{
// no results found
}
mysqli_stmt_close($stmt);
// your code

Error that will not show itself

I'm trying to code a registration system for a system I am making. Currently, I am receiving a MySQL error that makes me want to tear my head out each and every time I see it.
function UserRegister($user,$pass,$email,$first,$last)
{
$sqlfirst = mysql_real_escape_string($first);
$sqllast = mysql_real_escape_string($last);
$sqluser = mysql_real_escape_string($user);
$hashpass = crypt($pass);
$sqlpass = mysql_real_escape_string($hashpass);
$sqlemail = mysql_real_escape_string($email);
$sql = "SELECT *
FROM planerentalusers
WHERE user = '$sqluser' ";
if($result = mysqli_query($GLOBALS['db'],$sql))
{
$rowcount=mysqli_num_rows($result);
if($rowcount == 1)
{
echo "ERROR: There is already an account with that username! Click <a href='/PHPCalTest/login.php>here </a>to login if this is you. Otherwise, go back and try a different username.";
}
else
{
$sql2 = "INSERT INTO planerentalusers (first,last,user,pass,email) VALUES ('$sqlfirst','$sqllast','$sqluser','$sqlpass','$sqlemail')";
$result2 = mysqli_query($GLOBALS['db'],$sql);
if($result2 == true)
{
return true;
}
else return false;
}
}
else return false;
mysqli_free_result($result);
}
Above is the function that throws the error.
there is no PHP stack trace that is being thrown, so here is what I pinpointed it to: the query is failing. But how, I do not understand. Perhaps someone can point me in the right direction.
That is not a direct answer to your question. It has been solved somewhere between the comment lines.
Now, you can streamline and secure your code if you will:
use prepared statements. It's only natural since you are already using mysqli_* extension. Parameters that you pass to the prepared INSERT statement will be properly escaped.
utilize INSERT IGNORE syntax and check for affected rows with affected_rows. That way you do all you need to do hitting your database only once.
For INSERT IGNORE to work properly you have to have a UNIQUE constraint on username column.
ALTER TABLE planerentalusers ADD UNIQUE (username);
Now if you issue an INSERT IGNORE statement and a username doesn't exist a row will be inserted and affected_rows will return 1. If a username already exists then IGNORE clause will allow your INSERT statement to complete without throwing an error and affected_rows will return 0.
That being said an improved version of your function might look like
function UserRegister($db, $username, $pass, $email, $first, $last) {
$sql = "INSERT IGNORE INTO planerentalusers (first, last, username, pass, email) VALUES (?, ?, ?, ?, ?)";
// prepare the statement
$stmt = $db->prepare($sql);
if (!$stmt) {
die('Can\'t prepare: ' . $db->error); //TODO better error handling
}
// bind parameters
$stmt->bind_param('sssss', $first, $last, $username, $pass, $email);
if (!$stmt) {
die('Can\'t bind parameters: ' . $db->error); //TODO better error handling
}
// execute
$stmt->execute();
if (!$stmt) {
die('Query execution failed: ' . $db->error); //TODO better error handling
}
// get the number of affected rows
$affected_rows = $stmt->affected_rows;
// close the statement
$stmt->close();
return $affected_rows;
}
and the calling code
$first = $_POST['first'];
$last = $_POST['last'];
$username = $_POST['username'];
$pass = crypt($_POST['pass']);
$email = $_POST['email'];
//create a connection to the database
$db = new mysqli('localhost', 'user', 'password', 'dbname');
if ($db->connect_errno) {
die('Connection failed: ' . $db->connect_error); //TODO better error handling
}
if (!UserRegister($db, $username, $pass, $email, $first, $last)) {
echo "ERROR: There is already an account with that username! Click <a href='/PHPCalTest/login.php'>here </a>to login if this is you. Otherwise, go back and try a different username.";
} else {
echo "Account successfully created";
}
Note that
A reference to an open db connection is explicitly passed to the function instead of using $_GLOBALS['db']
presentation logic (echoing an error message and a link) is moved out to the calling code
Basic error handling is implemented throughout the function

Categories