PHP Creating dynamic WHERE clause [duplicate] - php

<?php
require_once("connect.php");
$login1 = $_POST['email'];
$password1 = $_POST['password'];
$select = "SELECT id FROM loginregistration WHERE login ='$login1', password ='$password1'";
$sql = mysqli_query($con,$select);
$row = mysqli_fetch_assoc($sql);
?>`
it seems that my mysqli_query doesn't work ,what should i do?

use AND insted of comma (,) in query near password that's why query returning false and throw that error
$select = "SELECT id FROM loginregistration WHERE login ='".$login1."' and password ='".$password1."'";
UPDATE 1
if query fail it return false . so you can use mysqli_error($con); to know the error
<?php
require_once("connect.php");
$login1 = $_POST['email'];
$password1 = $_POST['password'];
$select = "SELECT id FROM loginregistration WHERE login ='".$login1."' AND password ='".$password1."'";
$sql = mysqli_query($con,$select);
if($sql === FALSE) {
die(mysqli_error($con)); // better error handling
}
$row = mysqli_fetch_assoc($sql);
?>

Related

How to fetch data from two different tables in sql with single login form

I made two tables in SQL. first is login table and second is registration table. In login table I inserted a row of user admin and password admin, it works when I am logging in. But now I want to login from registration table. I means if an already registered user want to login how he can did it???
Following is my code, please help me.
when I trying to login as registered user it show me the error "invalid username or password":
<?php
include('../dbcon.php'); //Database connection included
if (isset($_POST['login'])) {
$username = $_POST['uname']; //data of login table in sql
$password = $_POST['password'];
$qry = "SELECT * FROM `login` WHERE `uname`='$username' AND `password`='$password' ";
$run = mysqli_query($dbcon,$qry);
$row = mysqli_num_rows($run);
if ($row<1)
{
echo "invalid usernaem or password";
}
else
{
$data = mysqli_fetch_assoc($run);
$id = $data['id'];
echo "Your Id is " .$id;
}
}
else
{
if (isset($_POST['login'])) { //for the data of registraion table in sql
$username = $_POST['uname'];
$password = $_POST['password'];
$qry = "SELECT * FROM `registration` WHERE `uname`= '$username' OR `email`='$email' AND `password` = '$password' ";
$run = mysqli_query($dbcon,$qry);
$row = mysqli_num_rows($run);
if ($row<1)
{
echo "password is incorrect";
}
else
{
$data = mysqli_fetch_assoc($run);
$id = $data['id'];
echo "Your Id is " .$id;
}
}
}
?>
You need to query the registration table when the login query doesn't find anything.
<?php
include('../dbcon.php'); //Database connection included
if (isset($_POST['login'])) {
$username = $_POST['uname']; //data of login table in sql
$password = $_POST['password'];
$qry = "SELECT * FROM `login` WHERE `uname`='$username' AND `password`='$password' ";
$run = mysqli_query($dbcon,$qry);
$row = mysqli_num_rows($run);
if ($row<1)
{
// not an admin, check registration table
$email = $_POST['email'];
$qry = "SELECT * FROM `registration` WHERE (`uname`= '$username' OR `email`='$email') AND `password` = '$password' ";
$run = mysqli_query($dbcon,$qry);
$row = mysqli_num_rows($run);
if ($row<1)
{
echo "password is incorrect";
}
else
{
$data = mysqli_fetch_assoc($run);
$id = $data['id'];
echo "Your Id is " .$id;
}
}
else
{
$data = mysqli_fetch_assoc($run);
$id = $data['id'];
echo "Your Id is " .$id;
}
}
?>
You should also learn to use prepared statements instead of substituting variables into SQL, to protect against SQL-injection. See How can I prevent SQL injection in PHP?. And you should use password_hash() and password_verify() instead of storing plaintext passwords in the database.

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in

<?php
require_once("connect.php");
$login1 = $_POST['email'];
$password1 = $_POST['password'];
$select = "SELECT id FROM loginregistration WHERE login ='$login1', password ='$password1'";
$sql = mysqli_query($con,$select);
$row = mysqli_fetch_assoc($sql);
?>`
it seems that my mysqli_query doesn't work ,what should i do?
use AND insted of comma (,) in query near password that's why query returning false and throw that error
$select = "SELECT id FROM loginregistration WHERE login ='".$login1."' and password ='".$password1."'";
UPDATE 1
if query fail it return false . so you can use mysqli_error($con); to know the error
<?php
require_once("connect.php");
$login1 = $_POST['email'];
$password1 = $_POST['password'];
$select = "SELECT id FROM loginregistration WHERE login ='".$login1."' AND password ='".$password1."'";
$sql = mysqli_query($con,$select);
if($sql === FALSE) {
die(mysqli_error($con)); // better error handling
}
$row = mysqli_fetch_assoc($sql);
?>

PHP choose another username

I have made a registration PHP file that runs through an authentication and connects to my database that I made in phpMyAdmin. The problem is, I can put in the same username without consequence and it adds to the database, so I could put; dogs as the username and then again put the same.
How can I make it so the user is told; that username already exists choose another one.
Here's my php so far;
Also please tell me where to insert it.
<?php
require('db.php');
// If form submitted, insert values into the database.
if (isset($_POST['username'])) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$username = stripslashes($username);
$username = mysql_real_escape_string($username);
$email = stripslashes($email);
$email = mysql_real_escape_string($email);
$password = stripslashes($password);
$password = mysql_real_escape_string($password);
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysql_query($query);
if ($result) {
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
} else {
?>
You should query the database before inserting any record (user) to users table.
Try the code below:
<?php
$username = mysql_real_escape_string( $username ); //Sql injection prevention
$existance = mysql_query("SELECT username FROM users WHERE username = '" . $username . "'");
if( !$existance ){
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysql_query( $query );
if ( $result ) {
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
else{
//unsuccessful insertion
}
} else {
//the user existed already, choose another username
}
?>
Create an if-statement where you check if $username exists in the db. If it does, throw an error. If not, continue with the code.
Note
Your code is vulnerable to SQL-injection. Read this post: How can I prevent SQL injection in PHP?
Rewriting my entire answer to a working example. I'm going to assume your post variables are the same as mine: email, password, username
<?php
$errorMessage = "";
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
$email = $_POST['email'];
$password = $_POST['password'];
$username = $_POST['username'];
$email1 = $_POST['email'];
$username1 = $_POST['username'];
$password1 = $_POST['password'];
$email = htmlspecialchars($email);
$password = htmlspecialchars($password);
$username = htmlspecialchars($username);
$connect = mysql_connect("localhost","DBuser", "DBpassword");
if (!$connect) {
die(mysql_error());
}
mysql_select_db("DBName");
$results = mysql_query("SELECT * FROM users WHERE username = '$username'");
while($row = mysql_fetch_array($results)) {
$kudots = $row['username']; }
if ($kudots != ""){
$errorMessage = "Username Already Taken";
$doNothing = 1;
}
$result = mysql_query("SELECT * FROM users WHERE email = '$email'");
while($row2 = mysql_fetch_array($results)) {
$kudots2 = $row2['email']; }
if ($kudots2 != ""){
$errorMessage = "Email Already in use";
$doNothing = 1;
}
//test to see if $errorMessage is blank
//if it is, then we can go ahead with the rest of the code
//if it's not, we can display the error
if ($errorMessage == "") {
$user_name = "DBUsername";
$pass_word = "DBPassword";
$database = "DBName";
$server = "localhost";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$email = quote_smart($email, $db_handle);
$password = quote_smart($password, $db_handle);
$username = quote_smart($username, $db_handle);
if ($username1 == ""){
$errorMessage = "You need a username";
}
if ($password1 == ""){
$errorMessage = $errorMessage . "<br>You need a password.";
}
if (!(isset($_POST['email']))){
$errorMessage = $errorMessage . "<br>You need an email.";
}
$SQL = "SELECT * FROM users WHERE email = $email";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$errorMessage = "email already exists";
$doNothing = 1;
}
if ($errorMessage == "") {
$SQL = "INSERT INTO users (email, username, password) VALUES ($email, $username, $password)";
$result = mysql_query($SQL);
mysql_close($db_handle);
//=================================================================================
// START THE SESSION AND PUT SOMETHING INTO THE SESSION VARIABLE CALLED login
// SEND USER TO A DIFFERENT PAGE AFTER SIGN UP
//=================================================================================
session_start();
$_SESSION['email'] = "$email1";
$_SESSION['password'] = "$password1";
header ("Location: myaccount.php");
else {
$errorMessage = "Database Not Found";
}
}
OK, now echo $errorMessage right below or above the form, to inform the user that the Email, or Username is taken. I'm pretty sure I have a duplicate function in here for the Email, but this code does work; disregard if somebody says it's vulnerable to SQL injection; this is a working EXAMPLE! If you want to do MySQL real escape string, just Google it. I had to rewrite a couple things because I don't want my full code on a public board, if for some odd reason this doesn't work; send me an eMail(canadezo121#gmail.com) and I'll send you the full page code. (Which WORKS!) This code will probably raise some concerns with other more professional coders, this example gives you a good logical viewpoint of what goes on and how it works. You can adjust it to MySQLi, PDO, etc as you get more familiar with PHP and MySQL.
1 you must verify if the username all ready exists in database (Select)
2 if not exists after you can insert the new user

How to make safe login script

I am trying to make login script safe to stop hacking of my website. I am trying to use mysql_real_escape_string in my script can anyone guide me if i am wrong in this.
Here is my code
<?php
session_start();
include("lib/conn.php");
?>
<?php
$email=$_POST['user'];
$password=$_POST['password'];
if ($email && $password){
$query = "SELECT * FROM register WHERE email = '$email' AND password= '$password' and status = '1'";
mysql_real_escape_string($email);
mysql_real_escape_string($password);
$result = mysql_query( $query ) or die ("didn't query");
$num = mysql_num_rows( $result );
if ($num == 1){
$_SESSION['ocer']=$email;
header("Location: admin.php");
}
else {
header("Location: index.php?l=1");
}
}
?>
1.- Don't use mysql* functions because are deprecated, use mysqli_* functions or PDO
2.- You should use prepared statements, this is an example using mysqli_* functions:
<?php
$email=$_POST['user'];
$password=$_POST['password'];
if ($email && $password){
$query = "SELECT email, password
FROM register
WHERE email = ?
AND password= ?
AND status = '1'";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($stmt, 'ss', $email, $password);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $column1, $column2);
while (mysqli_stmt_fetch($stmt)) {
echo "Column1: {$column1}, Column2: {$column2}";
}
?>
First of all. Use PDO with bind parameter. Then you don't have to worry about injections.
mysql_real_escape_string returns the escaped string and should be used before constructing your query. Use is as so:
$password = mysql_real_escape_string($password);
Also. Don not retrieve by password and email. retrieve password by email and validate that there the same.
Hope it helps
Here is the example:
session_start();
include("lib/conn.php");
//using isset to avoid warnings.
$email = isset($_POST['user']) ? $_POST['user'] : null;
$password = isset($_POST['password']) ? $_POST['password'] : null;
//check if values are not null
if ($email !== null && $password !== null){
//escape email
$email = mysql_real_escape_string($email);
//retrieve password by email and limit 1 result
$query = "SELECT password FROM register WHERE email = '{$email}' and status = '1' LIMIT 1";
//run query
$result = mysql_query( $query ) or die ("didn't query");
//validate if query run correctly
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
//fetch row
$row = mysql_fetch_row($result);
//validate result
if ($row['password'] == $password){
$_SESSION['ocer']=$email;
header("Location: admin.php");
} else {
header("Location: index.php?l=1");
}
}

Updating User Information using SQL query

Updated code, after information is typed in and the submit button clicked to run this code, it goes back to the account page but doesnt update the database:
<font face="ClearSans-Thin">
<font color="lightgray">
<?php
include 'editaccount.php';
include 'connection.php';
?>
<center>
<?php
if (isset($_POST['uregsubmit'])) {
$firstname = $_POST['ufirstname'];
$lastname = $_POST['ulastname'];
$email = $_POST['uemail'];
$dob = $_POST['udob'];
$user = $_POST['uregisterusername'];
$pass = $_POST['uregisterpassword'];
}
//the query
$query = "UPDATE Users SET FirstName='$firstname', LastName='$lastname' WHERE Username='$user'";
//execute the query
$result = mysqli_query($connection, $query)
or die("Error: ".mysqli_error($connection));
//check and see if any data returned
?>
</center>
Write sql query inside if statement
<?php
if (isset($_POST['uregsubmit'])) {
$firstname = $_POST['ufirstname'];
$lastname = $_POST['ulastname'];
$email = $_POST['uemail'];
$dob = $_POST['udob'];
$user = $_POST['uregisterusername'];
$pass = $_POST['uregisterpassword'];
//the query
$query = "UPDATE Users SET FirstName='$firstname', LastName='$lastname' WHERE Username='$user'";
//execute the query
$result = mysqli_query($connection, $query)
or die("Error: ".mysqli_error($connection));
//check and see if any data returned
}
?>
you have an extra comma before WHERE

Categories