Display error when condition not matched inside foreach - php

I am displaying data from mysql using foreach but there is also a if condition inside the for each. I want to display a message if this condition is not matched. the code is below;
<?php
// some other codes to connect data base etc.
$i = 0;
while($row = mysqli_fetch_assoc($result)) {
$lon[$i] = $row['lng'];
$lat[$i] = $row['lat'];
$status[$i] = $row['status'];
$title[$i] = $row['title'];
$property_id[$i] = $row['property_id'];
$price[$i] = $row['price'];
$availability[$i] = $row['availability'];
$type[$i] = $row['type'];
$bedrooms[$i] = $row['bedrooms'];
$lounges[$i] = $row['lounges'];
$type[$i] = $row['type'];
$time[$i] = $row['time'];
$i++;
}
for($i=0; $i<$count; $i++) {
$distance = Haversine($my_lat, $my_lon, $lat[$i], $lon[$i]);
if($distance < $radius) {
echo 'Display data';
} else{
echo "error message";
}
}
?>
After displaying message following this code:
if($distance < $radius) {
I want to display message if this condition is not met but nothing seem to work so far.

if($distance<$radius){
echo "This statement meets the criteria.";
}else{
echo "This statement doesn't meet the criteria.";
}
You should check the basics on how if/else works before diving into this.

Before make sure that your datatype is define.
http://php.net/manual/en/function.settype.php
Try not allow empty data:
if (empty($var)) {
echo '$var is either 0, empty, or not set at all';
}
After verify mojore points, simplify your conditions by:
elseif($distance >= $radius){
Like this you avoid Unexpect values.

first you print $distance and $radius and after put if condition so you can confirm what actually happened...

Related

Get all the values from the table and Count all the words with specific Word

Here is my Code
<?php
for ($x = 0; $x <= $n; $x++)
{
//Counting of rows
$countrow = get_rows($getvids);
if($offline == "Offline")
{
$apsys = "APSYS";
$offlined = "";
if ($getvids == $apsys || $getvids == $offlined )
{
echo "<tr>
<th>$x</th>
<th>$accntid[$x]</th>
<th>$fname[$x]</th>
<th>$lname[$x]</th>
<th>$vid[$x]</th>
<th>$vplatenum[$x]</th>
<th>$imei[$x]</th>
<th>$datas[1]</th>
<th>$datas[0]</th>
<th>$offline</th>";
echo "<th>$getvids</th>";
echo "<th><button type = 'button' class = 'btn btn-success viewbtn'> View Troubleshoot Report History</button></th>";
echo "</tr> ";
echo "total number of Rows:";
echo str_word_count($countrow);
}
else
{
}
}
else
{
}
}
?>
and here is my Function
<?php
function get_rows($getrowscount)
{
require ('db_connection.php');
$getrowscounts = $getrowscount;
//echo $getrowscounts;
return $getrowscounts;
}
//get_rows(); // call the function
?>
the table shows Two Rows with the value of = "APSYS"
I want to count the rows and show the output like this:
Total number of Rows: 2
but the output I can only get is like This:
Total number of Rows:1
Total number of Rows:1
Total number of Rows:0
can someone help me, I am a little bit confused about what will I use to count the rows?
Thanks.
How about this? Does this satifsfy your requirement?
<?php
$countrow = 0;
for ($x = 0; $x <= $n; $x++)
{
//Counting of rows
$countrow = $countrow + get_rows($getvids);
if($offline == "Offline")
{
//omitted
}
else
{
}
}
}
echo "total number of Rows:";
echo str_word_count($countrow);
?>
If you are trying to count them after fetching from the database, try to write a SQL query instead of your current approach.

how can I higlight the correct cell in PHP

I am trying to make a function in PHP which writes out a table, and looks in the database to find what cells should have info. the grid will always be the same size, but the content may be in different places.
I've gotten it to be able to look in the database, though it seems to only highlight the first cell, rather than the correct coordinates.
require("sql.php");
$sql = <<<SQL
SELECT *
FROM `maps`
WHERE `objpresent` = 1
SQL;
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
} // ran the query
$xobj = array();
$yobj = array();
while($row = $result->fetch_assoc()){
//echo $row['x'] . $row['y'] . $row['object'] . '<br />';
$xobj[] += $row['x'];
$yobj[] += $row['y'];
}// get the rows
//find whether the row is obstructed
for($a=0; $a<=20-1; $a++) //rows (y)
{
for($i=0; $i<=25-1; $i++) //cols (x)
{
echo "<td>"; //between these write the apt content
// if (empty($xobj[$i]) || empty($yobj[$a]) ){
// echo '0';
//} //detect whether there is even a record for this space
if(!empty($xobj[$i]))
{
if(!empty($yobj[$a]))
{
echo $xobj[$i]; //debug
if($xobj[$i] == $i)
{
//echo $xobj[$i];
echo "A";
}
}
}
//echo "<td><img src='emptysym.png'></img></td>";
echo "</td>"; //add textual descriptions for now, add icons later
}
echo "</tr>";
}
this is my current(though rather messy) code.
if there is a row with the column x saying 2, and the column y saying 3, then it should put a letter at (2,3.
is it possible to fix this, or is there a better method for this?
Use a 2-dimensional array whose indexes are the x and y values from the database:
$xyobj = array();
while($row = $result->fetch_assoc()){
$xyobj[$row['x']][$row['y']] = true;
}
Then your output loop should be:
for ($y = 0; $y < 20; $y++) {
echo '<tr>';
for ($x = 0; $x < 25; $x++) {
echo '<td>';
if (isset($xyobj[$x][$y])) {
echo 'A';
}
echo '</td>';
}
echo '</tr>';
}

php error count() displays "Array" or "m"

I'm trying to display different images from the database that are in the same field but the result is echoed either as "m" or "Array".
Here's my code:
$badges = $row['badges'];
$badges = explode(",", $badges);
$badge = count($badges);
if(empty($badges)) {
$badges = "";
} else {
$i = 0;
while($i <= $badge) {
$badges = "<img src='".$badges[$i]."' /> ";
$i++;
}
}
$rank = "<tr><td><img src='".$rank."' /> ".$badges."</td></tr>";
$rank is then echoed to the div that I want it to be displayed but the image src is always "m" or when I try putting the while in place of the $rank variable it echoes as "Array". Does anyone know why this is?
I would use another variable name, like badgeString as the output. Also, it seems like you want to append all the badges
if(empty($badges)) {
$badgeString = "";
} else {
$i = 0;
while($i <= $badge) {
$badgeString .= "<img src='".$badges[$i]."' /> ";
$i++;
}
}
$rank = "<tr><td><img src='".$rank."' /> ".$badgeString."</td></tr>";

Check if php mysql query result column is empty

I'm printing out a table with 27 cols from a database, so its obvious that it'll be aesthetically displeasing if 27 cols were visible on my screen. so this is one of the conditions i've been using to see if a particular col is empty, if it is empty then the table header will not be printed and if that isnt printed another if isset condition will not print the table data. But it isn't working out as planned. These are the variations i've tried and none of them are working P.S. $result = number of rows being returned by the query.
$i = 1;
while ($i <= $result)
{
if (!empty($array['Others'][$i]))
{
$others = print "<th>Others</th>";
break;
}
$i++;
}
$i = 0;
while ($i <= $result)
{
$emptyothers = !empty($array['Others'][$i]);
if ($emptyothers == '1')
{
$others= print "<th>Others</th>";
break;
}
$i++;
}
Your code should be like this:
$sql = mysql_query("SELECT * FROM table");
if (mysql_num_rows($sql) > 0) {
//your code...
} else {
print 'is empty';
}
Could you use array_key_exists()?
foreach($row in $result) {
if(array_key_exists('Others', $row)) {
if(!empty($row['Others']) {
print "<th>Others</th>";
break;
}
}
}

variable increment doesn't work

When I launch my web page, increment doesn't work correctly!
It should go like this: $i = from 1 to x (0,1,2,3,4,5,6 etc..).
But instead it jumps over every step giving result of (1,3,5,7 etc..).
Why is this code doing this?
<ul class="about">
<?php
$result = mysql_query("SELECT * FROM info WHERE id = 1");
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
$endBioTxt = explode("\n", $bioText);
for ($i=0; $i < count($endBioTxt);)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
$i++;
}
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
?>
</ul>
Output:
Sometext!(right side)
0
1
Sometext2!(right side)
2
3
...
Please DONT do this as other suggested:
for ($i=0; $i < count($endBioTxt); $i++)
do this:
$count = count($endBioTxt);
for ($i=0; $i < $count; $i++) {
}
No need to calculate the count every iteration.
Nacereddine was correct though about the fact that you don't need to do:
$i++;
inside your loop since the preferred (correct?) syntax is doing it in your loop call.
EDIT
You code just looks 'strange' to me.
Why are you doing:
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
???
That would just set $bioText with the last record (bio value) in the recordset.
EDIT 2
Also I don't think you really need a function to calculate the modulo of a number.
EDIT 3
If I understand your answer correctly you want 0 to be in the left li and 1 in the right li 2 in the left again and so on.
This should do it:
$endBioTxt = explode("\n", $bioText);
$i = 0;
foreach ($endBioTxt as $txt)
{
$class = 'left';
if ($i%2 == 1) {
$class = 'right';
}
echo '<li class="'.$class.'"><div>'.$txt.'</div></li>';
echo $i; // no idea why you want to do this since it would be invalid html
$i++;
}
Your for statement should be:
for ($i=0; $i < count($endBioTxt); $i++)
see http://us.php.net/manual/en/control-structures.for.php
$i++; You don't need this line inside a for loop, it's withing the for loop declaration that you should put it.
for ($i=0; $i < count($endBioTxt);$i++)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
//$i++; You don't need this line inside a for loop otherwise $i will be incremented twice
}
Edit: Unrelated but this isn't how you check whether a number is prime or not
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
This code works, please test it in your environment and then uncomment/comment what you need.
<?php
// This is how query should look like, not big fan of PHP but as far as I remember...
/*
$result = mysql_query("SELECT * FROM info WHERE id = 1");
$row = mysql_fetch_assoc($result);
$bioText = $row['bio'];
$endBioTxt = explode("\n", $bioText);
*/
$endBioTxt[0] = "one";
$endBioTxt[1] = "two";
$endBioTxt[2] = "three";
$endBioTxt[3] = "four";
$endBioTxt[4] = "five";
$totalElements = count($endBioTxt);
for ($i = 0; $i < $totalElements; $i++)
{
if ($i % 2)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
}
/*
// This is how you should test if all your array elements are set
if (isset($endBioTxt[$i]) == false)
{
echo "Array has some values that are not set...";
}
*/
}
Edit 1
Try using $endBioTxt = preg_split('/$\R?^/m', $bioTxt); instead of explode.

Categories