PHP mysqli_query() to PDO - php

I am trying to make a page to change a password in the database.
I made the form and this is the PHP code :
if(isset($_POST['btn-newpass']))
{
$username = strip_tags($_POST['username']);
$password = md5(strip_tags($_POST['password']));
$password_new = md5(strip_tags($_POST['password_new']));
$password_new_conf = md5(strip_tags($_POST['password_new_conf']));
$password_in_db= mysqli_query("SELECT password FROM utilizatori WHERE username='$username'");
if(!$password_in_db)
{ echo "The entered username doesn't exist";}
elseif($password!=$password_in_db)
{ echo "The current password is wrong";}
if($password_new == $password_new_conf)
{$sql = mysqli_query("UPDATE utilizatori SET password='$password_new' WHERE username='$username'");}
if($sql)
{ echo "Changed successfully!";}
else
{ echo "The passwords do not match";}
}
When I try to change a password I get the following errors:
Warning: mysqli_query() expects at least 2 parameters, 1 given in A:\XAMPP\htdocs\testing\change_password.php on line 10
The entered username doesn't exist
Warning: mysqli_query() expects at least 2 parameters, 1 given in A:\XAMPP\htdocs\testing\change_password.php on line 18
Passwords do not match
In connection.php I have the following code:
class Database
{
private $host = "localhost";
private $db_name = "atlx";
private $username = "root";
private $password = "";
public $conn;
public function dbConnection()
{
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
Could somebody point me out what is wrong here?
EDIT:
I realised the connection to the database is done using PDO. How can I convert the PHP code to work with PDO?

In the mysqli_query you have to pass the connection variable to for executing
Replace
$password_in_db= mysqli_query("SELECT password FROM utilizatori WHERE username='$username'")
With
$password_in_db= mysqli_query($con,"SELECT password FROM utilizatori WHERE username='".$username."'")

As mysqli_query expects parameter 1 to be connection object.
Replace
$password_in_db= mysqli_query("SELECT password FROM utilizatori WHERE username='$username'")
With
$conn = new Database;
$password_in_db= mysqli_query($conn->dbConnection(),"SELECT password FROM utilizatori WHERE username='".$username."'")
OR
$password_in_db= mysql_query("SELECT password FROM utilizatori WHERE username='".$username."'")

mysqli_query($Database->dbConnection(),"SELECT password FROM utilizatori WHERE username='$username'");

Since, You are using PDO for database connection why are you using mysqli_ to perform database query. Learn more about PDO
http://php.net/manual/en/book.pdo.php
on how to perform database query using it. OR learn how to make DB connection using mysqli
http://php.net/manual/en/book.mysqli.php
For your answer if you need to perform mysqli_query you need to add your Database connection in first parameter.
mysqli_query($dblink, "SELECT * FROM City")

Your Re-Written code should be like this
if(isset($_POST['btn-newpass']))
{
$username = strip_tags($_POST['username']);
$password = md5(strip_tags($_POST['password']));
$password_new = md5(strip_tags($_POST['password_new']));
$password_new_conf = md5(strip_tags($_POST['password_new_conf']));
$password_in_db= mysql_query("SELECT password FROM utilizatori WHERE username='".$username."'")
if(!$password_in_db)
{ echo "The entered username doesn't exist";}
elseif($password!=$password_in_db)
{ echo "The current password is wrong";}
if($password_new == $password_new_conf)
{$sql = mysqli_query("UPDATE utilizatori SET password='$password_new' WHERE username='$username'");}
if($sql)
{ echo "Changed successfully!";}
else
{ echo "The passwords do not match";}
}
You can learn more about PDO in this link
http://php.net/manual/en/book.pdo.php

Related

No database selected PHP login

Im trying to create a Login but everytime I type my credentials and click on Login, I get "No database selected"
Here is my PHP code
<?php define('DB_HOST', 'localhost');
define('DB_NAME', 'phplogin');
define('DB_USER','adminuser');
define('DB_PASSWORD','adminuser');
$con=mysql_connect(DB_HOST,DB_USER, "")
//$mysql_select_db = 'phplogin'
//or die("Failed to connect to MySQL: " . mysql_error());
//$db=mysql_select_db(DB_NAME,$con)
or die("Failed to connect to MySQL: " . mysql_error());
$ID = $_POST['user']; $Password = $_POST['pass'];
function SignIn()
{ session_start();
if(!empty($_POST['user']))
{ $query = mysql_query("SELECT * FROM phplogin where userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error()); $row = mysql_fetch_array($query) or die(mysql_error()); if(!empty($row['userName']) AND !empty($row['pass']))
{ $_SESSION['userName'] = $row['pass']; echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE..."; } else { echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY..."; } } } if(isset($_POST['submit'])) { SignIn(); } ?>
Where is the mistake?
Kind regards
newbie
You forgot to pass the variable $con as the link parameter.
mysql_select_db('database', $con) or die(mysql_error());
Use pdo for prevent sql injection.
You mistake this
mysql_select_db('database', $con) or die(mysql_error());
Mysql not available in php7. You can use mysqli or pdo.
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $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();
}
I would really recommend you to use classes, methods and most importantly PDOs.
The use of "unescaped" mysqli is very insecure and vulnerable due to SQL injections.
Also, when storing passwords into your DB, hash them using the PHP function password_hash($password, PASSWORD_DEFAULT); This will generate a hash string that you can store in your DB.
That SignIn with the use of PDO and password_hash() and password_verify() to verify the password would look the following:
Class DataBase (DB) (db.php)
class DB {
private $error;
private $db;
function Conn()
{
try {
$this->db = new PDO('mysql:host=localhost;dbname=phplogin;', 'adminuser', 'adminuser'); //second adminuser is password
return $this->db; //Returns PDO object
}
catch(PDOException $ex){
return $ex->getMessage();
}
}
}
Your login.php (login.php)
require_once('db.php');
$db = new DB(); //Create instance of DB class
$conn = $db->Conn(); //Call Conn() method of DB class
$username = $_POST["user"];
$password = $_POST["pass"];
$statement = $conn->prepare("SELECT * FROM phplogin where userName = :user");
$statement->execute(array(":user"=>$username)); //For :user in SQL query it enters the username you entered in the login form (bind param)
$row = $statement->fetch(); //Returns the row from DB
//password_verify() checks if the password you've enteres matches the hash in the DB
//$row["pass"] is the hash you get returned from the SQL query aboth
if(password_verify($password, $row["pass"])){
return true; //Or echo "success"
}
else{
return false; //Or echo "Wrong username/password"
}
I hope I was able to help you :)

PHP / MySQL: Login form doesn't work

I've got a login.php file which looks like this:
include "myfuncs.php";
$connect = dbConnection();
$username = $_POST["username"];
$passwort = md5($_POST["password"]);
$query = "SELECT username, password FROM user WHERE username LIKE '$username' LIMIT 1";
$ergebnis = mysql_query($query);
$row = mysql_fetch_object($result);
if($row->password == $passwort)
{
echo "Hi $username";
$_SESSION["username"] = $username;
echo "Login successfully";
}
else
{
echo "Login doesn't work";
}
and a myfuncs.php file which looks like this:
function dbConnection()
{
$servername = "...";
$username = "...";
$password = "...";
$dbname = "...";
$db_connect = new mysqli($servername, $username, $password, $dbname);
if ($db_connect->connect_error)
{
die("Connection failed: " . $db_connect->connect_error);
}
return $db_connect;
}
Unfortunately the login form doesn't work - it always gives the error "Login doesn't work" even when the username and password matches with the database entry.
Arg, you are mixing a mysqli with class mysql functions. I dont think it works...
It works this way : PHP MySQLI
$stmt = $mysqli->prepare($query)
while ($stmt->fetch()) {
(...)
}
I see you have error in your variable name in line #6.
try this:
$query = "SELECT username, password FROM user WHERE username LIKE '$username' LIMIT 1";
$result= mysql_query($query);
$row = mysql_fetch_object($result);
There are several problems with your code. In myfuncs.php you use mysqli and after that, in your code you use mysql (without "i"). mysql (without "i") is deprecated, so you should use mysqli everywhere.
More than that, in your code you have:
$query = "SELECT username, password FROM user WHERE username LIKE '$username' LIMIT 1";
$ergebnis = mysql_query($query);
$row = mysql_fetch_object($result);
Please see the bold text from next two lines (it should be the same variable):
$ergebnis = mysql_query($query);
$row = mysql_fetch_object($result);
You should have
$result = mysql_query($query);
if you will use mysql.

Switch from mysql_connect to PDO: mysql_num_rows() expects parameter 1 to be resource

I had code that used mysql_connect which I understand is now deprecated to I switched to the following code (I'm working locally):
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$DBusername = 'admin';
/*** mysql password ***/
$DBpassword = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $DBusername, $DBpassword);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
But this now means that a function of mine breaks:
$result = mysql_num_rows($query);
Because, following the script back, the connection is not working. There is something up with my PDO connection script but I do not understand what I have done wrong. The details are correct for logging into phpMyAdmin on localhost.
function user_exists($username){
$sql = "SELECT `id` FROM `users` WHERE `username` = '".$username."'";
$query = mysql_query($sql);
$result = mysql_num_rows($query);
if($result == 1){
// username does already exist
return true;
}else{
// username doesn't exist in the database
return false;
}
}
PDO is entirely independent from the mysql extension, you will have to update your function calls as well. mysql_query for example should be a combination of prepare and execute.
As a note: Please please use Prepared Statements, your example query is completely insecure.
As an example was requested:
// initialize PDO
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $DBusername, $DBpassword);
// Prepare a query
$sql = "SELECT COUNT(*) AS count
FROM users
WHERE username = ?
LIMIT 1";
$statement = $dbh->prepare($sql);
// execute the query
$statement->execute(array($username));
// retrieve the first row
$row = $statement->fetch();
if ($row['count']) echo 'The user exists';
else echo 'The user does not exist';

PHP registered user check

I have PHP + AS3 user login&register modul.I want to check registered user by username.But can't do it because I'm new at PHP.If you can help it will helpfull thx.(result_message part is my AS3 info text box.)
<?php
include_once("connect.php");
$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
$sql = "INSERT INTO users (username, password, user_bio) VALUES ('$username', '$password', '$userbio')";
mysql_query($sql) or exit("result_message=Error");
exit("result_message=success.");
?>
Use MySQLi as your PHP function. Start there, it's safer.
Connect your DB -
$host = "////";
$user = "////";
$pass = "////";
$dbName = "////";
$db = new mysqli($host, $user, $pass, $dbName);
if($db->connect_errno){
echo "Failed to connect to MySQL: " .
$db->connect_errno . "<br>";
}
If you are getting the information from the form -
$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
you can query the DB and check the username and password -
$query = "SELECT * FROM users WHERE username = '$username'";
$result = $db->query($query);
If you get something back -
if($result) {
//CHECK PASSWORD TO VERIFY
} else {
echo "No user found.";
}
then verify the password. You could also attempt to verify the username and password at the same time in your MySQL query like so -
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password';
#Brad is right, though. You should take a little more precaution when writing this as it is easily susceptible to hacks. This is a pretty good starter guide - http://codular.com/php-mysqli
Using PDO is a good start, your connect.php should include something like the following:
try {
$db = new PDO('mysql:host=host','dbname=name','mysql_username','mysql_password');
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
Your insert would go something like:
$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
$sql = "INSERT INTO users (username, password, user_bio) VALUES (?, ?, ?)";
$std = $db->prepare($sql);
$std = execute(array($username, $password, $userbio));
To find a user you could query similarly setting your $username manually of from $_POST:
$query = "SELECT * FROM users WHERE username = ?";
$std = $db->prepare($query)
$std = execute($username);
$result = $std->fetchAll();
if($result) {
foreach ($result as $user) { print_r($user); }
} else { echo "No Users found."; }
It is important to bind your values, yet another guide for reference, since I do not have enough rep yet to link for each PDO command directly from the manual, this guide and website has helped me out a lot with PHP and PDO.

PHP mysql_real_escape_string(); whats the correct method using mysqli?

its a little difficult to explain. I've build the mysql function which works fine and with the depreciation of mysql I will need to change this function to use mysqli rather than the mysql method.
I current have:
$con = mysql_connect("host", "username", "pass");
mysql_select_db("db", $con);
$Username = mysql_real_escape_string($_POST['user']);
$Password = hash_hmac('sha512', $_POST['pass'], '&R4nD0m^');
$Query = mysql_query("SELECT COUNT(*) FROM users WHERE username = '{$Username}' AND password = '{$Password}'") or die(mysql_error());
$Query_Res = mysql_fetch_array($Query, MYSQL_NUM);
if($Query_Res[0] === '1')
{
//add session
header('Location: newpage.php');
}
else {
echo 'failed login';
}
Now I've applied mysqli to this and it's not returning any data or errors but the function still complies.
$log = new mysqli("host", "user", "pass");
$log->select_db("db");
$Username = $log->real_escape_string($_POST['user']);
$Password = hash_hmac('sha512', $_POST['pass'], '&R4nD0m^');
$qu = $log->query("SELECT COUNT(*) FROM users WHERE username = '{$Username}' AND password = '{$Password}'");
$res = $qu->fetch_array();
if($res[0] === '1'){
//add session
header('Location: newpage.php');
}
else {
$Error = 'Failed login';
sleep(0.5);
}
echo $res['username'].' hello';
}
But I'm unsure on why this is wrong. I know it's probably a simply answer
Just to have it as an answer:
http://php.net/manual/en/pdo.prepared-statements.php
http://php.net/manual/en/pdo.prepare.php
e.g.
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
You may check if the connection is establishing before using real_escape_string()
if ($log->connect_errno) {
echo "Failed to connect to MySQL: (".$log->connect_errno.")".$log->connect_error;
}
afaik, there's no problem with $log->real_escape_string($_POST['user']);

Categories