When using the fetch object in PHP, the while loop cannot be used to take effect
P粉803444331
2023-08-16 11:49:58
<p>I am making a login page for the admin, but the while loop in the php code is not working. I'll leave the code here (sorry for the Spanish in the code) </p>
<pre class="brush:php;toolbar:false;">//Create a connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
echo "An error occurred while connecting to the server.";
}
$username = $_POST["username"];
if ($username != "") {
$password = $_POST["password"];
$accountLevel = $_POST["accountLevel"];
$content = $_POST["content"];
$sql = "SELECT password, accountLevel FROM `accounts1` WHERE username='".$username."'";
$result = mysqli_query($conn, $sql);
while ($post = $result->fetch_object()) {
if ($post->password != $password) {
echo "Wrong password";
}else if ($post->accountLevel != $accountLevel) {
echo "Error: Unable to publish. Account level error.";
}else{
$sql = "INSERT INTO `blogposts`(`title`, `contentHTML`, `publishDate`, `commentSection`, `likes`, `dislikes`, `publisher`, `selector`) VALUES ('','". $_POST['content']."','".$_POST['publishDate']."','',0,0,'".$_POST['username']."','')" ;
/*$fetchObj = mysqli_fetch_object($QueryResult);
var_dump($fetchObj);*/
echo "sent";
}
}
}else{
echo "No user specified";
}</pre>
<ul>
<li><p>Is there a way to replace the while loop with a simpler assignment (since it is a login page and only checks one account)</p>
</li>
<li><p>Why does the while loop not work? I've used the same code before on another page and it worked perfectly fine and I didn't see any logic errors. </p>
</li>
</ul>
<p>This is a request sent from a script with a function and I'm using request to a Php page. After that it reads the echo and displays it on the screen. (Just in case anyone needs this information)</p>
Instead of using a
while
loop, just capturefetch_object()
once and useif
to test whether you get a true result.You should also use prepared statements, I show how to do that below.
You should not store clear text passwords and should use
password_hash()
andpassword_verify()
. I don't show that code below (it will require corresponding changes to your registration script).