PHP Prepared Statements - MySQL Check if user exists - php

I don't know why my code doesn't seem to be working. I want to check if an email exists in the database, and if it doesn't exist proceed with registration. Here's the code:
if (empty($errors)) { //Using Prepared Statements
// Connect to the database:
$dbc = mysqli_connect ('localhost','root', 'pass', 'book_store');
$q = "SELECT user_id FROM users WHERE email=?";
$stmt = mysqli_prepare($dbc, $q);
mysqli_stmt_bind_param($stmt, 'i', $email);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$num_rows = mysqli_num_rows($result);
if ($num_rows == 0) { //Check if email exists
$q = 'INSERT INTO users(first_name, last_name, state, email) VALUES (?, ?, ?, ?)';
$stmt = mysqli_prepare($dbc, $q);
mysqli_stmt_bind_param($stmt,'ssss', $fn, $ln,$state, $email);
mysqli_stmt_execute($stmt);
// Closee statement:
mysqli_stmt_close($stmt);
// Close the connection:
mysqli_close($dbc);
} else {
echo '<h1>email exists</h1>';
}
}
else {
echo '<p>The Errors Occurred:<br />';
foreach ($errors as $msg) {
echo " - $msg<br />\n";
}
echo '</p><p>Please Try Again.</p>';
}
}

You have given i, which represents variable of type int. Try replacing that with s as given below.
$q = "SELECT user_id FROM users WHERE email=?";
$stmt = mysqli_prepare($dbc, $q);
mysqli_stmt_bind_param($stmt, 's', $email);

Related

Inserting values to different tables based on variables

$username = $_POST['uid'];
$email = $_POST['mail'];
$password = $_POST['pwd'];
$passwordRepeat = $_POST['pwd-repeat'];
$date = $_POST['date2'];
$stream = $_POST['relationship'];
$sql1 = "INSERT INTO users (uidUsers, emailUsers, pwdUsers, relationship) VALUES (?, ?, ?, ?);";
$sql2 = "INSERT INTO Family1 (username, application_filed, relationship) VALUES (?, ?, ?);";
$sql3 = "INSERT INTO Family2 (username, application_filed, relationship) VALUES (?, ?, ?);";
mysqli_query($sql1, $conn);
mysqli_query($sql2, $conn);
mysqli_query($sql3, $conn);
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql2)) {
header("Location: ../signup.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "sss", $username, $date, $stream);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result))
($username==$_SESSION['uid'] and $stream =='nursing');
mysqli_stmt_execute($stmt);
}
if (!mysqli_stmt_prepare($stmt, $sql3)) {
header("Location: ../signup.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "sss", $username, $date, $stream);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result))
($username==$_SESSION['uid'] and $stream =='doctoral');
mysqli_stmt_execute($stmt);
}
if (!mysqli_stmt_prepare($stmt, $sql1)) {
header("Location: ../signup.php?error=sqlerror");
exit();
}
if (!mysqli_stmt_prepare($stmt, $sql1)) {
header("Location: ../signup.php?error=sqlerror");
exit();
}
else {
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "ssss", $username, $email, hashedPwd,$stream);
mysqli_stmt_execute($stmt);
header("Location: ../signup.php?signup=success");
exit();
/////////////New Code////////////////
$username = $_POST['uid'];
$email = $_POST['mail'];
$password = $_POST['pwd'];
$passwordRepeat = $_POST['pwd-repeat'];
$date = $_POST['date2'];
$stream = $_POST['relationship'];
$sql1 = "INSERT INTO users (uidUsers, emailUsers, pwdUsers, relationship) VALUES (?, ?, ?, ?);";
$sql2 = "INSERT INTO Family1 (username, application_filed, relationship) VALUES (?, ?, ?);";
$sql3 = "INSERT INTO Family2 (username, application_filed, relationship) VALUES (?, ?, ?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql2)) {
header("Location: ../signup.php?error=sqlerror");
exit();
} else if ($username==$_SESSION['uid'] && $stream =='nursing') {
mysqli_stmt_bind_param($stmt, "sss", $username, $date, $stream);
mysqli_stmt_execute($stmt);
}
if (!mysqli_stmt_prepare($stmt, $sql3)) {
header("Location: ../signup.php?error=sqlerror");
exit();
}
else if ($username==$_SESSION['uid'] && $stream =='doctoral') {
mysqli_stmt_bind_param($stmt, "sss", $username, $date, $stream);
mysqli_stmt_execute($stmt);
}
if (!mysqli_stmt_prepare($stmt, $sql1)) {
header("Location: ../signup.php?error=sqlerror");
exit();
}
else {
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "ssss", $username, $email, $hashedPwd, $stream);
mysqli_stmt_execute($stmt);
header("Location: ../signup.php?signup=success");
exit();
}
I was wondering if someone could point me in the right direction. I have this code. They idea I had behind it is to insert values into different tables depending on variables being passed.
So when user fills out a form and selects $stream="nursing" I want results to go to table 'users' and 'Family1', but not 'Family2' table. and if user selects $stream='doctoral' results should go to table 'users' and 'Family2', and not go to 'Family1'
But with my query I get results go to both table and also users table. And there is no restriction to what users selects, variable $stream being passed no matter what it is.
Is this the wrong way to go here? Did I completely mess up the logic?
For one thing, the mysqli_query() calls at the top will try to run the queries and will fail, since it has no understanding of the ? placeholders and you have the $conn and $sqlX variables the wrong way around.
But aside from that, let me fix the indentation for you so you can see what's actually happening for one of your statements:
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql2)) {
header("Location: ../signup.php?error=sqlerror");
exit();
} else {
mysqli_stmt_bind_param($stmt, "sss", $username, $date, $stream);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result))
($username==$_SESSION['uid'] and $stream =='nursing');
mysqli_stmt_execute($stmt);
}
Do you see what's happening here?
$sql2 is an INSERT query. If you were able to prepare that statement you try to get the result before the query is even executed. If you manage to retrieve a row of data from that result (which you can't since an INSERT query does not return any records), you then do a check on $username and $stream that has no effect. The call to execute the prepared statement is executed regardless of whether or not you managed to get anything from $result.
All your statements have the same problems, so I'll only fix this one.
Here's what I changed:
The whole $result step seemed unnecessary, so I removed it.
I replaced and with && because of my personal preference. There was once a reason why it became my preference, but I forget. It's mostly for consistency between programming languages, since many languages use && and only a few use and.
Since there's no point in binding params to a statement you're not planning to execute, I moved that into the if-statement.
Since I now ended up with an else { if { ... } } construction, I simplified that down to an else if { ... } for cleaner code.
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql2)) {
header("Location: ../signup.php?error=sqlerror");
exit();
} else if ($username==$_SESSION['uid'] && $stream =='nursing') {
mysqli_stmt_bind_param($stmt, "sss", $username, $date, $stream);
mysqli_stmt_execute($stmt);
}
Now, the query $sql2 is only executed if the $username matches the current uid from the session and the user selected the nursing stream.

Cant echo out data from database using PHP mysqli_stmt_fetch

What i want to do is to check if the email & username are already inside on my database, then if it is already inside the database then i want to echo out the username, how to fix this? thanks
$sql = "SELECT * FROM user WHERE uidUser=? OR emailUser=?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../signup.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "ss", $username, $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);
if ($resultCheck > 0) {
while ($row=mysqli_stmt_fetch($stmt)) {
echo "Name: ".$row['uidUser'];
}
}
}

CSS and nav bar issue when logged into live server

My site looks like this after login, without any navigation bar or css.
It should have included my header2.php file, which contains my nav bar and my css should be working.
Below is my code for login.php:
<?php
ob_start();
if (!isset($_POST['submit'])) {
header("Location: /../index.php?login=error");
exit();
} else {
include_once __DIR__.'/dbh.php';
include_once __DIR__.'/../header2.php';
$uid = strip_tags($_POST['uid']);
$pwd = strip_tags($_POST['password']);
$date = date("Y-m-d H:i:s");
$sql = "UPDATE users
SET user_session = ?
WHERE user_uid = ?;
";
$stmt = mysqli_stmt_init($conn);
//Prepare the prepared statement
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "ss", $date, $_SESSION['u_uid']);
//Run parameters inside database
mysqli_stmt_execute($stmt);
// include error handlers:
// Check to see if the inputs are empty
//Check to see if user has activated his or her account before logging in
$user_activate = 0;
if(empty($uid) || empty($pwd)) {
echo "<meta http-equiv='refresh' content='0;url=../signup.php?signup=empty'>";
exit();
} else {
// Check to see if user has activated his or her account
$sql = "SELECT * FROM users WHERE user_activate = ? AND user_uid= ?;";
$stmt = mysqli_stmt_init($conn);
//Prepare the prepared statement
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "is", $user_activate, $uid);
//Run parameters inside database
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0) {
echo "<meta http-equiv='refresh' content='0;url=/../index.php?signup=notactivated'>";
exit();
} else {
// Check to see if the username exists in the database
$sql = "SELECT * FROM users WHERE user_uid = ? OR user_email = ?";
$stmt = mysqli_stmt_init($conn);
//Prepare the prepared statement
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "ss", $uid, $uid);
//Run parameters inside database
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck < 1) {
echo "<meta http-equiv='refresh' content='0;url=/../index.php?login=notsignup'>";
exit();
} else {
// Does the password match the password in the database?
// while($row = mysqli_fetch_assoc($result));
if ($row = mysqli_fetch_assoc($result)) { // insert database results into an array
// De-hasing the password
$hashedPwdCheck = password_verify($pwd, $row['user_password']);
if ($hashedPwdCheck == false) {
$login_attempts = $row['login_attempts'];
$login_attempts += 1;
$sql2 = "UPDATE users
SET login_attempts = ?
WHERE user_uid = ?;
";
if (!mysqli_stmt_prepare($stmt, $sql2)) {
echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "is", $login_attempts, $uid);
//Run parameters inside database
mysqli_stmt_execute($stmt);
if ($row['login_attempts'] == 5) {
$login_attempts = 0;
$user_activate = 0;
$token = 'qqewreqreqwsdfdfdafcbvcQERFGHFGHGFHRETERTDF!##$%^^()';
$token = str_shuffle($token);
$token = substr($token, 0, 10);
$sql3 = "UPDATE users
SET user_activate = ?, user_token = ?, login_attempts = ?
WHERE user_uid = ?;
";
if (!mysqli_stmt_prepare($stmt, $sql3)) {
echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "isis", $user_activate, $token, $login_attempts, $uid);
//Run parameters inside database
mysqli_stmt_execute($stmt);
$company = "pianocourse101#hotmail.com";
$subject = "Account temporary deactivated due to fail login attempts";
$mailTo = $row['user_email'];
$headers = "From: ".$company;
$txt = "Dear".$row['user_first']."".$row['user_last'].", \n\nYour account has been temporary deactivated because either you or someone claiming to be you has failed to log into your account on more than 5 occasions! \n\n You can use the following information to reactivate your account: \n\n Your new token: ".$token."\n\nYou can either copy and paste the token into the relevant section or click on the following link: http://localhost/loginsystem/includes/activate.php?email=".htmlspecialchars($row['user_email'])."&activatetoken=".htmlspecialchars($token);
mail($mailTo, $subject, $txt, $headers);
}
}
echo "<meta http-equiv='refresh' content='0;url=/../index.php?login=passwordfailed'>";
exit();
}
} elseif ($hashedPwdCheck == true) {
// Log in the user here
$_SESSION['u_id'] = $row['user_id'];
$_SESSION['u_first'] = $row['user_first'];
$_SESSION['u_last'] = $row['user_last'];
$_SESSION['u_email'] = $row['user_email'];
$_SESSION['u_uid'] = $row['user_uid'];
$_SESSION['u_permission'] = $row['admin'];
$_SESSION['u_moderator'] = $row['moderator'];
$_SESSION['u_session'] = $row['user_session'];
$_SESSION['freelesson'] = $row['freelesson'];
$_SESSION['datejoined'] = $row['datejoined'];
$_SESSION['premium'] = $row['premium'];
// Insert into reward points when login
// Select names from rewards
$sql2 = "SELECT * FROM rewards WHERE user_uid = ?;";
$stmt = mysqli_stmt_init($conn);
//Prepare the prepared statement
if (!mysqli_stmt_prepare($stmt, $sql2)) {
echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "s", $uid);
//Run parameters inside database
mysqli_stmt_execute($stmt);
$result2 = mysqli_stmt_get_result($stmt);
$resultCheck2 = mysqli_num_rows($result2);
while ($row2 = mysqli_fetch_assoc($result2)) {
$_SESSION['u_reward_points'] = $row2['reward_points'];
$points = 100;
$_SESSION['u_reward_points'] += $points;
$sql = "UPDATE rewards
SET reward_points = ?
WHERE user_uid = ?;
";
$stmt = mysqli_stmt_init($conn);
//Prepare the prepared statement
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "is", $_SESSION['u_reward_points'], $_SESSION['u_uid']);
//Run parameters inside database
mysqli_stmt_execute($stmt);
echo "<meta http-equiv='refresh' content='0;URL=/../header2.php?login=success' />" ;
exit();
}
}
}
}
}
}
}
}
}
}
}
}
ob_end_flush();
enter image description here
Make sure the CSS files are loaded properly if loaded from external files.
Always debug your scripts with enabled PHP Error Reporting!
The final output in the browser you can see the Source code - usually Ctrl+U, or you can debug with Developers tools - usually right click the page and do Inspect element Ctrl+Shift+I - Network tab might show you some errors, same in Console tab etc.
Both should help you to identify the problematic part of your coding.
it's seems like your css files aren't loaded.
you can check through your network tab if they do loaded.

PHP echo all data from database based on input

I want to find out how to output data from database based on a single key,for example my database column are :
kodeDosen(PrimaryKey),namaDosen,email,telepon,password
and my login screen the user can only input kodeDosen and password,and i want to show the other data exept password,this is my register php:
<?php
include 'connectdb.php';
$data = json_decode(file_get_contents('php://input'), true);
$kodeDosen =$data["kodeDosen"];
$namaDosen = $data["namaDosen"];
$email = $data["email"];
$telepon = $data["telepon"];
$password= $data["password"];
$message = array("message"=>"Success");
$failure = array("message"=>"Failure,kodeDosen already used");
$sql = "INSERT INTO tbl_dosen (kodeDosen, namaDosen, email, telepon, password) VALUES ('$kodeDosen', '$namaDosen', '$email', '$telepon','$password')";
if (mysqli_query($conn, $sql)) {
echo json_encode($message);
} else {
echo json_encode($failure) ;
}
?>
and this is my login php:
<?php
include 'connectdb.php';
$data = json_decode(file_get_contents('php://input'), true);
$kodeDosen =$data["kodeDosen"];
$password = $data["password"];
$message = array("message"=>"Data found");
$failure = array("mesage"=>"Data not found");
if ($stmt = mysqli_prepare($conn, "SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen =? and password = ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ss", $kodeDosen,$password);
/* execute query */
mysqli_stmt_execute($stmt);
/* store result */
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) > 0) {
echo json_encode($row);
}else {
echo json_encode($failure);
}
}
?>
It's not a good idea to insert a variable directly into an SQL query because of SQL injection.
I would suggest to use prepared statements on both of the queries. To pull the result from the db with prepared statements it's something like:
OOP style:
$stmt = $db->prepare("SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen = ? and password = ?");
$stmt->bind_param('ss', $kodeDosen, $password);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
//result is in row
var_dump($row);
}
Procedural style:
$stmt = mysqli_prepare($conn, "SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen = ? and password = ?");
mysqli_stmt_bind_param($stmt, 'ss', $kodeDosen, $password);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = $result->fetch_assoc()) {
//result is in row
var_dump($row);
}
You can change in sql SELECT statement in login.php
$sql = "SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen ='$kodeDosen' and password = '$password'";
in SELECT * means return all columns.
I think you want echo json_encode($row); rather than echo json_encode($message);
Try:
<?php
include 'connectdb.php';
$data = json_decode(file_get_contents('php://input'), true);
$kodeDosen =$data["kodeDosen"];
$password = $data["password"];
$message = array("message"=>"Data found");
$failure = array("mesage"=>"Data not found");
if ($stmt = mysqli_prepare($conn, "SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen =? and password = ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ss", $kodeDosen,$password);
/* execute query */
mysqli_stmt_execute($stmt);
/* store result */
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc( $result );
if(mysqli_num_rows($result) > 0) {
echo json_encode($row);
}else {
echo json_encode($failure);
}
}
?>

Prepared Statements Checking if row exists

I am new to Prepared Statements in Php and and wondering how you would best approach checking if a row already exists as I seem to be getting confused at this stage:
<?php
include '../config.php';
$stmt = $conn->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
$stmt->bind_param("ss", $email, $password);
if(mysqli_num_rows($stmt) > 0) {
$email = $_POST['email'];
$password = $_POST['password'];
$stmt->execute();
header('Location: ../login.php');
} else {
echo 'user already exists';
}
$stmt->close();
$conn->close();
?>
The above returns the else statement, if I switch them around it will insert again making use of the else statement and inserting the record but still not checking.
** UPDATE **
Here is my updated code for you to see after assistance below..
<?php
include '../config.php';
ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);
$email = $_POST['email'];
$password = $_POST['password'];
$stmt_check = $conn->prepare("SELECT * FROM users WHERE email =?");
$stmt_check->bind_param("s", $email);
$stmt_check->execute();
if($stmt_check->num_rows > 0) {
echo 'user already exists';
} else {
$stmt = $conn->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
$stmt->bind_param("ss", $email, $password);
$stmt->execute();
// header('Location: ../login.php');
}
$stmt->close();
$conn->close();
?>
mysqli_num_rows applicable to SELECT statement.
$stmt_check = $conn->prepare("SELECT * FROM users WHERE email =? AND password =?");
$stmt_check->bind_param("ss", $email, $password);
$stmt_check->execute();
if(mysqli_num_rows($stmt_check) > 0)
Updated Code
<?php
include '../config.php';
$email = $_POST['email'];
$password = $_POST['password'];
$stmt_check = $conn->prepare("SELECT * FROM users WHERE email =? AND password =?");
$stmt_check->bind_param("ss", $email, $password);
$stmt_check->execute();
if($stmt_check->num_rows > 0){
echo 'user already exists';
} else {
$stmt = $conn->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
$stmt->bind_param("ss", $email, $password);
$stmt->execute();
header('Location: ../login.php');
}
$stmt->close();
$conn->close();
?>
Quick Link
mysqli_num_rows
mysql_num_rows
Which States,
This command is only valid for statements like SELECT or SHOW that
return an actual result set. To retrieve the number of rows affected
by a INSERT, UPDATE, REPLACE or DELETE query, use
mysql_affected_rows().
Edit 1
Change
if(mysqli_num_rows($stmt_check) > 0){
To
if($stmt_check->num_rows > 0){
See Example2 of PHP mysqli_num_rows() Function
This is my updated code, please try
<?php
include '../config.php';
$email = $_POST['email'];
$password = $_POST['password'];
$stmt_check = $conn->prepare("SELECT * FROM users WHERE email =? AND password =?");
$stmt_check->bind_param("ss", $email, $password);
$stmt_check->execute();
$stmt_check->store_result();
$numberofrows = $stmt_check->num_rows;
if(($numberofrows) > 0)
echo 'user already exists';
} else {
$stmt = $conn->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
$stmt->bind_param("ss", $email, $password);
$stmt->execute();
header('Location: ../login.php');
}
$stmt->close();
$conn->close();
?>
Take a look at mysqli_stmt_affected_rows()
<?php include '../config.php';
$stmt = $conn->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
$stmt->bind_param("ss", $_POST['email'], $_POST['password']);
$stmt->execute();
if(mysqli_stmt_affected_rows($stmt) > 0)
{
header('Location: ../login.php');
}
else
{
echo 'user already exists';
}
$stmt->close();
$conn->close();
?>
<?php include '../config.php';
$stmt = $conn->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
$stmt->bind_param("ss", $_POST['email'], $_POST['password']);
$result = $stmt->execute(); // this return a bool: true if row affected otherwise false
if($result)
{
header('Location: ../login.php');
}
else
{
echo 'user already exists';
}
$stmt->close();
$conn->close();
?>

Categories