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;
Related
I'm trying to make a query that would check if username has been taken but it only stores the form data into the database even if the username already exists
<?php
$db= new mysqli('localhost', 'root', '', 'mytrackz');
$query= "SELECT * FROM users ";
$result2= mysqli_query($db, $query);
$user= mysqli_fetch_assoc($result2);
if (isset($_POST['regbutton']))
{
$username= $_POST['username'];
$email= $_POST['email'];
$password= $_POST['password'];
$sql= "INSERT INTO users (username, email, password) VALUES ('$username', '$email', '$password')";
$result= mysqli_query($db, $sql);
if ($user) {
if ($user == $username){
echo "Username already exists";
}elseif($result){
echo "Registeration Successful";
}else{
echo "Registeration unsuccessful";
}
}
}
?>
1:
when you do '$query= "SELECT * FROM users "' you are getting all records in your table without any filter by user.
2:
afeter check the post in 'if (isset($_POST['regbutton']))' you are inserting the value without check in database.
3: 'if ($user == $username){
echo "Username already exists";' you are checking a single value agains an array of objects from database;
To fix it:
<?php
$db= new mysqli('localhost', 'root', '', 'mytrackz');
if (isset($_POST['regbutton']))
{
$username= $_POST['username'];
$email= $_POST['email'];
$password= $_POST['password'];
$query= "SELECT * FROM users WHERE username = '$username'";
$result2= mysqli_query($db, $query);
$user= mysqli_fetch_assoc($result2);
if ($user['username'] == $username){
echo "Username already exists";
}else{
$sql= "INSERT INTO users (username, email, password) VALUES ('$username','$email', '$password')";
$result= mysqli_query($db, $sql);
}
}
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
This is my php code for insert account into the table
<?php
require "conn.php";
$user_name = $_POST["user_name"];
$user_pass = $_POST["password"];
$mysql_qry = "insert into account_data (username,password) values ('$user_name','$user_pass')";
$result = mysqli_query($conn ,$mysql_qry);
if($result) {
echo "insert success";
}
else {
echo "Failed insert of '$user_name', '$user_pass' ";
}
?>
And this is the php for login
<?php
require "conn.php";
$user_name = $_POST["user_name"];
$user_pass = $_POST["password"];
$mysql_qry = "select * from account_data where username like '$user_name' and password like '$user_pass';";
$result = mysqli_query($conn ,$mysql_qry);
if(mysqli_num_rows($result) > 0) {
echo "Accesso riuscito";
}
else {
echo "Accesso non riuscito: username ($user_name) o password ($user_pass) non corretti ";
}
?>
I can't understand why the second code works perfectly and the second one doesn't work, any ideas?
Alright, I have tried and searched everywhere to fix this but no luck.
All I am trying to do is display a users username and email (Who are logged in) and then print their details to thier account page.
The problem is that all of the users in the database are being logged, I only want the users who is logged in to be displayed.
Db.php
<?php
$myConnection= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($myConnection, "register") or die ("no database");
>
Auth.php
<?php
session_start();
if(!isset($_SESSION["username"])){
header("Location: login.php");
exit(); }
?>
Login.php
<?php
require('db.php');
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$username = mysqli_real_escape_string($myConnection, $username);
$password = stripslashes($password);
$password = mysqli_real_escape_string($myConnection, $password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE username='$username' and password='".md5($password)."'";
$result = mysqli_query($myConnection, $query) or die(mysqli_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $username;
$_SESSION['user_id'] = $row['user_id'];
header("Location: index.php"); // Redirect user to index.php
}else{
echo "<div class='form'><h3>Username/password is incorrect.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
}else{
?>
Register.php
<?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 = mysqli_real_escape_string($myConnection, $username);
$email = stripslashes($email);
$email = mysqli_real_escape_string($myConnection, $email);
$password = stripslashes($password);
$password = mysqli_real_escape_string($myConnection, $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 = mysqli_query($myConnection, $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{
?>
Account.php //Where I want user data to be displayed on page
<?php
// SQL query
$strSQL = "SELECT * FROM users";
// Execute the query (the recordset $rs contains the result)
$rs = mysqli_query($myConnection, $strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysqli_fetch_array
while($row = mysqli_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['username'] . "<br />";
echo $row['email'] . "<br />";
}
// Close the database connection
mysqli_close($myConnection);
?>
$strSQL = "SELECT * FROM users";
Why that query? if you say you wanted to display only the info about users logged in, you are getting all users without conditions
Do the query for the user who is logged in at the moment, something like
$strSQL = "SELECT * FROM users WHERE username = '".$_SESSION['username']."'";
or somethinbg like this
<?php
session_start(); //Add this
//Also you have to add your connection file before your query
require('db.php');
// SQL query
$strSQL = "SELECT username, email FROM users WHERE user_id = '".$_SESSION['user_id']."'";
// Execute the query (the recordset $rs contains the result)
$rs = mysqli_query($myConnection, $strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysqli_fetch_array
while($row = mysqli_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['username'] . "<br />";
echo $row['email'] . "<br />";
}
// Close the database connection
mysqli_close($myConnection);
?>
I think it should have to work, tell me if it worked for you
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).