Cant echo out data from database using PHP mysqli_stmt_fetch - php

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'];
}
}
}

Related

My php & mysqli script is returning with zero rows in database even though there is a row

I am semi-new to PHP and MySQL so I was using this tutorial video to set up the forgotten password system for their previous tutorial on a login system (https://www.youtube.com/watch?v=wUkKCMEYj9M, timestamp to the part I am working on is 1:05:46).
Everything was working fine until I got to the part where we had to create the new password and anytime I submit the new password, it receives an error essentially saying that there are no rows in the database, or at least I believe that is what the error is. (Error Message: You need to re-submit your request (1)) Below I have given my code (The file for the database connector is accurately named dbc.inc.php, I messed it up when originally naming it so I just apply the different name to my scripts) and if you see what it is, I will be very grateful. Thanks!
<?php
if(isset($_POST["reset-password-submit"])) {
$selector = $_POST["selector"];
$validator = $_POST["validator"];
$password = $_POST["pwd"];
$passwordRepeat = $_POST["pwd-repeat"];
if(empty($password) || empty($passwordRepeat)) {
header("Location: ../create-new-password.php?newpwd=empty&selector=". $selector . "&validator=" . $validator);
exit();
}
else if ($password != $passwordRepeat){
header("Location: ../create-new-password.php?newpwd=pwdnotsame&selector=". $selector . "&validator=" . $validator);
exit();
}
$currentDate = date("U");
require 'dbc.inc.php';
$sql = "SELECT * FROM pwdReset WHERE pwdResetSelector=? AND pwdResetExpires >= ?";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
echo "There was an error. (1)";
exit();
}
else {
mysqli_stmt_bind_param($stmt, "ss", $selector, $currentDate);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if(!$row = mysqli_fetch_assoc($result)) {
echo "You need to re-submit your reset request. (1)";
exit();
}
else
{
$tokenBin = hex2bin($validator);
$tokenCheck = password_verify($tokenBin, $row["pwdResetToken"]);
if($tokenCheck == false)
{
echo "You need to re-submit your reset request. (2)";
exit();
}
else if ($tokenCheck == true)
{
$tokenEmail = $row['pwdResetEmail'];
$sql = "SELECT * FROM users WHERE emailUsers=?;";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
echo "There was an error. (2)";
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $tokenEmail);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if(!$row = mysqli_fetch_assoc($result)) {
echo "There was an error. (3)";
exit();
}
else
{
$sql = "UPDATE users SET pwdUsers=? WHERE emailUsers=?";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
echo "There was an error. (4)";
exit();
}
else {
$newPwdHash = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "ss", $newPwdHash, $tokenEmail);
mysqli_stmt_execute($stmt);
$sql = "DELETE FROM pwdReset WHERE pwdResetEmails=?";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
echo "There was an error. (5)";
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $tokenEmail);
mysqli_stmt_execute($stmt);
header("Location: ../signup.php?newpwd=passwordupdated");
}
}
}
}
}
}
}
}
else {
header("Location: ../index.php");
}
I figured out what was wrong. In the page the user would input their new password on also stores the selector and token, both of which I had misspelled value on. The script above works fine with a minor tweak to the bottom part.
The new hash part should be:
$newPwdHash = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "ss", $newPwdHash, $tokenEmail);
mysqli_stmt_execute($stmt);
$sql = "DELETE FROM pwdReset WHERE pwdResetEmail=?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "There was an error 5";
exit();
} else {
mysqli_stmt_bind_param($stmt, "s", $tokenEmail);
mysqli_stmt_execute($stmt);
header("Location: ../signup.php?newpwd=passwordupdated");
}
Not what it was originally above.

What does $row stand for in prepared statements (MySQLi)?

I'm watching a login system guide on Youtube, and recreating it. It's about done, but every time i try to login, it gives me an error:
"Incorrect Password"
I suspect this has to do with the $row that was made in an if statement. But i don't know what $row does.
I'll leave some code if someone can see the problem.
<?php
else {
$sql = "SELECT * FROM users WHERE uidUsers=? OR emailUsers=?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../index.php?error=sqlerror");
exit();
}
else{
mysqli_stmt_bind_param($stmt, "ss", $mailuid, $mailuid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
$pwdCheck = password_verify($password, $row['pwdUsers']);
if ($pwdCheck == false) {
header("Location: ../index.php?error=wrongpwd");
exit();
}
elseif ($pwdCheck == true) {
session_start();
$_SESSION['userId'] = $row['idUsers'];
$_SESSION['userUid'] = $row['uidUsers'];
header("Location: ../index.php?login=succes");
exit();
} ?>
if ($row = mysqli_fetch_assoc($result))
This tries to fetch a row from the query result. If there is a row to fetch from the results, then that row is assigned to the $row variable and the if statement is executed. If there is not a row to fetch from the results, then the if statement returns false and is skipped.

Prepared statement fails when it shouldn't

I have a signup form on my website and the following code should run whenever a new user signs up:
$sql = "SELECT * FROM users WHERE uidUsers=?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt)) {
header("Location: ../signup.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);
if ($resultCheck > 0) {
header("Location: ../signup.php?error=usertaken");
exit();
}
else {
$hashedPwd = password_hash(PASSWORD_DEFAULT, $password);
$sql = "INSERT INTO users (`uidUsers`, `pwdUsers`, `phraseUsers`) VALUES(?,
?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt)) {
header("Location: ../signup.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "sss", $username, $hashedPwd,
$securityphrase);
mysqli_stmt_execute($stmt);
header("Location: ../login.php?signup=success");
exit();
}
The !mysqli_stmt_prepare error handler is triggered when it shouldn't be given the database circumstance, as well as the correct INSERT statement. Therefore I don't understand why it's triggered and I'm asking why?
There is a similar question here on Stack Overflow
Thank you for your help, the problems where the password_hash order, it should be like this password_hash($var, PASSWORD_DEFAULT);. The second mistake I made was not including my $sql statements in the mysqli_stmt_prepare, it should be like this !mysqli_stmt_prepare($stmt, $sql).

How to randomly select two strings?

I have decided to store the winner into another database table and then to use that to output the winner on another page... I have the following code but for some reason, my second query is not working and I have checked it through... All the variables are correct and my database table should be set up correctly:
<?php
include_once __DIR__.'/header2.php';
if(!isset($_SESSION['u_uid'])) {
echo "<meta http-equiv='refresh' content='0;url=index.php?level1promo_competitions_winner=notlogin'>";
exit();
} else {
if($_SESSION['u_permission'] == 0) {
echo "<meta http-equiv='refresh' content='0;url=header2.php?level1promo_competitions_winner=nopermission'>";
exit();
} else {
include_once __DIR__.'/includes/dbh.php';
$level1promo_competitions_winner_form = strip_tags($_POST['level1promo_competitions_winner_form']);
if ($level1promo_competitions_winner_form == $level1promo_competitions_winner_form) {
$limit = 1;
$sql = "SELECT * FROM level1promo_participants WHERE entry_id = ? ORDER BY RAND() LIMIT ?;";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL error";
} else {
mysqli_stmt_bind_param($stmt, "si", $level1promo_competitions_winner_form, $limit);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$resultCheck = mysqli_num_rows($result);
if($resultCheck < 1) {
echo '<div class="nolevel1promo_competitions_winner">There are no Level 1 Promo Competition\'s Winner yet for that entry id</div>';
exit();
} else {
$row = mysqli_fetch_assoc($result);
$useruid = $row['user_uid'];
$email = $row['user_email'];
echo $level1promo_competitions_winner_form;
echo $useruid;
echo $email;
$sql2 = "INSERT INTO level1promo_winner (entry_id, user_uid, user_email) VALUES (?,?,?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql2)) {
echo "SQL statement failed";
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "sss", $levelpromo_competitions_winner_form, $useruid, $email);
mysqli_stmt_execute($stmt);
echo "<meta http-equiv='refresh' content='0;url=header2.php?level1promo_competitions_winner=success'>";
}
}
}
}
}
}
?>
You can do it easily by using below query. you don't need to put that much logic for it.
select column_name from table_name order by RAND() limit 1

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.

Categories