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.
Related
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
Basically I'm doing digital signage and I'm trying to get names to be pulled from a MySQL database to a PHP page. Right now its all centered in one column, but I want the results to be in two columns side by side. How can I do this?
$sql = "SELECT * FROM donor WHERE DonationAmount = 5000 AND Category = '1' or DonationAmount = 5000 AND Category IS NULL ORDER BY LastName ASC";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
// test if the DisplayName field is empty or not
if(empty($row['DisplayName']))
{
// it's empty!
if(empty($row['FirstName'])){
echo $row['LastName']. "<br>";
}
else{
echo $row["LastName"]. ", " . $row["FirstName"]. "<br>";
}
}else{
// Do stuff with the field
echo $row["DisplayName"]. "<br>";
}
}
} else {
}
Basically I want this data to be spread across two columns instead of 1 single page.
output the strings like this:
echo "<span style=\"width:50%;float:left;\">".$row['LastName']."</span>";
do not forget to remove <br /> from each output
You can use tables, and count the rows to determine if you need to start a new table row.
$i = 0;
$total_rows = $result->num_rows;
echo "<table><tr>";
while($row = mysqli_fetch_assoc($result)) {
// test if the DisplayName field is empty or not
echo "<td>";
if(empty($row['DisplayName']))
{
// it's empty!
if(empty($row['FirstName'])){
echo $row['LastName'];
}
else{
echo $row["LastName"]. ", " . $row["FirstName"];
}
}else{
// Do stuff with the field
echo $row["DisplayName"]. "";
}
echo "</td>";
$i++;
if($i % 2 == 0 && $i != $total_rows) {
echo "</tr><tr>";
}
}
echo "</tr></table>";
if your content is in <div id="myDiv"> use this JS function and call it after the content loads
function splitValues() {
var output = "";
var names = document.getElementById('myDiv').innerHTML.split("<br>");
for(var i in names) {
output += "<span style=\"width:50%;float:left;display:inline-block;text-align:center;\">"+names[i]+"</span>";
}
document.getElementById('myDiv').innerHTML = output;
}
$sql = "SELECT * FROM today WHERE heading='$heading' and day='$day'";
$sql1 = "SELECT * FROM today WHERE day='$day'";
$result = $conn->query($sql);
$result1 = $conn->query($sql1);
if ($result->num_rows > 0) {
echo "<div id='post'><h1>".$row["heading"]."</h1>
<aside class='related-post'>".while($row = $result1->fetch_assoc())
{echo'<img src='".$row["image"]."'>;}
.</aside>}";
I have been using while loops for fetching data from table. My connection is working is perfect but I need another loop in the first that is not working. Isn't it the good way?
Update: I tried to finish echo and again started as follow but still an error
while($row = $result->fetch_assoc()) {
echo "<div id='post'><h1>"
.$row["heading"].
"</h1><div class='post-side'><img class='post-image' src='"
.$row["image"].
"'><div class='post-data'><p><strong>Age: </strong><span>$age</span></p><p><strong>Date of birth: </strong><span>"
.$row["day"].
"-"
.$row["month"].
"-"
.$row["year"].
"</span></p></div></div></div><div class='description'><p>"
.$row["description"].
"</p></div><div class='bottom-related'><aside class='related-post'>";
while($row = $result1->fetch_assoc())
{echo"<img src='"
.$row["image"].
"'>/";}.echo"</aside><aside class='ad2'>".$includead."</aside></div>";
}
echo "</div>";
} else {
echo "No table found";
}
$conn->close();
You're trying to concatenate to a string a WHILE loop; this is wrong.
You should echo your first part, end with it and then do your while loop, and echo the end afterwards:
Your quotes are a bit messed up as well
if ($result->num_rows > 0)
{
echo "<div id='post'><h1>".$row["heading"]."</h1>
<aside class='related-post'>";
while($row = $result1->fetch_assoc())
{
echo'<img src="'.$row["image"].'">';
}
echo '</aside>';
}
You can't concatene while with String, it's a syntaxic error
Also, you have a probleme when trying to echo a String, you can use this syntax:
echo "PHP"; // will evaluate PHP variables and whitespace inside a string
echo 'PHP'; // will evaluate nothing;
But you can not start flushing a string ' and finish by " or vice-versa.
Here the correct code :
<?php
$sql = "SELECT * FROM today WHERE heading='$heading' and day='$day'";
$sql1 = "SELECT * FROM today WHERE day='$day'";
$result = $conn->query($sql);
$result1 = $conn->query($sql1);
if ($result->num_rows > 0) {
echo "<div id='post'><h1>" . $row["heading"] . "</h1><aside class='related-post'>";
while($row = $result1->fetch_assoc()) {
echo'<img src="' . $row["image"] .'">';
}
echo "</aside>";
}
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
How would I do let the user know if there wasnt any rows found?
And if it finds (for example) 26 rows I want it to print that it found 26 hits (Your search for "hey" gave 26 results)
$name = mysql_real_escape_string($_POST['player_name']);
$q = mysql_query("SELECT * FROM players WHERE name LIKE '%$name%'");
while ($row = mysql_fetch_array($q)) {
$name = $row['name'];
echo "<ul>\n";
echo "<li>" . "" .$name . " </li>\n";
echo "</ul>";
}
Use mysql_num_rows:
$rowCount = mysql_num_rows($q);
if ($rowCount === 0)
{
echo 'Found nothing!';
}
else
{
echo "Found $rowCount rows!";
while ($row = mysql_fetch_array($q))
{
$name = $row['name'];
echo "<ul>\n";
echo "<li>" . "" .$name . " </li>\n";
echo "</ul>";
}
}
Check out mysql_num_rows
mysql_num_rows
$numberOfResults = mysql_num_rows($q);