Good day! I'm trying to connect my code to the database localhost/phpmyadmin.
This is my code:
In register.php file:
<?php
session_start();
require_once('dbconfig/config.php');
//phpinfo();
?>
config.php is file where the database name was located
<!DOCTYPE html>
<html>
<head>
<title>Registration Page</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body style="background-color:#bdc3c7">
<div id="main-wrapper">
<center><h2>Registration Form</h2></center>
<form action="register.php" method="post">
<div class="imgcontainer">
<img src="imgs/avatar.png" alt="Avatar" class="avatar">
</div>
<div class="inner_container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<label><b>Confirm Password</b></label>
<input type="password" placeholder="Enter Password" name="cpassword" required>
<button name="register" class="sign_up_btn" type="submit">Sign Up</button>
<button type="button" class="back_btn"><< Back to Login</button>
</div>
</form>
<?php
if(isset($_POST['register']))
{
#$username=$_POST['username'];
#$password=$_POST['password'];
#$cpassword=$_POST['cpassword'];
if($password==$cpassword)
{
$query = "select * from userinfotbl where username='$username'";
//echo $query;
$query_run = mysqli_query($con,$query);
//echo mysql_num_rows($query_run);
if($query_run)
{
if(mysqli_num_rows($query_run)>0)
{
echo '<script type="text/javascript">alert("This Username Already exists.. Please try another username!")</script>';
}
else
{
$query = "insert into userinfotbl values('$username','$password')";
$query_run = mysqli_query($con,$query);
if($query_run)
{
echo '<script type="text/javascript">alert("User Registered.. Welcome")</script>';
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header( "Location: homepage.php");
}
else
{
echo '<p class="bg-danger msg-block">Registration Unsuccessful due to server error. Please try later</p>';
}
}
}
else
{
echo '<script type="text/javascript">alert("DB error")</script>';
}
}
This line where error occurs. But i don't know exactly what happened.
else
{
echo '<script type="text/javascript">alert("Password and Confirm Password do not match")</script>';
}
}
else
{
}
?>
</div>
</body>
</html>
However in localhost page i got an error saying "Localhost says: DB Error"
I don't know what's wron with it.
It means that the "select * from userinfotbl where username='$username'" query do not found any entities which would match a condition or got an error.
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will return a mysqli_result object. For
other successful queries mysqli_query() will return TRUE.
http://php.net/manual/en/mysqli.query.php
Use mysqli_error to see what an error you got.
Example:
if($password==$cpassword)
{
$query = "select * from userinfotbl where username='$username'";
//echo $query;
$query_run = mysqli_query($con,$query);
//echo mysql_num_rows($query_run);
if(!empty($query_run)) {
...
} elseif ($query_run === false)
echo mysqli_error($con);
else
echo '<script type="text/javascript">alert("DB error")</script>';
}
you must use mysqli_error to check if there is an error in connection or query error
Related
<?php
session_start();
require_once('dbconfig/config.php');
//phpinfo();
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body style="background-color:#bdc3c7">
<div id="main-wrapper">
<center><h2>Login Form</h2></center>
<div class="imgcontainer">
<img src="imgs/avatar.png" alt="Avatar" class="avatar">
</div>
<form action="index.php" method="post">
<div class="inner_container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<button class="login_button" name="login" type="submit">Login</button>
<button type="button" class="register_btn">Register</button>
</div>
</form>
<?php
if(isset($_POST['login']))
{
#$username=$_POST['username'];
#$password=$_POST['password'];
#$date=$_POST[date('Y-m-d')];
$query = "select * from userinfotbl where username='$username' and password='$password' ";
$query1="insert into userinfotbl values('$date')";
//echo $query;
$query_run = mysqli_query($con,$query);
$query_run1 = mysqli_query($con,query1);
//echo mysql_num_rows($query_run);
if($query_run)
{
if(mysqli_num_rows($query_run)>0)
{
$row = mysqli_fetch_array($query_run,MYSQLI_ASSOC);
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header( "Location: homepage1.php");
}
else
{
echo '<script type="text/javascript">alert("No such User exists. Invalid Credentials")</script>';
}
}
else
{
echo '<script type="text/javascript">alert("Database Error")</script>';
}
}
else
{
}
?>
</div>
</body>
</html>
The date field in my database is getting filled with 0000-00-00.where i need to insert that field with the system date when the user clicks on login button.I am unable to detect the problem.I have a variable $date to which i am assigning the function date('Y-m-d').
In Place of #$date=$_POST[date('Y-m-d')] use #$date = date('Y-m-d H:i:s');
Select datatype DATETIME in Mysql database field.
<?php
if(isset($_POST['login']))
{
#$username=$_POST['username'];
#$password=$_POST['password'];
//#$date=$_POST[date('Y-m-d')];
#$date = date('Y-m-d H:i:s');
$query = "select * from userinfotbl where username='$username' and password='$password' ";
$query1="insert into userinfotbl values('$date')";
//echo $query;
$query_run = mysqli_query($con,$query);
$query_run1 = mysqli_query($con,query1);
//echo mysql_num_rows($query_run);
if($query_run)
{
if(mysqli_num_rows($query_run)>0)
{
$row = mysqli_fetch_array($query_run,MYSQLI_ASSOC);
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header( "Location: homepage1.php");
}
else
{
echo '<script type="text/javascript">alert("No such User exists. Invalid Credentials")</script>';
}
}
else
{
echo '<script type="text/javascript">alert("Database Error")</script>';
}
}
?>
Hi you only need to change the date datatype to timestamp and set default CURRENT_TIMESTAMP.
This will automatically add date value column and you don't need to provide date for that in query.
Replace
#$date=$_POST[date('Y-m-d')];
with
$date=date('Y-m-d');
I have this script sign in first with sql insert into query and redirected to login page. I checked all my queries on phpmyadmin. All queries are working. I do not have any error message in my query. Also it is suppose to show " password/username does not match" message if there is incorrect user/password. After i submit form, the page did not redirect to welcome page and form field clears.
this is my login page
<?php
require_once "./include/variables.inc.php";
$debug =0;
$error_text = "";
$uname = "";
$pwd = "";
session_start();
if (!isset($_SESSION['member_id'])){
if(isset($_POST["submit"])) {
if($debug) {
echo "<pre>";
print_r($_POST);
echo "</pre>";
//die("temp stop point");
}//end ofdebug if
$uname = mysqli_real_escape_string($dbc,trim($_POST['uname']));
$pwd = mysqli_real_escape_string($dbc,trim($_POST['pwd']));
if (!empty($uname) && !empty($pwd)) {
$query = "SELECT * FROM employees WHERE username = '".$uname."'
AND password = '".MD5($pwd)."'";
echo $query;
$result = mysqli_query($dbc,$query) or die ("Error in query". mysql_error());
if(mysqli_num_rows($result)) {
$row = mysqli_fetch_assoc($result);
$_SESSION['member_id'] = $row['member_id'];
$_SESSION['member_name'] = $row['member_name'];
header('Location:index.php');
}
else {
$error_text .= "The username/password are incorrect. Please enter correct username and password.";
}
}
}//end of if(isset($_POST["submit"])
}
require_once('./include/html.head.php');
?>
<body>
<div id="wrapper">
<?php require_once('./include/header.php'); ?>
<div id="side">
<?php require_once('./include/pb.side.php'); ?>
</div>
<div id="content">
<div class="form">
<p class="strong">All Santa helpers log-in here.</p>
<?= $error_text ?>
<form method="post" action="<?= $_SERVER['PHP_SELF'] ?>" enctype="multipart/form-data">
<p>User Name: <input name="uname" type="text" value="<?= $uname ?>"></p>
<p>Password: <input name="pwd" type="password"></p>
<input name="submit" type="submit" value="Login">
</form>
</div>
<div class="rdeer">
<img src="images/login_img.png" alt="Rain Deer">
</div>
</div>
<?php require_once('./include/footer.php'); ?>
</div>
</body>
</html>
and function php is
<?php
function user_authenticated($username, $password) {
if(!empty($username) && !empty($password)) {
$query = "SELECT userName, password FROM employees WHERE userName = '".$username."' and password = '".$password."'";
$result= mysqli_query($dbc, $query)
or die ("Query does not work." . mysql_error());
// If result matched $username and $password, table row must be 1 row
} else {
echo "Query error. ";
}
}
Notice the line mysqli_num_rows($result). Replace it with mysqli_num_rows($result)>0 since that function returns an int.
I'm a beginner at php and I have created a simple login system with php and mysqli for my website however my code wont validate such as "username doesnt exist" and im not sure how to make the account for the user so that it is individual. My code is in 3 files and all linked. connection.php contains session_star(); and connection to the database
Homepage.php - what the form appears on
<?php
include 'login.php';
?>
<section>
<img id="image1" src="homepic.jpg" alt="logo" />
</section>
loginform.php
<link rel="stylesheet" href="homecss.css"/>
<div id="form">
<h2>Login</h2>
<form method="post" action="loginSubmit.php">
User Name: <br/>
<input type="name" name="username" type="text" /><br />
Password: <br/>
<input id="password" name="password" type="password" /><br />
<input type="submit" name="logsubmit" value="Login" />
</form></div>
login.php
<link rel="stylesheet" href="homecss.css"/>
<?php
include './connection.php';
?>
<div id="form">
<?php
if(!isset($_SESSION['authenticatedusername'])){
include './loginform.php';
if (!empty($_POST['username'])) {
echo "Username is required";
}
if (!empty($_POST['password'])) {
echo "Password is required";
}
}
else{
echo 'welcome '. $_SESSION['authenticatedusername'];
echo '<br/> logout ';
echo '<br/> My account ';
//check to see if error message is to be displayed
if (isset($_SESSION['message'])){
echo $_SESSION['message']="login failed";
}
?>
</div>
loginSubmit.php
<?php
include "connection.php";
if(isset($_POST['logsubmit'])){
$user=$_POST['username'];
$pass=$_POST['password'];
$query= "SELECT * FROM users WHERE user_name='$user' AND user_password='$pass'";
$result=mysqli_query($connection, $query);
if ($row = mysqli_num_rows($result) >0){
$_SESSION['authenticatedusername']=$user;
header ("Location: homepage.php");
} else{
echo $_SESSION['message'];
header("Location: homepage.php");
}
}
?>
You are taking wrong condition on empty()
if (!empty($_POST['username'])) { // If username is filled, you are showing error.
echo "Username is required";
}
if (!empty($_POST['password'])) { // If password is filled, you are showing error.
echo "Password is required";
}
Should be
if (empty($_POST['username'])) { // If username is not filled, show error.
echo "Username is required";
}
if (empty($_POST['password'])) { // If password is not filled, show error.
echo "Password is required";
}
This code shall find the error in your MySQL query, as it points there. The error may be caused by unescaped user and pass variables or typo in field name... whatever, it will show you.
<?php
include "connection.php";
if(isset($_POST['logsubmit'])){
$user=mysqli_real_escape_string($connection, $_POST['username']);
$pass=mysqli_real_escape_string($connection, $_POST['password']);
$query= "SELECT * FROM users WHERE user_name='$user' AND user_password='$pass'";
if (!$result=mysqli_query($connection, $query)) {
echo "<div>$query</div>"; //this outputs your query as sent to MySQL
echo "<div>".mysqli_error($connection)."</div>"; // this will output the mysql error
}
if ($row = mysqli_num_rows($result) >0){
$_SESSION['authenticatedusername']=$user;
header ("Location: homepage.php");
} else{
echo $_SESSION['message'];
// header("Location: homepage.php"); //disabled to see the error
}
}
?>
Homepage
We have a login page which validates the username and password from our database, however we'd like it to display the invalid username and password message above the input fields rather than at the top of the page. We know we can edit and put the php code in the div to display it where it is, we put out headers and therefore as soon as we move the php from the top of the page it generates an error message. Is there an alternative to this? Or a way of using the headers differently? Our code is below and an image of what we want...
<?php
error_reporting (E_ALL ^ E_NOTICE);
$username = $_POST['usrname'];
$pass_word = $_POST['pass_word'];
if(($usrname=="")&&($pass_word==""))
{
//Do nothing as nothing has been posted......
}
else
{
$con = mysql_connect("localhost"," "," ");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("", $con);
$result = mysql_query("SELECT * FROM `leicester_login` WHERE `user_name`='$username'", $con);
$num_row = mysql_num_rows($result);
}
if($username=="")
{
//do nothing as nothing has been posted
}
else
{
if($num_row == 0)
{
echo "<p>The username <b>". $username ."</b> doesnt exist!</p>";
}
else
{
$return_pass = mysql_fetch_array($result);
if($pass_word == $return_pass['pass_word'])
{
session_start();
if(isset($_SESSION['username']))
{
//do nothing as session already exists...
header("Location: ");
}
else
{
$_SESSION['username']= $username;
header("Location: ");
exit;
}
}
else
{
echo "<p>The password entered is incorrect!</p>";
}
}
}
?>
<html lang="en">
<head>
</head>
<body>
<div class="container">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post" class="form-signin">
<h2 class="form-signin-heading"><img src="" alt="Logo"/>Leicester</h2>
<?php
?>
<h6 class="form-signin-heading">You are not logged in, please login.</h6>
<input name="usrname" id="usrname" type="text" class="input-block-level" placeholder="Username">
<input type="password" name="pass_word" id="pass_word" class="input-block-level" placeholder="Password">
<center><button align="center" class="btn btn-large btn-primary" type="submit">Sign in</button></center>
< Go Back
</form>
</div> <!-- /container -->
</body>
</html>
Your if statement is wrong [There is no such $usrname variable on your code]
if(($usrname=="")&&($pass_word==""))
should be
if(($username=="")&&($pass_word==""))
Try this:
<?php
error_reporting (E_ALL ^ E_NOTICE);
$username = $_POST['usrname'];
$pass_word = $_POST['pass_word'];
if(($usrname=="")&&($pass_word==""))
{
//Do nothing as nothing has been posted......
}
else
{
$con = mysql_connect("localhost"," "," ");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("", $con);
$result = mysql_query("SELECT * FROM `leicester_login` WHERE `user_name`='$username'", $con);
$num_row = mysql_num_rows($result);
}
if($username=="")
{
//do nothing as nothing has been posted
}
else
{
$message = null; //create a container for the messages
if($num_row == 0)
{
$message = "<p>The username <b>". $username ."</b> doesnt exist!</p>";
}
else
{
$return_pass = mysql_fetch_array($result);
if($pass_word == $return_pass['pass_word'])
{
session_start();
if(isset($_SESSION['username']))
{
//do nothing as session already exists...
header("Location: ");
}
else
{
$_SESSION['username']= $username;
header("Location: ");
exit;
}
}
else
{
$message = "<p>The password entered is incorrect!</p>";
}
}
}
?>
<html lang="en">
<head>
</head>
<body>
<div class="container">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post" class="form-signin">
<h2 class="form-signin-heading"><img src="" alt="Logo"/>Leicester</h2>
<?php
//if there's something in the container, echo it out.
if (!is_null($message)) {
echo $message;
}
?>
<h6 class="form-signin-heading">You are not logged in, please login.</h6>
<input name="usrname" id="usrname" type="text" class="input-block-level" placeholder="Username">
<input type="password" name="pass_word" id="pass_word" class="input-block-level" placeholder="Password">
<center><button align="center" class="btn btn-large btn-primary" type="submit">Sign in</button></center>
< Go Back
</form>
</div> <!-- /container -->
</body>
</html>
Whenever echo is called it will output something right there, if it's before any output (like the html part), itt will show up before the HTML starts. If you put something in a container (like the $message) and output it with the html it will show up in the predestined place. As a side effect, the header("Location: "); will not throw headers already sent errors.
I recommend using Javascript:
If you place a span in the logindiv at the place you want. e.g. that span has an id of 'errormessage'. Now you can use Javascript to place the message in the span.
HTML:
<h6 class="form-signin-heading">You are not logged in, please login.</h6>
<span id="errormessage"></span>
<input name="usrname" id="usrname" type="text" class="input-block-level" placeholder="Username">
PHP:
//an error has occurred...
echo "<script>document.getElementById('errormessage').innerHTML='The password entered is incorrect!'</script>";
A benefit of using a span is that you can edit the layout of the errormessage using CSS.
I hope this is an answer to your question.
It's outputting it up top because that is where you are telling it to output - before the actual start of the HTML. One way to solve it is to save the string to display in a variable, and then display the variable at the proper place in your HTML.
I am currently working on my own CMS.
It seems like it doesn't accept my login details for some reason... The codes are:
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
// display index
} else {
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
if (empty($username) or empty($password)){
$error = 'Please enter all of the fields!';
} else {
$query = $pdo->prepare("SELECT * FROM users WHERE user_name = ? AND user_password = ?");
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->execute();
$num = $query->rowCount();
if ($num == 1) {
// user entered correct
$_SESSION['logged_in'] = true;
header('Location: index.php');
exit();
} else {
//user entered false
$error = "Incorrect details!";
}
}
}
?>
<html>
<head>
<title>CMS</title>
<link rel="stylesheet" type="text/css" href="../assets/style.css" />
</head>
<body>
<div class="container">
CMS
<br /><br />
<?php if (isset($error)) { ?>
<small style="color:#aa0000;">
<?php echo $error; ?>
<br /><br />
</small>
<?php } ?>
<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Login" />
</form>
</div>
</body>
</html>
<?php
}
?>
And the connection are:
> <?php
>
> try { $pdo = new PDO('mysql:host=localhost;dbname=website', 'root',
> ''); } catch (PDOException $se) { exit('Database error.'); }
>
>
> ?>
Every time i try to login with the correct details it just says ''Incorrect Details''
Any ideas?
You are checking if the query returned a result. However the way you do it is not for SELECT queries. It's used for e.g. deletes.
Try this instead:
<?php
if ($res = $conn->query($sql))
{
if ($res->fetchColumn() > 0)
{
// user entered correct
}
else
{
//user entered false
}
}
More information about this can be found in the PHP Manual.
I want to add this quote from the manual:
For most databases, PDOStatement::rowCount() does not return the
number of rows affected by a SELECT statement. Instead, use
PDO::query() to issue a SELECT COUNT(*) statement with the same
predicates as your intended SELECT statement, then use
PDOStatement::fetchColumn() to retrieve the number of rows that will
be returned. Your application can then perform the correct action.