I'm VERY new to PHP and MySql and like most beginners I'm trying to make use of things I'm learning so I'm trying to make a simple login/logout system.
I've downloaded WAMP,made my database in PHPMyAdmin and my table etc however I cannot get my PHP code to recognise the data in the database, I simply get 'Query failed'!I can certainly connect the database,and I don't believe the problem is with the database but my login file!I've looked at loads of different tutorial but I still can't get this to work.I'd really appreciate if anyone could point me in the right direction!
If anyone wants to play around with my code thats fine the fields I have in the database are: id, username, password, first name, last name (id is a primary key with auto increment)
My login file is
<?php
//require 'core.inc.php';
//echo $current_file;
if (isset($_POST['username'])&& isset ($_POST['password'])){
$username= $_POST['username'];
$password= $_POST['password'];
if (empty ($username)&&empty ($password)){
echo 'supply username and password';
}
$query = "SELECT * FROM 'test1' WHERE 'username'='$username'AND 'password'='$password'";
$result= mysql_query($query);
if($result) {
if(mysql_num_rows($result) > 0) {
//Login Successful
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SURNAME_NAME'] = $member['username'];
$_SESSION['SESS_ID'] = $member['password'];
session_write_close();
exit();
}else {
//Login failed
echo 'user name and password not found';
$errflag = true;
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
exit();
}
}
}else {
die("Query failed");
}
}
?>
<form method="POST">
Username: <input type = "text" name="username"> Password: <input type ="password" name="password">
<input type="submit" value="Log in">
</form>
and my connect data base file is(I have removed my password on purpose) :
// assign the host user name and database name to variables
$db_host = "localhost";
$db_username = "";
$db_password = "";
$db_name = "";
session_start();
// connect to database, if not send error message
mysql_connect("$db_host", "$db_username", "$db_password") or die ("Could not connect to MySQL.");
// check database exists, if not send error message
mysql_select_db("$db_name") or die ("No database.");
// if sucessful connection etc print out the following!
//echo("Successful connection established.");
?>
$query = "SELECT * FROM test1 WHERE username = '$username' AND password = '$password'";
or
$query = "SELECT * FROM `test1` WHERE `username` = '$username' AND `password` = '$password'";
Change die('....'); with echo mysql_errno() . ": " . mysql_error(); exit(); to see whats going on. Also do not use this example code in your real application. It's not secure since it doesn't validate input.
At least do something like:
$sql = "SELECT * FROM bla WHERE x = '".mysql_real_escape_string($_POST['x'])."'";
Alot of problems! here is a fixed code to do it right:
ini_set('display_errors', 1);
$database="******";
$host="localhost";
$table1="install_crawler";
$data_username="**********";
$data_password="*********";
$linkos = mysql_connect("$host", "$data_username", "$data_password") or die('no connection -'.mysql_error());
mysql_select_db("$database") or die('no connection -' .mysql_error());
session_start();
if (isset($_POST['username'])&& isset ($_POST['password'])) {
$username= mysql_real_escape_string($_POST['username']);
$password= mysql_real_escape_string($_POST['password']);
if (empty ($username)&&empty ($password)) { echo 'supply username and password <br />'; }
else {
$query = "SELECT * FROM $table1 WHERE username='$username' AND password='$password'";
$result = mysql_query($query) or die ( "Query problem!".mysql_error());
}
}
if(isset($result)) {
$member = mysql_fetch_row($result);
if(isset($member[0])) //0 - is the first col of the table, 1 is the second etc....
{
//Login Successful - do your stuff - call your functions.
echo "SUCCESS LOGIN!".$member[0];
exit;
}
else
{
//Login failed - do your stuff - call your functions.
echo 'User-name Or Password NOT Correct! Try agian: <br />';
echo '<form method="POST">
Username: <input type = "text" name="username"> Password: <input type ="password" name="password">
<input type="submit" value="Log in">
</form>';
exit;
}
}
else
{
echo '<form method="POST">
Username: <input type = "text" name="username"> Password: <input type ="password" name="password">
<input type="submit" value="Log in">
</form>';
}
Note:
you should use *.mysql_error()*. and add it to your DIE() statements.
don't use single quote while typing the table name & col's.
to check if a query is ok use : *$result = mysql_query($query) or die ( "Query problem!".mysql_error());*
use mysql_real_escape_string() to avoid and escape SQL special chars. (IMPORTANT).
See the rest in the edited code.
Have fun!
$query = "SELECT * FROM test1 WHERE username='".$username."'AND password='".$password."'";
$result= mysql_query($query);
I always always split my variables out from strings and append them together like above.
You may want to start with the following test after using the above
if($result) echo "success";
else echo mysql_error();
Your mysql code would be sound then. I shall point you in the direction that PHPMyAdmin has a create php code button if you create an sql statement using the sql feature.
I noticed that your 'form' tags in the example do not contain an Action parameter, perhaps this is a problem.. If it is intentional then disregard.
You should put action="siteexample.php" as the page where the forum data gets processed.
Does this help?
Related
I've made/copied a fitting and nice inlog page.
I've made it fully functional except there is one mistake, when the username and password arent in the DB it still redirects?
The login form:
<div class="login">
<h1>Login</h1>
<form method="post" action="connectivity.php">
<input type="text" name="user" placeholder="Gebruikersnaam" required/>
<input type="password" name="pass" placeholder="Wachtwoord" required/>
<input id="button" type="submit" class="btn btn-primary btn-block btn-large" name="submit" value="Log-In">
</br>
And the php code where its getting posted:
<?php
session_start();
$user = $_POST['user'];
$_SESSION['user'] = $user;
define('DB_HOST', 'localhost');
define('DB_NAME', 'mkuiper1');
define('DB_USER','mkuiper1');
define('DB_PASSWORD','password');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) 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($data){
//checking the 'user' name which is from Sign-In.html, is it empty or have some text
if(!empty($data['user'])){
//$query = mysql_query("SELECT * FROM WebsiteUsers where userName = '".$data['user']."' AND pass = '".$data['pass']."'") or die(mysql_error());
// The above query is sql-injecation valnerable query, use the below query instead
// Also do not use mysql erxtension anymore is deprecated, use mysqli instead
// Let us say that your db connection is stored in $con variable
$stmt = $con->prepare("SELECT * FROM WebsiteUsers where userName = '$_POST[user]' AND pass = '$_POST[pass]'");
$stmt->bind_param('ss', $data['user'],$data['pass']);
if($stmt->execute()){
$stmt->store_result();
if($stmt->num_rows>0){
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$_SESSION['userName'] = $row['pass'];
//echo "Login Succesvol!"; do not echo anything here before redirecting !!!
$_SESSION['loggedin'] = 1;
header("Location: index.php");
}
}
}
} else{
$message = "Verkeerde Gebruikersnaam/Wachtwoord!";
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('$message')
window.location = '/Sign-In.php';
</SCRIPT>");
}
}
if(isset($_POST['submit'])){
SignIn($_POST);
}
?>
But it still goes and stays on connectivty.php, even when the pass and username are incorrect.
Sorry for the bad english
Jesse
As I said in my comment, there are many issues with your code, this function should solve them:
function SignIn($data){
//checking the 'user' name which is from Sign-In.html, is it empty or have some text
if(!empty($data['user'])){
//$query = mysql_query("SELECT * FROM WebsiteUsers where userName = '".$data['user']."' AND pass = '".$data['pass']."'") or die(mysql_error());
// The above query is sql-injecation valnerable query, use the below query instead
// Also do not use mysql erxtension anymore is deprecated, use mysqli instead
// Let us say that your db connection is stored in $con variable
$stmt = $con->prepare('SELECT * FROM WebsiteUsers where userName = ? AND pass = ?');
$stmt->bind_param('ss', $data['user'],$data['pass']);
if($stmt->execute()){
$stmt->store_result();
if($stmt->num_rows>0){
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$_SESSION['userName'] = $row['pass'];
//echo "Login Succesvol!"; do not echo anything here before redirecting !!!
$_SESSION['loggedin'] = 1;
header("Location: index.php");
}
}
}
} else{
$message = "Verkeerde Gebruikersnaam/Wachtwoord!";
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('$message')
window.location = '/Sign-In.php';
</SCRIPT>");
}
}
if(isset($_POST['submit'])){
SignIn($_POST);
}
i want to create a login page, display the data from database of particular user in table form upto 4 columns and 1 row and also should be able to update the table data's and then logout. can anyone help me in this with a script. i need it to be done using php, mysql. i have tried till this, but i don't know what to do beyond this.
<html>
<form action="login.php" method="post">
Username: <input type="text" name="username"><p>
Password: <input type="password" name="password"><p>
<input type="submit" value="Log in!" >
</form>
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if ($username&&$password)
{
$connect = mysql_connect("localhost", "root", "") or die("Couldn't connect to the database!");
mysql_select_db("login") or die("Couldn't find database");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if ($numrows!==0)
{
while($row = mysql_fetch_assoc($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password']; # code...
}
if ($username==$dbusername&&$password==$dbpassword)
{
echo "You are logged in!";#
#$_SESSION['usernme'] = $username;
}
else
echo "Your password is incorrect!";
# code...
}
else
die("That user doesn't exists!");
}
else
die("Please enter a username and password!")
?>
Why not directly let MySQL check if the combination of username and password is correct?
$query = mysqli_query("SELECT * FROM users WHERE username='" . $username . "' AND password = '" . $password . "'");
Only if mysqli_num_rows($query) == 1, there is a valid login. More than 1 row should not be possible.
when I enter no data in password and username field then it is working correct it says that "enter data" which is correct but when i enter the data and press sign in it just goes to a blank page no error nothing.After pressing sign in it just shows me a blank page.
php code:-
<?php
$conn_error= 'could not connect to the databse';
$mysql_host= 'localhost';
$mysql_user= 'root';
$mysql_pass= '';
$mysql_db='shubhamyadav';
mysql_connect($mysql_host, $mysql_user, $mysql_pass) or die($conn_error);
mysql_select_db($mysql_db) or die($conn_error);
if(isset($_POST['userName'])&& isset($_POST['pass'])) {
$userName = $_POST['userName'];
$pass = $_POST['pass'];
if (!empty($userName) && !empty($pass)){
$query = "SELECT 'id' FROM 'users' WHERE 'userName' = '$userName' AND 'pass' = '$pass'";
if ($query_run = mysql_query($query)){
$query_num_rows = mysql_num_rows($query_run);
if($query_num_rows == 0){
echo'invalid data';
}elseif($query_num_rows==1){
echo'ok';
}
}
}else{
echo'enter data';
}
}
?>
?>
html code on which i am displaying form:-
<form method="POST" action="connect.inc.php">
UserName<input type="text" name="userName" size="40">
<br>
<br>
Password<input type="password" name="pass" size="40">
<br>
<br>
<input id="button" type="submit" name="submit" value="Sign-In">
</form>
The error is because your MySQL query is wrong. Your query should be like this,
$query = "SELECT `id` FROM `users` WHERE `userName` = '$userName' AND `pass` = '$pass'";
You should use backticks (`) for table and column names, single quotes (') for strings. Backticks are only needed when your table name or column name is a MySQL reserved word, but it's a best practice is to avoid reserved words.
Sidenote: Switch to PDO and using prepared statements, or at least to mysqli rather than mysql.
What is happenning is that a php error occurs, but because it seems your php configuration does not show errors you get that blank page.
Check this link to show errors:
Getting php errors to display
Following Standards will always keep you away from small problems, Replace and try:
$query = "SELECT id FROM users WHERE userName = '".$userName."' AND pass = '".$pass."'";
FOR LOGIN USE THIS TYPE OF QUERY
//DB CONNECTION
<?php
$con = mysqli_connect("localhost","root","","Testify");
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
?>
<?php
//login script
if(isset($_POST['login'])){
$username = trim(htmlspecialchars($_POST['username']));
$password = trim(htmlspecialchars($_POST['password']));
//if username or password is empty
if(empty($username) || empty($password)){
echo "<div class='alert alert-danger'>Fill in all the fields</div>";
exit();
}
//check username and password match the db record
$q = mysqli_query($con,"SELECT id FROM `user` WHERE username='$username' AND password='$password'");
if(mysqli_num_rows($q) != 1){
echo "<div class='alert alert-danger'>Invalid username or password</div>";
exit();
}
//fetch the if of the logged in user start the session
$row = mysqli_fetch_assoc($q);
//set the session with logged in user id
$_SESSION['id'] = $row['id'];
$_SESSION['username'] = $username;
header("Location: index.php");
exit();
}
I am trying to make a simple php and sql login form, but it is not working
Can anyone help me to fix my code?
<form method="post" action="form.php">
Username <input type="text" name="username"><br>
Password <input type="password" name="password">
<br>
<input type="submit" name="submit" value="submit">
</form>
<?php
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$con = mysql_connect("localhost", "root", "");
mysql_select_db($con, "formcolumn");
$sql = mysql_query("select * from data1_table where username='$username' and password='$password' ");
$row = mysql_fetch_array($sql);
$uname = $row['username'];
$pass = $row['password'];
if ($username == $uname && $password == $pass) {
header("Location: main.php");
} else {
echo "invalid username and password ";
}
}
?>
Replace mysql_select_db($con, "formcolumn"); with mysql_select_db("formcolumn",$con); where formcolumn is your Database name
Interchange the positions of your parameters in your mysql_select_db function bass the name of your database first then pass the connection. You must remember this is a predefined function and it is defined to accept parameters in a certain order therefore it expects that the first parameter passed to the function is going to be the database name.
You should have
mysql_select_db("formcolumn",$con);
also why not try something along the lines of this:
$sql = "select * from data1_table where username='$username' and password='$password'";
$result = mysql_query($sql,$con);
$row= mysql_fetch_assoc($result);
I have a username/database that i wanna log into via PHP in the back end - so i created 2 files - one called login.php and the latter called process.php -
here's the code for them both -
login.php:
<form action="process.php" method="POST">
username: <input type="text" name="username"/></br>
password: <input type="password" name="password"/>
<input type="submit" value="Login"/>
</form>
process.php:
<?php
$dbc = mysqli_connect('localhost','root','semen1985*','forum');
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM members WHERE (Email='$username' AND password='$password')'";
$result = mysqli_query($dbc,$query);
if (empty($_POST['password'])) {
$error[] = 'Please Enter Your Password ';
}
if(!$result){
echo 'Query Failed ';
}
if ($result==1){
echo 'Correct Password!!!';
} else {
echo "Wrong Username and/or Password!";
}
?>
Anyways, I seem to be continuously getting the following result - Query Failed Wrong Username and/or Password!
This is even after i attempt multiple correct entries for email/username (same thing) and password...does anyone of u know what the problem is or how i could fix this simple code up?
Your query is wrong
$query = "SELECT * FROM members WHERE (Email='$username' AND password='$password')'";
This query has an extra single quote at the end of the string that is causing the problem.
$query = "SELECT * FROM members WHERE (Email='$username' AND password='$password')";
Keep in mind that this is an insecure way of creating queries. You should look into using parameters for your query. I'm not familiar enough with mysqli to give you an example, , but with PDO you would do something like this:
$sth = $dbh->prepare("SELECT * FROM members WHERE Email=:username AND password=:password");
$sth->bindParam(":username",$username,PDO::PARAM_STR);
$sth->bindParam(":password",$password,PDO::PARAM_STR);
$sth->execute();
<?php
$dbc = mysqli_connect('localhost','root','semen1985*','forum');
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM members WHERE Email='$username' AND password='$password'";
$result = mysqli_query($dbc,$query);
if (empty($_POST['password'])) {
$error[] = 'Please Enter Your Password ';
}
if(!$result){
echo 'Query Failed ';
}
if (count($result)==1){
echo 'Correct Password!!!';
} else {
echo "Wrong Username and/or Password!";
}
?>