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
Related
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 trying to create a register/login html/php script. I created a database and I believe my html/php code is correct. I was wondering if I am missing something small. Here is my code so far.
Here is the database
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'on');
if(isset($_POST["submit"]))
{
$User = "**";
$Password = "**";
$Database = "member";
$Host = "localhost";
$con = mysqli_connect($Host, $User, $Password);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,$Database);
$myusername = $_POST["username"];
$mypassword = $_POST["password"];
$sql = "INSERT INTO member (username, password) VALUES ('$myusername','$mypassword')";
mysqli_query($con,$sql);
mysqli_commit($con);
mysqli_close($con);
echo "Thank You! Information entered.";
}
else
{
?>
<form method="post" action="proInput.php">
Username:<input type="Text" name="username"><br>
Password:<input type="Text" name="password"><br>
<input type="Submit" name="submit" value="Register"></form>
<?
}
?>
Every time I type SELECT * FROM member; in MySQL my database is empty.
mysqli_commit($con);
mysqli_query($con,$sql);
mysqli_close($con);
You're committing before you insert, and then closing an uncommitted transaction. Try swapping the first two lines in the above excerpt.
As you answered already in your comment,
the name of the file isn't main_login.php but proinput.php
Your form is posting it's data to main_login.php and I'm assuming you don't have the insert query on that page, your code isn't run at all.
Options:
Try changing the name of this php file to main_login.php and then instead of the echo redirect the user to the login page
Move this part of the insert to your main_login.php
if(isset($_POST["submit"]))
{
$User = "";
$Password = "";
$Database = "member";
$Host = "localhost";
$con = mysqli_connect($Host, $User, $Password);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,$Database);
$myusername = $_POST["username"];
$mypassword = $_POST["password"];
$sql = "INSERT INTO member (username, password) VALUES ('$myusername','$mypassword')";
mysqli_query($con,$sql);
mysqli_commit($con);
mysqli_close($con);
echo "Thank You! Information entered.";
}
else
{
?>
for debugging add the following to the very top of your php file right after the opening of php
error_reporting(E_ALL);
ini_set('display_errors', 'on');
This worked for me
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'on');
if(isset($_POST["submit"]))
{
$User = "db_user";
$Password = "db_password";
$Database = "db_name";
$Host = "db_host";
$con = mysqli_connect($Host, $User, $Password);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,$Database);
$myusername = $_POST["username"];
$mypassword = $_POST["password"];
$sql = "INSERT INTO member (username, password) VALUES ('$myusername','$mypassword')";
mysqli_query($con,$sql);
mysqli_commit($con);
mysqli_close($con);
echo "Thank You! Information entered.";
}
else
{
?>
<form method="post" action="proinput.php">
Username:<input type="Text" name="username"><br>
Password:<input type="Text" name="password"><br>
<input type="Submit" name="submit" value="Register"></form>
<?php
}
?>
please add 'or die (mysqli_error())' at the end of your query and get the sql error report. That should tell you what is exactly wrong with sql . Php error reporting will only give php errors.
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
Customer will complete a form and enter a pathway where they will want the CSV to be exported to. The pathway is entered using the top section of the php (below):
<form action="register.php" method="post">
Enter file pathway where CSV will be saved: <input type="text" name="username" required="required"/> <br/>
<input type="submit" value="Enter"/>
</form>
</body>
I want to create a variable called pathway. At the moment I can get text entered into the correct row in the mysql database (I can get John printed in the database), but not the correct text that was entered into the form (i.e. $pathway).
I want to create a variable because after saving the pathway in the database i also want to use it in an export.php.
I am assuming i also need something like this:
if($_SERVER["REQUEST_METHOD"] == "POST"){
$pathway = mysql_real_escape_string($_POST['pathway']);
// but i can't seem to piece it altogether.
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "first_db";
$table_users = $row['pathway'];
$pathway = "pathway";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO users (pathway)
VALUES ('John')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
This shoud work, if not then check your usename and password...
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "first_db";
$pathway = $_POST['username']; username - is the name of your input.
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO users (pathway)
VALUES ('$pathway')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
your DB username is Null
Change $username = ""; to $username = "root";
Your input field name is username
change it to pathway for $_POST['pathway'] to work
<form action="register.php" method="post">
Enter file pathway where CSV will be saved:
<input type="text" name="pathway" required="required"/> <br/>
<input type="submit" value="Enter"/>
</form>
First of all, you've got 'username' as the name of the field using for type a pathway, so rename it to 'pathway'.
I don't know if I understand you, but do you just want to read posted content?
Try something like:
$pathway = $_POST['pathway']
I strongly recommend to use object-oriented style with
$conn = new mysqli...
and then
mysqli->prepare(), mysqli->bind_param(), mysqli->execute()
With this you won't have to deal with mysqli_real_escape_string etc.
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>";
}