PHP is loading the same content endlessly - php

How can i prevent it from loading the same table row all over again and never stopping ? My head can't take it ... I know i somehow created an infinite loop so i searched on internet and i saw people doing almost the same but somehow it worked for them.
include_once "additional_code/dbh.inc.php";
session_start();
$savedUsername = $_SESSION["username"];
if (!isset($savedUsername) || empty($savedUsername)) {
header("location: login.php");
exit;
}
$sql = "SELECT * FROM messages WHERE sender = $savedUsername";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
if ($row > 0) {
echo "it works";
while($row) {
echo htmlspecialchars($row["sender"] . ": " . $row["msg"]);
echo "<br><br>";
}
}
else {
echo "It doesn't work";
}
?>

When you use
while($row) {
You are effectively creating an endless loop. Because $row is a defined variable, it's a turthy value - this makes it essentially become
while (true) {
What you want instead is to fetch each row, meaning that you must supply the mysqli_fetch_assoc() as the argument to your while. You also want to check the number of rows instead, as you are now fetching the first row (and it will not be visible in the loop).
if (mysqli_num_rows($result)> 0) {
echo "it works";
while($row = mysqli_fetch_assoc($result)) {
echo htmlspecialchars($row["sender"] . ": " . $row["msg"]);
echo "<br><br>";
}
}
else {
echo "It doesn't work";
}
You should also be aware that your code is vulnerable for SQL-injection attacks, and you should use prepared statements with MySQLi and bind your values instead of injecting the variables directly in your query.
How can I prevent SQL injection in PHP?

Change this:
$row = mysqli_fetch_assoc($result);
if ($row > 0)
{
echo "it works";
while($row)
{
echo htmlspecialchars($row["sender"] . ": " . $row["msg"]);
echo "<br><br>";
}
}
To this:
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
echo htmlspecialchars($row["sender"] . ": " . $row["msg"]);
echo "<br><br>";
}
}

You can first count with mysqli_num_rows if your query contains any records or not and then can use mysqli_fetch_assoc if records are there like below:
$sql = "SELECT * FROM messages WHERE sender = $savedUsername";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if ($count > 0) {
echo "it works";
while($row = mysqli_fetch_assoc($result)) {
echo htmlspecialchars($row["sender"] . ": " . $row["msg"]);
echo "<br><br>";
}
}
Always use Prepared Statements to make Queries more Secure

Related

php mysql issue with printing value on html page

I'm trying to query MySQL DB and print a single result on the page using PHP.
It's always going to be a single result, so I'm not sure if I need to loop
In any case, would anyone mind advising why the below doesn't work?
Thank you!!
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else {
echo "success";
}
$sql = "SELECT sum(Discounted_Value) as id FROM Orders WHERE Year = 2017";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Total 2017 " $row["id"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
If there will be only one result you can simplify code to:
$sql = "SELECT sum(Discounted_Value) as id FROM Orders WHERE Year = 2017";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo "Total 2017 " . $row["id"] . "<br>"; // Don't forget dots for concatenation

How can I get a value by it self using php from a database?

I am trying to access firstname by it self. I have the code below put together:
<?php
$sql = "SELECT firstname, lastname FROM guests WHERE option = $option";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "You Are " . $row["firstname"]. " " . $row["lastname"]. "<br>";
?>
It gives me You are Bob Testing. I need to convert them to self variable so I can use them anywhere. Like $row["firstname"] = $firstname; so then I could echo $firstname; But it won't work if I use $row["firstname"] = $firstname;
I think the issue is somewhere in how I form the result $result = mysqli_query($conn, $sql); Can I say something else here so then I could just use say $row["firstname"] = $firstname; and use like echo $firstname;? Thanks.
Firstly, if this is your actual code, it's missing a few closing braces.
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "You Are " . $row["firstname"]. " " . $row["lastname"]. "<br>";
} // this one was missing
} // as was this one
Now, assign a variable "to" the row(s) and not the other way around.
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$first = $row["firstname"];
$last = $row["lastname"];
}
echo "You are " . $first . " " . $last . "<br>";
}
However the above will only echo a single row, therefore you will need to place the echo "inside" the while loop in order to echo all the rows in your table:
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$first = $row["firstname"];
$last = $row["lastname"];
echo "You are " . $first . " " . $last . "<br>";
}
}
Something about this though WHERE option = $option";
If $option is a string, it will need to be quoted:
WHERE option = '$option'";
otherwise, MySQL will see that as a syntax error. Check for errors on your query:
http://php.net/manual/en/mysqli.error.php
It will also be prone to an SQL injection, therefore it is best you use a prepared statement.
https://en.wikipedia.org/wiki/Prepared_statement
Seeing you may be new to working with MySQL, it's best to learn about protecting yourself against SQL injection. Here is a good article about it on Stack:
How can I prevent SQL injection in PHP?

counter in php when client press button

I have this part of code in php . when player press button in client (using ajax) I want my database show next record. but I won't.
if(isset($_POST['req'])){
$counter++;
$sql = "SELECT question FROM mytable WHERE id = $counter";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["id"]." ". $row["question"]. " " . "<br>";
}
} else {
echo "0 results";
}
}
I would suggest storing your counter in a session. Then each time a player does this action you can give them the next row like so :-
session_start();
if(isset($_POST['req'])){
if ( ! isset($_SESSION['counter']) ) {
$_SESSION['counter'] = 1;
} else {
$_SESSION['counter'] = $_SESSION['counter'] + 1;
}
$sql = "SELECT question FROM mytable WHERE id = {$_SESSION['counter']}";
$result = $conn->query($sql);
if ( ! $result ) {
// log error to error log
error_log(print_r($conn->errorinfo(),true), 3, 'app_error.log');
echo "Temporary database issues, please try again later";
header('Location: error_page.php');
exit;
}
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
echo $row["id"]." ". $row["question"]. " " . "<br>";
} else {
echo "0 results";
}
}
The easy way is to send the current id along in the Ajax request. Increment it then use it to pull the next question from your database

If value in certain cell equals "Certain Text" echo "Text"

I'm trying to get this to echo a warning message when the cell contains a certain text like "0" or "N/A". It would work when there was no value entered in the first place, but I can't get it to echo when there is already a certain value. Any help would be great. Thanks!
<?php
$listing = "$_POST[listing]";
$sql = "SELECT open_house_attended FROM property_flyers WHERE street_property = '$listing' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "</span><span class='report_bignumber'><br>". $row["open_house_attended"]."</span>";
}
} else {
echo "<br> ". $noresults . "</span>";
}
?>
You can use a little regex -
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
preg_match(trim($row["open_house_attended"]), '/[0]|[N\/A]/', $matches); // try to match '0' or 'N/A'
if(count($matches) == 0) { // do we have matches?
echo "</span><span class='report_bignumber'><br>". $row["open_house_attended"]."</span>";
} else {
echo "<br> ". $noresults . "</span>";
}
}
}
?>
Or you can go a little more directly -
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$ohCount = $row["open_house_attended"];
if(( $ohCount != '0') && ($ohCount != 'N/A')) { // do we have matches?
echo "</span><span class='report_bignumber'><br>". $ohCount ."</span>";
} else {
echo "<br> ". $noresults . "</span>";
}
}
}
?>
preg_match()
$sql = "SELECT open_house_attended FROM property_flyers WHERE street_property = '$listing' AND open_house_attended NOT IN ('0', 'N/A')";
use NOT IN and a list of values to reject. It's one option anyway. The preg match option works as well, just it asks php to do the work and this asks sql to do it.

how do i display this columns side by side

im having some problem here. basically, i want to compare columns. so i fetched object and the comparing results appeared just as expected. however, it does not return the compare value anymore after i added the fetch_array to view the current table hoping that the compare value would appear beside the compare value. is there any way i could run the compare code and make it appear the table? i tried a query but it would only work in MySQL and not PHP.
$query = "SELECT * FROM system_audit"; $result = mysql_query($query) or die(mysql_error());
echo " ID Type Setting Value ";
while($row = mysql_fetch_array($result)) {
echo $row['ID'];
echo $row['Type'];
echo $row['Setting'];
echo $row['Value'];
}
while ($row = mysql_fetch_object($result)) {
if($row->Setting != $row->Value) {
echo "X";
} else {
echo "O";
}
}
Your code contains a lot of echo's that have no use. I would suggest learning PHP a bit more.
Your compare is wrong, this should work :
$query = "SELECT * FROM system_audit";
$result = mysql_query($query) or die(mysql_error());
echo " ID Type Setting Value ";
while($row = mysql_fetch_array($result)) {
echo $row['ID'] . "<br>";
echo $row['Type'] . "<br>";
echo $row['Setting'] . "<br>";
echo $row['Value'] . "<br>";
if($row['Setting'] != $row['Value']) {
echo "X" . "<br>";
}
else {
echo "O" . "<br>";
}
echo "<br>";

Categories