No database selected PHP login - php

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 :)

Related

PHP mysqli_query() to PDO

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

PHP bindParam not working - blindValue is not the solution

I can't figure this out. I've googled it and a lot of answers refer to blindValue as the solution but I've also tried that with no luck.
The problem is that the SELECT statement is returning zero records but it should return one record. If I hard code the values into the SQL statement it works but passing them in as parameters isn't. Can some one please help me out with this? Thanks.
<?php
function checklogin($email, $password){
try
{
// Connection
$conn;
include_once('connect.php');
// Build Query
$sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = :email AND Password = :password';
// $sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = "a" AND Password = "a"';
// Prepare the SQL statement.
$stmt = $conn->prepare($sql);
// Add the value to the SQL statement
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
// Execute SQL
$stmt->execute();
// Get the data in the result object
$result = $stmt->fetchAll(); // $result is NULL always...
// echo $stmt->rowCount(); // rowCount is always ZERO....
// Check that we have some data
if ($result != null)
{
// Start session
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Search the results
foreach($result as $row){
// Set global environment variables with the key fields required
$_SESSION['UserID'] = $row['pkUserID'];
$_SESSION['Email'] = $row['Email'];
}
echo 'yippee';
// Return empty string
return '';
}
else {
// Failed login
return 'Login unsuccessful!';
}
$conn = null;
}
catch (PDOexception $e)
{
return 'Login failed: ' . $e->getMessage();
}
}
?>
the connect code is;
<?php
$servername = 'localhost';
$username = 'admin';
$password = 'password';
try {
// Change this line to connect to different database
// Also enable the extension in the php.ini for new database engine.
$conn = new PDO('mysql:host=localhost;dbname=database', $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'm connecting to mySQL. Thanks for the help,
Jim
It was a simple but stupid error.
I had a variable called $password also in the connect.php file which was overwriting the $password that I was passing to the checklogin.
Jim

Parsing Json From PHP to Xcode(Swift) with Mysql query

Morning All,
Im after a bit of advice/help with the below issue.
i have tried looking around and google'ing but I still don't understand where I'm going wrong. Please forgive me as I'm a complete noob at this.
some of you may have seem this code before but I'm want to adapt it. Once the user logs in i want to get the user ID from the MySQL Database and send that to swift in the JSON but i can't get it to work, i have tried putting the query in different places with no luck, JSON is completely new to me :(
Ideally > user logs in> swift sends JSON to verify>JSON-PHP verified by MySQL > PHP - JSON reply with success AND user id from the db.
Any Help would be amazing !!
<?php
header('Content-type: application/json');
require("conn.php");
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
$db_name = '***';
$db_user = '***';
$db_password = '***';
$server_url = 'localhost';
$mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
} else {
if ($stmt = $mysqli->prepare("SELECT username FROM users WHERE username = ? and password = ?")) {
$password = md5($password);
/* bind parameters for markers */
$stmt->bind_param("ss", $username, $password);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($id);
/* fetch value */
$stmt->fetch();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
if ($id) {
error_log("User $username: password match.");
echo '{"success":1, "ID":0}';
} else {
error_log("User $username: password doesn\'t match.");
echo '{"success":0,"error_message":"Invalid Username/Password"}';
}
}
} else {
echo '{"success":0,"error_message":"Invalid Username/Password."}';
}
}else {echo '{"success":0,"error_message":"Invalid Data."}';
}
?>

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 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