SELECT * FROM multiple column - php

I am absolute beginner in creating database and
I only know that we can use,
"SELECT * FROM users WHERE username = '$username' and password = '$password'";
but, what if there is multiple table in my SQL and I want to select them all?
can I just do,
"Select * from users where username = '$username' and password = '$password' and email = '$email' and address = '$address' and phone = '$phone'";
Here are my PHP script:
public function does_user_exist($username,$password,$email,$address,$phone){
$query = "Select * from users where username = '$username' and password = '$password' and email = '$email' and address = '$address' and phone = '$phone'";
$result = mysqli_query($this->connection, $query);
if(mysqli_num_rows($result) > 0){
$json['success'] = 'Welcome '.$email;
echo json_encode($json);
mysqli_close($this->connection);
} else {
$query = "Insert into users(username, password, email, address, phone) values ('$username','$password','$email', '$address', '$phone')";
$is_inserted = mysqli_query($this->connection, $query);
if ($is_inserted == 1){
$json['success'] = 'Account created, welcome '.$email;
} else {
$json['error'] = 'Wrong password ';
}
echo json_encode($json);
mysqli_close($this->connetion);
}
}
UPDATE
<?php
require_once 'connection.php';
header('Content-Type: application/json');
class User {
private $db;
private $connection;
function __construct() {
$this->db = new DB_Connection();
$this->connection = $this->db->get_connection();
}
public function does_user_exist($username,$password,$email,$address,$phone){
$query = ("Select * from users where username = '$username' and password = '$password' and email = '$email' and address = '$address' and phone = '$phone'");
$result = mysqli_query($this->connection, $query);
if(mysqli_num_rows($result) > 0){
$json['success'] = 'Welcome '.$email;
echo json_encode($json);
mysqli_close($this->connection);
} else {
$query = "Insert into users(username, password, email, address, phone) values ('$username','$password','$email', '$address', '$phone')";
$is_inserted = mysqli_query($this->connection, $query);
if ($is_inserted == 1){
$json['success'] = 'Account created, welcome '.$email;
} else {
$json['error'] = 'Wrong password ';
}
echo json_encode($json);
mysqli_close($this->connetion);
}
}
}
$user = new User();
if (isset($_POST['username'], $_POST['password'], $_POST['email'], $_POST['address'], $_POSt['phone'])){
$username = $POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$address = $_POST['address'];
$phone = $_POST['phone'];
if(!empty($username) && !empty($password) && !empty($email) && !empty($address) && !empty($phone)){
$encrypted_password = md5($password);
$user -> does_user_exist($username,$encrypted_password,$email,$address,$phone);
} else {
echo json_encode("You must fill all fields!")
}
}
?>
Hopefully you guys can help, I really appreciate the answers.

You have to use JOIN Queries. Try the below SQL Statement
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_field = table2.common_field;
Refer this JOIN SQL SO Answers
What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?
Difference in MySQL JOIN vs LEFT JOIN
Mysql join query

Generally speaking you will want to use JOIN to do this, and you will need to have values in common between your tables, which act as foreign keys, referencing corresponding values in other tables.
EDIT
Updates to the question and comments indicate that the original question was slightly misphrased. Yes, you can absolutely reference/use/compare/evaluate numerous columns in a single query. The example you posted is a good example:
SELECT (column1, column2) FROM users WHERE username = $username AND email = $email
And so on, for as many columns as the table has. You can also use the OR operator, which has the effect of including any row that matches on username OR on email (or whatever other columns you like).

Related

check if the email is already in database when creating a new acount

So i want to check if the email is already in database when creating a new account but i do not know how to make it work , because i am a beginner in php
<?php
if (isset($_POST["register"]))
{
include 'header.php';
$firstName = $connection->real_escape_string($_POST["firstName"]);
$email = $connection->real_escape_string($_POST["email"]);
$password = sha1($connection->real_escape_string($_POST["password"]));
$sql = "SELECT * FROM users WHERE email LIKE '%$email%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if($queryResult >0)
echo"Email already exists";
else
{
$connection = new mysqli('mysql.hostinger.com', 'xxx', 'xxx', 'xxx');
$data = $connection->query("INSERT INTO users (username, email, password) VALUES ('$firstName', '$email', '$password')");
if ($data === false)
echo "Eroare!";
else
header( 'Location:http://alergii-help.tk/account/login.php');
}}
?>
<input type="submit" class="login100-form-btn" name="register" value="Inregistrare" required />
i don't know what is not working
the table is caled "article"
Why don't you add a unique constraint for email in the table using below query?
ALTER TABLE USERS ADD CONSTRAINT UNQ_EML UNIQUE (EMAIL)
If your code tries to insert an already existing email, then MySQL will throw such duplicate data exception while inserting and you can easily catch it and identify. Below is pseudo code to check.
if( mysql_errno() == 1062) {
// Duplicate key
} else {
// Non duplicate
}
https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
Try:
<?php
if (isset($_POST["register"])) {
include 'header.php';
$connection = new mysqli('xxxx', 'xxx', 'xxx', 'xxxx');
$firstName = $connection->real_escape_string($_POST["firstName"]);
$email = strtolower($connection->real_escape_string($_POST["email"]));
$password = sha1($connection->real_escape_string($_POST["password"]));
$sql = "SELECT * FROM users WHERE LOWER(email) = '$email';";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if($queryResult >0)
echo"Email already exists";
} else {
$data = $connection->query("INSERT INTO users (username, email, password) VALUES ('$firstName', '$email', '$password')");
if ($data === false) {
echo "Eroare!";
} else {
header( 'Location:http://alergii-help.tk/account/login.php');
}
}
}
?>
You need the first make the connection and then pass it before statement:
$result = mysqli_query($conn, $sql)
like below:
$conn = new mysqli('mysql.hostinger.com', 'u784726611_teze', 'b567c63b567c63', 'u784726611_teze');
$result = mysqli_query($conn, $sql);

Select then Insert PHP query

Ho can I check the database first if a user exists then use a insert statement if it does not. The code currently only executes the select statement.
<?php
include_once('includes/dbconn.php');
if (isset($_POST['submitted'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$user = $_POST['user'];
$pass = $_POST['pass'];
$query_check_user = "SELECT username FROM Users WHERE username = '$user'";
$query = "INSERT INTO Users(firstname, lastname, username, password) VALUES ('$fname','$lname','$user','$pass')";
if (mysqli_query($dbconn, $query_check_user)) {
echo "user already exists";
mysqli_close($dbconn);
}else{
mysqli_query($dbconn, $query);
}
}
?>
<?
include_once('includes/dbconn.php');
if (isset($_POST['submitted'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$user = $_POST['user'];
$pass = $_POST['pass'];
//Query for count
$query_check_user = "SELECT count(*) as total FROM Users WHERE username = '$user'";
$query = "INSERT INTO Users(firstname, lastname, username, password) VALUES ('$fname','$lname','$user','$pass')";
//Execute query for count
$result = mysqli_query($dbconn, $query_check_user);
//Fetch result
$data = mysqli_fetch_assoc($result);
//Check if count >0
if ($data['total']>0) {
echo "user already exists";
mysqli_close($dbconn);
}else{
mysqli_query($dbconn, $query);
}
}
?>
you can use mysqli_num_rows(); to check the number if result if it is greater then 0 then user exist else insert user data.
my example :
include_once('includes/dbconn.php');
if (isset($_POST['submitted'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$user = $_POST['user'];
$pass = $_POST['pass'];
$query_check_user = "SELECT username FROM Users WHERE username = '$user'";
$query_result = mysqli_query($query_check_user);
$query = "INSERT INTO Users(firstname, lastname, username, password) VALUES ('$fname','$lname','$user','$pass')";
if (mysqli_num_rows($query_result) > 0) {
echo "user already exists";
mysqli_close($dbconn);
}else{
mysqli_query($dbconn, $query);
}
}
as I get from your question is, you want to insert the user if the user doesn't exist, right?
$query_check_user = "SELECT username FROM Users WHERE username = '$user'";
$b = mysqli_query($dbconn,$query_check_user);
$a = mysqli_num_rows($b);
if($a<0):
mysqli_query(dbconn, "INSERT INTO Users(firstname, lastname, username, password) VALUES ('$fname','$lname','$user','$pass')");
endif;

password_verify() always return false

I am a newbie and I was trying to create a login system using PHP and Mysql. After finishing registration form and adding few users, I was trying to create a login form. but it always returns false saying my your Your username or password is incorrect!. Below is my code. It will be great if someone could help me. Advance sorry if my doubt is tooo basic :/
<?php
session_start();
include '.\includes\functions\db.php';
?>
<?php
$username = strtolower(mysqli_real_escape_string($db, $_POST['username']));
$password = strtolower(mysqli_real_escape_string($db, $_POST['password']));
$sql = "SELECT * FROM users WHERE username = '$username' ";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_assoc($result);
$hash_pwd = $row['password'];
echo $hash_pwd;
echo $password;
$hash = password_verify($password, $hash_pwd);
if ($hash ==0) {
header("Location: ./index.php?error=check");
exit();
}else {
$sql = "SELECT * FROM user WHERE username = '$username' AND password = '$hash_pwd'";
$result = mysqli_query($db, $sql);
if (mysqli_num_rows($result) == 0) {
echo "Your username or password is incorrect!";
}else {
$_SESSION['id'] = $row['id'];
$_SESSION['username'] = $row['username'];
}
//header("Location: ./index.php");
}
?>
and my registration page is as follows
<?php
//This Page is for registration of users
?>
<?php
// this php tag is for all includes
include '.\includes\functions\db.php';
?>
<?php
//print isset($_POST["submit"]);
//Getting all details inserted in form
if(isset($_POST["register"])){
$username = $_POST['username'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$date = date('Y-m-d H:i:s');
//Encrypting and Securing recieved data
$username = strtolower(mysqli_real_escape_string($db, $username));
$firstname = strtolower(mysqli_real_escape_string($db, $firstname));
$lastname = strtolower(mysqli_real_escape_string($db, $lastname));
$email = strtolower(mysqli_real_escape_string($db, $email));
$password = strtolower(mysqli_real_escape_string($db, $password));
$encryptedpassword = password_hash($password, PASSWORD_DEFAULT);
//To check duplication of email ids
$sql = "SELECT email FROM users WHERE email='$email'";
$result = mysqli_query($db, $sql);
$row = mysqli_num_rows($result);//$row will return count of rows if any duplicate email ids are found
//To check duplication of usernames
$sql2 = "SELECT username FROM users WHERE username='$username'";
$result2 = mysqli_query($db, $sql2);
$row2 = mysqli_num_rows($result2);//$row2 will return count of rows if any duplicate usernames are found
//conditions to check what all duplicates are found
if($row > 0 && $row2 >0){
echo "Sorry...This email id and username is already taken!!!";
} elseif ($row > 0 ) {
echo "Sorry...This email id is already taken!";
} elseif ($row2 > 0) {
echo "Sorry...This Username is already taken!";
}else {
$query = mysqli_query($db, "INSERT INTO users (username, firstname, lastname, password, email, regdate) VALUES
('$username', '$firstname', '$lastname', '$encryptedpassword', '$email', '$date')");
if($query){
echo "Thank You! you are now registered.";
}
}
}
?>
The error in my code is because of password = '$hash_pwd' condition in my where clause. When i retried row with given username and later verified password using php, it works as intended. I guess password hashed in php using password_hash() cannot be retrived and verified like encryption. Anyway thanks for all of yours responses

Checking only email, not username

I have this code which checks email availability from database, but it's only checking email and not username. I want to check both email and username, I tried to check them through the code below but it doesnt work.
What is wrong with the code?
<?php
require_once './config.php';
if (isset($_POST["sub"])) {
$fname = ($_POST["fname"]);
$lname = ($_POST["lname"]);
$name = ($_POST["username"]);
$pass = ($_POST["password"]);
$email = ($_POST["email"]);
$sql = "SELECT COUNT(*) AS count from users where email = :email_id and username = :username_id ";
try {
$stmt = $DB->prepare($sql);
$stmt->bindValue(":email_id", $email);
$stmt->bindValue(":username_id", $name);
$stmt->execute();
$result = $stmt->fetchAll();
if ($result[0]["count"] > 0) {
echo "<div style='color:red;' class='errorbox'>Incorrect Username or Password</div><br>";
} else {
$sql = "INSERT INTO `users` (`username`, `password`, `email`, `firstname`, `lastname`) VALUES " . "( :name, :pass, :email, :fname, :lname)";
}
}
}
?>
You have a problem with your SQL statement, you are checking that both email and username are together try changing your statement from
$sql = "SELECT COUNT(*) AS count from users where email = :email_id and username = :username_id "
to
$sql = "SELECT COUNT(*) AS count from users where email = :email_id or username = :username_id "
This should force a return of 1 whenever either the username or email appears proving that they are not unique
You are using and condition. If you use or condition means it will be fine.
$sql = "SELECT COUNT(*) AS count from users where email = :email_id or username = :username_id ";
Typographical error. This line should be replaced:
$stmt->bindValue(":username_id", $email);
should be replaced with:
$stmt->bindValue(":username_id", $name);
Maybe you have an error here:
$stmt->bindValue(":email_id", $email); //ok
$stmt->bindValue(":username_id", $email); //you bind with $email again .. is it normal ?
You should validate your $_POST datas with !empty i.e.:
if(!empty($_POST["email"]) $email = $_POST["email"]) ... because with your actual code you could make sql queries with empty $email = null

Registration script, need a database input to be checked then deleted upon register

I have a problem with my script. What it is supposed to do is that when a user register with the form, it should insert it, but only if the "passkey" matches the one that is in a different table that I set. After it has been verified it should insert the user info to the database, and then delete the passkey. I cannot seem to figure out what is wrong, it worked when there was only one input in the "passkey" table, but when I inserted more it stoped working. Any help would be appreciated!
Here is the code:
<?php
session_start();
if ($_SESSION['auth'] == true)
{
header('location: ../../index.php');
}
else
{
include($_SERVER['DOCUMENT_ROOT']."/skole/system/db/DbConnector.php");
new DbConnector();
if ($_POST)
{
$navn = mysql_real_escape_string($_POST['name']);
$brukernavn = mysql_real_escape_string($_POST['username']);
$passord = md5(mysql_real_escape_string($_POST['password']));
$siste_logginn = date("d/m/y H:i:s");
$logginn_ip = $_SERVER['REMOTE_ADDR'];
$email = mysql_real_escape_string($_POST['email']);
$passkey = mysql_real_escape_string($_POST['passkey']);
$qGetPasskey = mysql_query("SELECT * FROM passkey");
$rGetPasskey = mysql_fetch_array($qGetPasskey);
if($rGetPasskey['passkey'] == $passkey)
{
mysql_query("INSERT INTO brukere SET navn = '{$navn}', brukernavn = '{$brukernavn}', passord = '{$passord}', siste_logginn = '{$siste_logginn}', logginn_ip= '{$logginn_ip}', email = '{$email}', passkey = '{$passkey}'");
mysql_query("DELETE FROM passkey WHERE passkey = '{$passkey}'");
echo 'Success';
}
//header('location: ../../index.php');
}
else
{
echo 'Failure';
//header('location: ../../index.php?aksjon=register&feil=1');
}
}
?>
I believe it is not matching because there is no loop to check multiple records in your array:
$qGetPasskey = mysql_query("SELECT * FROM passkey");
while($rGetPasskey = mysql_fetch_array($qGetPasskey)) {
if($rGetPasskey['passkey'] == $passkey) {
mysql_query("INSERT INTO brukere SET navn = '{$navn}', brukernavn = '{$brukernavn}', passord = '{$passord}', siste_logginn = '{$siste_logginn}', logginn_ip= '{$logginn_ip}', email = '{$email}', passkey = '{$passkey}'");
mysql_query("DELETE FROM passkey WHERE passkey = '{$passkey}'");
echo 'Success';
}
}
The recommended way to store and check a password is to use a salted hash function.
Never store an unencrypted password in a database!
See: Secure hash and salt for PHP passwords
Store the userdata including passhash
INSERT INTO user (username, salt, passhash)
VALUES ('$username','$salt',SHA2(concat('$salt','$password'),512))
Check for valid username and password
SELECT id FROM user
WHERE username = '$username' AND passhash = SHA2(concat('$salt','$password'),512)
Insert data into a table if and only if a user exists
$passkey = mysql_real_escape_string($_POST['passkey']);
mysql_query("INSERT INTO brukere
(navn, brukernavn, passord, sisteloginn, loginn_ip, email, passhash)
SELECT
'$navn','$brukernavn','$passord', '$siste_logginn', '{$logginn_ip}', '{$email}', id
FROM user u
WHERE u.username = '$brukernavn'
AND passhash = SHA2(concat(u.salt,'$passkey'),512) ";
Note that you don't need the {} in your query, you only need those if you want to evaluate an expression. If you just want to inject a $var, '$var' and {'$var'} is the same.
use or die(mysql_error());
see if you have any MySQL errors in your queries.
Example:
mysql_query("INSERT INTO brukere SET navn = '{$navn}', brukernavn = '{$brukernavn}', passord = '{$passord}', siste_logginn = '{$siste_logginn}', logginn_ip= '{$logginn_ip}', email = '{$email}', passkey = '{$passkey}'") or die("Error ->".mysql_error());

Categories