PHP Login and connecting to MySql - php

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>";
}

Related

Simple PHP login form not working

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

Checking if username is available

I am trying to check if the username is available before i insert into the table.
But it seems to insert into the table no matter if the username already exists.
Here is my php code:
<?php
session_start();
define('DB_NAME', 'madsanker_dk_db');
define('DB_USER', 'madsanker_dk');
define('DB_PASSWORD', 'myPassword');
define('DB_HOST', 'mysql43.unoeuro.com');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' .mysqli_error());
}
$db_selected = mysqli_select_db( $link, DB_NAME);
if (!$db_selected) {
die('Could not connect: ' .mysqli_connect_error());
}
$username = $_POST['username'];
$password = $_POST['password'];
$name = $_POST['name'];
$email = $_POST['email'];
$username = mysqli_real_escape_string($link,$username);
$password = mysqli_real_escape_string($link,$password);
$name = mysqli_real_escape_string($link,$name);
$email = mysqli_real_escape_string($link,$email);
$password = md5($password);
$sql = "SELECT * FROM mainLogin WHERE username = '$username'";
$result = mysqli_query($link, $sql);
$count = mysqli_num_rows($result);
if($count > 0) {
$sql = "INSERT INTO mainLogin (username, password, name, email) VALUES ('$username', '$password', '$name','$email' )";
$result = mysqli_query($link, $sql);
if (!$result) {
die('Error: ' . mysqli_error($link));
}else {
$_SESSION['login'] = $username;
echo "<script>window.location = 'http://madsanker.dk.linux101.unoeuro-server.com'</script>";
}
}else {
echo "username taken";
}
mysqli_close($link);
?>
What am I doing wrong?
just change the greater sign in your if statement from ">" to ==0
if($count==0){
}
If username already in db than change this condition:
if($count > 0) { 
//your stuff
}
With:
if($count <= 0) { // if not found
//your stuff
}

Make PHP loop echo in reversed order

I'm making a simple webpage where anyone can type in a text in a textfiel, and that text will be stored to a database and placed on the screen. At the moment, the text that was posted most recently gets placed at the bottom at the page. I want it to be reversed; the newest at the top and the oldest at the bottom.
Here is my code:
<html>
<head><title>JANNEchat Beta</title></head>
<form action="index.php" method="post" />
<p>Send a message to JANNES database: <input type="text" name="input1" />
</p><input type="submit" value"Submit" />
</form>
</html>
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
define('DB_NAME', 'janne');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link){
die('Nu är något vajsing, kunde inte ansluta ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('Nu spelas det trix, kan inte hitta databasen ' . DB_NAME . ' : ' .
mysql_error()); }
$value = isset($_POST['input1']) ? $_POST['input1'] : '';
if($value != ''){
$sql = "INSERT INTO janne (String) VALUES ('$value')";
if(!mysql_query($sql)){
die('vajsing: ' . mysql_error());
}
}
mysql_close();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "janne";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT String FROM janne";
$result = $conn->query($sql);
//$a = $result->num_rows - $result->fetch_assoc();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//THE PROBLEM IS HERE, I GUESS.
echo $row["String"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Just update your SQL
$sql = "SELECT String FROM janne ORDER BY id DESC";
Here id may be the Auto Increment field in your table.

No Match found using query in MySql database using PHP

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

PHP SESSION will not be set by value from DB

Problem: I have built an login system and it works fine on my localhost.
Localhost: Here it works.
FTP-server: Here it's not working.
I've tried to fix this for 7 hours now.
$_POST is getting the value, if I set a $_SESSION it also shows the value.
DB info is correct.
I think the problem is when connecting to DB to get values. Where I did wrong I do not know, as above tried to fix this for a long time now.
Login file:
<?php
ini_set("default_charset","iso-8859-1");
session_start();
require_once("db_config.php");
echo $_SESSION['USER_ID']." - ";
if(!empty($_POST['username']) AND !empty($_POST['password'])) {
$username_db = $_POST['username'];
$password_db = $_POST['password'];
if(isset($username_db) AND isset($password_db)) {
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$qry="SELECT * FROM user_table WHERE email='".$username_db."' OR alias='".$username_db."' AND password='".$password_db."' ";
$result=mysql_query($qry);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while($rows=mysql_fetch_row($result)) {
$_SESSION['USER_ID'] = $rows['id'];
header("Location: index.php");
}
}
}
if(!empty($_SESSION['USER_ID'])) {
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$qry="SELECT * FROM user_table WHERE id='".$_SESSION['USER_ID']."'";
$result=mysql_query($qry);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while($rows=mysql_fetch_array($result)) {
header("Location: index.php");
}
}
?>
check if login SESSION is set: I think there is some messed up code here.
<?php
ini_set("default_charset","iso-8859-1");
session_start();
require_once("db_config.php");
if(!empty($_SESSION['USER_ID'])) {
$user_id = $_SESSION['USER_ID'];
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$qry="SELECT * FROM user_table WHERE id='".$user_id."'";
$result=mysql_query($qry);
if (!$result) {
header("Location: login.php");
die('Invalid query: ' . mysql_error());
}
while($rows=mysql_fetch_array($result)) {
$_SESSION['ALIAS'] = $rows['alias'];
$_SESSION['FIRST_NAME'] = $rows['first_name'];
$_SESSION['LAST_NAME'] = $rows['last_name'];
$_SESSION['EMAIL'] = $rows['email'];
$_SESSION['USER_LEVEL'] = $rows['user_level'];
}
} else { header("Location: login.php"); }
?>

Categories