I have a MySql database with the following columns:
and a HTML form like so:
<form method="post" action="validate.php">
<label for="users_email">Email:</label>
<input type="text" id="users_email" name="users_email">
<label for="users_pass">Password:</label>
<input type="password" id="users_pass" name="users_pass">
<input type="submit" value="Submit"/>
</form>
Here's snippet of code within the validate.php page:
$email = $_POST['users_email'];
$pass = $_POST['users_pass'];
$dbhost = '************';
$dbuser = '************';
$dbpass = '************';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn)
{
die('Could not connect: '. mysql_error());
}
mysql_select_db("SafeDropbox", $conn);
$result = mysql_query("SELECT Email, UserPassword FROM tblnewusers WHERE Email = $email");
$row = mysql_fetch_array($result);
if($row['Email'] == $email && $row['UserPassword'] == $pass) {
echo "Valid";
}
elseif($row.count() == 0) {
echo "No Match";
}
else {
echo "Invalid";
//header("Location: http://www.google.ie");
//exit();
}
The problem is I'm getting no match even though the values of $email and $pass are definitely within my database. What am I doing wrong?
The problem is in:
$result = mysql_query("SELECT Email, UserPassword FROM tblnewusers WHERE Email = $email");
$email should be escaped and surrounded by quotes. The safest solution is to use a prepared statement:
$result = mysql_query("SELECT Email, UserPassword FROM tblnewusers WHERE Email = ?");
$con=new mysqli($dbhost, $dbuser, $dbpass, $yourDatabase);
$stmt = $mysqli->prepare($result);
$stmt->bind("s",$email);
$result=$stmt->execute();
For more details see http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
Related
Why can't I login to my index.php page its just getting stucked in my login.php page. Please help. Thanks.
<?php
session_start();
$conn = new PDO('mysql:host = localhost;dbname=userdb','root','');
if (isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
$query = $conn->prepare("SELECT COUNT('userID') FROM 'tbl_account' WHERE 'username' = '$username' AND 'password' = '$password' ");
$query->execute();
$count = $query->fetchColoumn();
if ($count == 1){
$_SESSION['username'] = $username;
header("location : index.php");
exit();
}else{
$error = "Your Login Name or Password is invalid";
}
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<form action = "?" method = "POST">
<input type = "text" name="username"><br> //username
<input type = "password" name = "password"><br> //password
<input type = "submit" name = "submit" value = "Login"> /button
</form>
</body>
</html>
where could probably my mistake? on my PDO? on my prepared statement? TIA
1)form action missing.
2)isset($_POST['login']) wrong name checking in if condition.
3)prepared statement have lots of issue.
try something like this
<?php
session_start();
//db connection
global $conn;
$servername = "localhost"; //host name
$username = "root"; //username
$password = ""; //password
$mysql_database = "userdb"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
if(isset($_POST['submit']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $conn->prepare("SELECT * FROM tbl_account WHERE username =? AND password =? ");
$stmt->bind_param('ss',$username,$password);
$stmt->execute();
$get_result= $stmt->get_result();
$row_count= $get_result->num_rows;
$stmt->close();
$conn->close();
if ($row_count>0){
$_SESSION['username'] = $username;
header("location:index.php");
exit();
}else{
$error = "Your Login Name or Password is invalid";
}
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<form action = "login.php" method = "POST">
<input type = "text" name="username"><br> //username
<input type = "password" name = "password"><br> //password
<input type = "submit" name = "submit" value = "Login"> /button
</form>
</body>
</html>
its syntax to use an exit(); after any header('location [...]') calls, you're missing this in your code which could be the reason why your page does nothing.
Also, I'd really like to touch up on some security notes: what the hell is that?
PDO has pre-written functions to allow you the full dynamics of a connection with security, they are there to be used; as it stands, your SQL statement is a security risk as you're directly inserting untrusted data into a statement without stripping it of injections.
Heres an example you could use to secure this:
class DB extends PDO
{
function __construct(
$dsn = 'mysql:host=localhost;dbname=kida',
$username = 'root',
$password = 'root'
) {
try {
parent::__construct($dsn, $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
parent::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo $e->getMessage();
}
}
public function query($statement, array $parameters = array())
{
$stmp = parent::Prepare($statement);
$i = 1;
foreach($parameters as $parameter) {
$stmp->bindParam($i, $parameter);
$i++;
}
$stmp->execute();
return $stmp->FetchAll();
}
}
$Con = new DB();
$username = "example";
$row = $Con->query("SELECT * FROM table WHERE username = ?", [$username]);
You have wrongly used prepared statement.
You should write,
$query = $conn->prepare("SELECT COUNT('userID') FROM REGISTRY WHERE name = ? AND password' = ?");
$query->bindParam(':name', $username);
$query->bindParam(':password', $password);
$query->execute();
$result_rows = $query->fetchColumn(); // get result
Check this link for more detail.
Suggestion:- also add exit; after header tag to stop execution of afterward code.
try and change this code to
"SELECT COUNT('userID') FROM 'tbl_account' WHERE 'username' = '$username' AND 'password' = '$password' ");
put semicolon inside the quotes and on the outside as well
"SELECT userID FROM tab1_account WHERE username='$username' AND password='$password';";
I'm currently trying to create a VERY basic login request page with no security (i'm just learning the fundamentals).
I currently have a database and a table created on phpmyadmin with 1 tuple consisting of an email and password (as well as other information).
I've created a HTML form which consists of two input fields for email, password and a submit button which sends the user to a new sign-in-script.php page.
My HTML:
<form action="sign-in-script.php" method="GET">
<input type="text" name="email" placeholder="Email" />
<input type="password" name="password" placeholder="Password"/>
<input type="submit" value="Sign in" name="submit" />
sign-in-script.php
if(isset($_GET['submit'])) {
$servername = 'localhost';
$username = 'root';
$password = 'root';
$email = $_GET['email'];
$user_password = $_GET['password'];
$conn = new mysqli($servername, $username, $password);
if($conn->connect_error) {
die ('Connection Failed');
} else {
echo ('Connection Established <br>');
if(!mysqli_select_db($conn,'Oreon')) {
die('Database could not be reached ' . $conn->error);
} else {
echo ('Database Reached <br> ');
echo $email;
echo '<br>';
echo $user_password;
$sign_in_token = "SELECT * FROM core_customer_information WHERE email='".$email."' AND password='".$user_password."' LIMIT 1";
$result = mysqli_query($sign_in_token);
if(mysqli_num_rows($result) == 1) {
echo "You have successfully logged in";
} else {
die ("Incorrect email address or password: " . $conn->error);
}
} // close brackets db selected
}
}
I've made sure multiple times that the email and password i've entered match those saved in the db but it's still returning as 'incorrect email or password' and I'm unsure why.
I've took the SQL query and ran it directly in phpmyadmin at the query returns the tuple i'm supposed to return so pretty unsure why it is not working in my script.
I would appreciate some help if possible.
Thank you to anyone who takes the time in advance.
mixed use of mysql and mysqli.
try this:
if(isset($_GET['submit'])) {
$servername = 'localhost';
$username = 'root';
$password = 'root';
$email = $_GET['email'];
$user_password = $_GET['password'];
$conn = new mysqli($servername, $username, $password);
if($conn->connect_error) {
die ('Connection Failed');
} else {
echo ('Connection Established <br>');
if(!mysqli_select_db($conn,'Oreon')) {
die('Database could not be reached ' . $conn->error);
} else {
echo ('Database Reached <br> ');
echo $email;
echo '<br>';
echo $user_password;
$sign_in_token = "SELECT * FROM core_customer_information WHERE email=".$email." AND password=".$user_password." LIMIT 1";
$result = mysqli_query($conn, $sign_in_token);
if(mysqli_num_rows($result) == 1) {
echo "You have successfully logged in";
} else {
die ("Incorrect email address or password: " . $conn->error);
}
} // close brackets db selected
}
}
I am new to PHP. I am creating a login.php page. i have created a table into MySQL database.
Database name: school
Table name: users
I have saved a username = admin and pass= 123
I am now trying to connect the database and trying to verifying the input information from database before accessing to the page "admin.php"
<?php
error_reporting(E_ERROR);
global $link;
$servername='localhost';
$dbname='school';
$dbusername='root';
$dbpassword='';
$table_Name="users";
$link = mysql_connect($servername,$dbusername,$dbpassword);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
else
{
mysql_select_db($dbname,$link) or die ("could not open db".mysql_error());
}
?>
Getting input data from this code
<?php
$my_user = $_POST['user'];
$my_password = $_POST['password'];
?>
trying this
$signin = mysql_query( "SELECT FROM users where username = &my_user" )
or die("SELECT Error: ".mysql_error()); $num_rows = mysql_num_rows($signin);
Now kindly explain with code how can I connect the database and verify the information and if its correct the page should redirect to admin.php page
This will insert the form info into database:
$insert="INSERT INTO `users`(`user`,`password`) VALUES ('$my_user','$my_password') ";
$query=mysql_query($insert,$link);
This will select the info from database:
$result=mysql_query('SELECT * FROM users WHERE username='$my_user' AND password='$my_password'");
$sql1=mysql_query($result,$link);
<?php
if (isset($_POST)) {
$my_user = $_POST['user'];
$my_password = $_POST['password'];
$con=mysql_connect("localhost","root","");
if(!$con)
{
die("Database is not connected");
}
mysql_select_db("school",$con);
$query="select * from users where username=$my_user and pass=$my_password";
$res=mysql_query($query);
if(mysql_num_rows($res) > 0)
header('Location:admin.php'); // redirect to home page
else
echo 'Not found'; // can show some validation err
}
<?php
include('conn.php');
if (isset($_POST['submit'])){
$UserName=$_POST['user'];
$PassWord=$_POST['pass'];
$sql = "SELECT username,pass from login WHERE username='$UserName'and password='$PassWord'";
$retval = mysql_query($sql);
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
if (($row['username']==$Username)and($row['pass']==$Password)){
header("location:admin.php");
}
}
}
echo "Invalid User Name and Password\n";
?>
Start to use PDO for database connections. I have not tested this, but should give you insight into what to do.
config.php
<?php
define('DB_TYPE', 'mysql');
define('DB_HOST', 'localhost');
define('DB_NAME', 'school');
define('DB_USER', 'root');
define('DB_PASS', '');
?>
functions.php
<?php
function validate_user_creds() {
try
{
$pdo = new PDO(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME.', '.DB_USER.', '.DB_PASS);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
header('Location: admin.php');
exit();
}
catch (PDOException $e)
{
$error = 'Unable to connect to the database server.';
include 'error.html.php';
exit();
}
}
?>
login.php
<?php
require 'config.php';
require 'functions.php';
if ($_POST['user'] === DB_NAME && $_POST['password'] === DB_PASS) {
validate_user_creds();
}
?>
Normally with mysql (deprecated!)
<?php
error_reporting(E_ERROR);
$error = false;
if(isset($_POST['login']))
{
$servername = 'localhost';
$dbname = 'school';
$dbusername = 'root';
$dbpassword = '';
$table_Name = 'users';
$link = mysql_connect($servername, $dbusername, $dbpassword) or die('Could not connect: ' . mysql_error());
mysql_select_db($dbname, $link) or die ('could not open db' . mysql_error());
$my_user = $_POST['user'];
$my_password = $_POST['password'];
$signin = mysql_query("SELECT * FROM `users` WHERE `username` = '" . mysql_real_escape_string($my_user) . "' AND `password` = '" . mysql_real_escape_string($my_password) . "' LIMIT 1;")
or die('SELECT Error: '.mysql_error());
$num_rows = mysql_num_rows($signin);
mysql_close($link);
if($num_rows)
{
header('Location: admin.php');
}
else
{
$error = 'Unknown login!';
}
}
?><html><head><title>Login</title></head><body>
<form action="#" method="post">
<?php if($error !== false) { echo '<p>' . $error . '</p>'; } ?>
<input name="user" type="text" size="255" />
<input name="password" type="text" size="255" />
<button type="submit" name="login">Login</button>
</form>
</body></html>
PDO / MySQLi
<?php
error_reporting(E_ERROR);
$error = false;
if(isset($_POST['login']))
{
$servername = 'localhost';
$dbname = 'school';
$dbusername = 'root';
$dbpassword = '';
$table_Name = 'users';
$link = new mysqli($servername, $dbusername, $dbpassword, $dbname);
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$my_user = $_POST['user'];
$my_password = $_POST['password'];
if(!($signin = $link->prepare('SELECT * FROM `users` WHERE `username` = ? AND `password` = ? LIMIT 1;')))
{
printf("Select Error: %s\n", $link->error);
exit();
}
$signin->bind_param('ss', $my_user, $my_password);
if($signin->execute())
{
$signin->store_result();
$num_rows = $signin->num_rows;
if($num_rows)
{
header('Location: admin.php');
}
else
{
$error = 'Unknown login!';
}
}
$link->close();
}
?><html><head><title>Login</title></head><body>
<form action="#" method="post">
<?php if($error !== false) { echo '<p>' . $error . '</p>'; } ?>
<input name="user" type="text" size="255" />
<input name="password" type="text" size="255" />
<button type="submit" name="login">Login</button>
</form>
</body></html>
Use PDO with prepared statements when you access databases in PHP, since it helps against SQL injection. Have a look at http://php.net/manual/en/intro.pdo.php.
Edit:
Wayne's answer is just confusing. In login.php he is validating the administrator by comparing the user's name to the database name and the user's password to the database's password. I don't recommend it, and it doesn't really have much to do with what you posted.
I'd go with PatrickB's answer.
if(mysql_num_rows(mysql_query("select * from users where username='$my_user' and pass='$my_password'"))>0) {
header('Location:admin.php');
} else {
echo " < b > Incorrect username or password<\b>";
}
Hey guys i am new to php development and came across with a project in php ..
My html code
<html>
<body>
<form name="input" action="database.php" method="post">
Username: <input type="text" name="user">
<br>
<input type="submit" value="Submit">
</form>
php code
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$name = $_POST['user'];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT username, phoneno FROM test';
mysql_select_db('test');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_assoc($retval,MYSQL_ASSOC))
{
if($name != $row['username']) {
echo "this username is not in our db";
} else {
echo "you are logged in";
}
}
mysql_close($conn);
?>
Here the user is allowded to login by giving his username and if the username is not in the database he must get a message this is not in out db.But when i typed a username which doesnt exist in our db it gives me message 3 times like this username is not in our db you are logged in this username is not in our db..Here the else part code and actual code are working together ..why is it like this ..Hope you guys can help me ,
You're looping through all rows in your table and hence on each iteration, either one of the if-else statement is getting executed.
To overcome this, you can do something like this:
$users = array();
while($row = mysql_fetch_assoc($retval,MYSQL_ASSOC))
{
$users[] = $row['username']; // store all usernames in an array
}
// now check for your condition
// in_array checks for existence of a string inside an array ($users)
if(in_array($name, $users)) {
echo "You are logged in";
} else {
echo "This username is not in our db";
}
Steps to solve the problem:
1) We are checking in the database if there is any entry with username = $_POST['user']
2) If we don't find an entry then echo "this username is not in our db" or else echo "you are logged in"
My HTML code
<html>
<body>
<form name="input" action="database.php" method="post">
Username: <input type="text" name="user">
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
PHP code
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'test';
$name = $_POST['user'];
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(!$conn){ die('Could not connect: ' . mysqli_connect_error()); }
$retval = mysqli_query($conn, "SELECT username, phoneno FROM test WHERE username='".$name."'");
if(mysqli_num_rows($retval)<1){
echo "this username is not in our db";
} else {
echo "you are logged in";
}
mysqli_close($conn);
?>
Your Mistake :
1) You were looping the entire table & hence it was generating 3 output at the same time
I'm sitting infront of this code for 2 hours i cant figure out whats wrong :(
I've been trying to have a html form which calls the php function to insert the information from the form into the database but for some reason does not work :/
here is my form code :
<?php include 'connection.php'; ?>
<html>
<body>
<form action="user_create.php" method="POST">
username: <input type="text" name="username"/>
password: <input type="text" name="password"/>
email: <input type="text" name="email"/>
<input type="submit" name='submit' value="user_create"/>
</form>
</body>
</html>
database connection
<?php
//Connecting databases
$localhost = "";
$dbuser = "";
$dbpass = "m";
$dbname = "";
$connect = mysql_connect($localhost, $dbuser, $dbpass);
mysql_select_db("$dbname", $connect);
?>
my php function
<?php include 'connection.php';?>
<?php
if (isset($_POST['submit']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$query = mysql_query("INSERT INTO users( username,password,email,type)
VALUES ('$username', '$password', '$email','1')");
mysql_query($query);
echo '<script type="text/javascript">alert("You have been registered");</script>';
}
else
{
echo '<script type="text/javascript">alert("jo");</script>';
}
?>
You should use PHP-PDO in order to avoid from SQL Injection attacks also it will fix insert trouble too.
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=animals", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** INSERT data ***/
$sql = "INSERT INTO users(username,
password,
email,
type) VALUES (
:username,
:password,
:email,
:type)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $_POST['username'], PDO::PARAM_STR);
$stmt->bindParam(':password', $_POST['password'], PDO::PARAM_STR);
$stmt->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
$stmt->bindParam(':type', $_POST['type'], PDO::PARAM_INT);
$stmt->execute();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Are you connecting properly?
$dbuser = "";
Maybe must be "root" or other user?
Check this part :
//Connecting databases
$localhost = "";
$dbuser = "";
$dbpass = "m";
$dbname = "";