echo inside if else in php - php

I want to use echo inside if...else so i can print "-" if the data doesn't exist in the database, and if the data exist in database, print the data. Until now, my "-" doesn't shows up if the data doesn't exist in database.
This is for printing on localhost .php
<?php
$kata='';
$no=1;
$data = mysqli_query($koneksi,"SELECT msdosen.`IDDOSEN`, `POSITION`,
`COMPANY`, `START`, `END`
FROM trprofessionalhis
INNER JOIN msdosen ON msdosen.IDDOSEN = trprofessionalhis.IDDOSEN
WHERE trprofessionalhis.IDDOSEN ='$id'
ORDER BY trprofessionalhis.`START` DESC");
while($d = mysqli_fetch_array($data)){
?>
<br><?php echo $d['POSITION'];?><br><?php echo $d['COMPANY'];?>
<br><?php echo $d['START'];?>-<?php echo $d['END']?><br>
<?php
if (empty($d['POSITION'])){
echo '-';
}
else{
echo '';
}
}
?>
I expect the output prints "-" if the data doesn't exist in database.

You can use ternary operator. Here is example:
echo empty($d['POSITION']) ? $d['POSITION'] : '-';
If you are using PHP 7+ version, there is more short way:
echo $d['POSITION'] ?? '-';
More examples about ternary operator.

If your SQL query returns no result, $d will return NULL and the while-loop will end before it starts. Therefore none of the echo statements in the loop will be run.
Given the screenshot in this comment, I think this is the case. That is why your if-then never ran in the case intended and shows nothing:
As #catcon mentioned in comment, you can use mysqli_num_row to check if there is any result at all. That way you may still show something when there is no result:
<?php
$kata='';
$no=1;
$data = mysqli_query($koneksi,"SELECT msdosen.`IDDOSEN`, `POSITION`,
`COMPANY`, `START`, `END`
FROM trprofessionalhis
INNER JOIN msdosen ON msdosen.IDDOSEN = trprofessionalhis.IDDOSEN
WHERE trprofessionalhis.IDDOSEN ='$id'
ORDER BY trprofessionalhis.`START` DESC");
// add this to print "-" if the query returns no result
if (mysqli_num_row($data) <= 0) {
echo '<br> -';
}
?>
<?php while($d = mysqli_fetch_array($data)) { ?>
<br><?php echo $d['POSITION'];?><br><?php echo $d['COMPANY'];?>
<br><?php echo $d['START'];?>-<?php echo $d['END']?>
<?php } ?>

Related

Find and display certain strings from database with if and else

The php-code below finds and displays an external url as a link from a database. Sometimes there is a phonenumber instead of an url in that row. How can I manage to echo out the phonenumber without making it to a link. I guess it will work with if and else but I'm not finding out how to display it the right way. My code below:
<?php
$ticketurl = $row ['show_external_url'];
$query = mysqli_query( $connection,"SELECT *, DATE_FORMAT(`show_date`, '%W (%d/%m/%y)') as dateFormatted
FROM nhto_gigpress_shows
WHERE `show_date` >= CURDATE()
AND WEEKDAY(nhto_gigpress_shows.show_date) >= 5
ORDER By show_date" );
$row = mysqli_fetch_array( $query ); {
echo "<a href='".$ticketurl."'>BOOK</a>";
}
?>
Try to check whether the column has any data or not and use condition
inside the while loop:
if(empty($row['url'])){
echo $row['phone'];
}
else{
echo 'BOOK';
}

PHP/SQL fetch query data

I'm having a problem in this simple SQL/PHP query...
<?php
$course=$row['course'];
include('../db.php');
$cat=$row['cat'];
$result = mysql_query("SELECT * FROM question WHERE course='$course' AND cat='$cat'");
while($row = mysql_fetch_array($result))
{
echo $row['question'].'?<br>';
$qid=$row['qid'];
echo '<input type="hidden" name="qqqq[]" value="'.$qid.'" />';
echo '<select name="answer[]">';
echo '<option>Select Answer></option>';
$resultik = mysql_query("SELECT * FROM choices WHERE question='$qid' ORDER BY RAND() LIMIT 4");
while($rowik = mysql_fetch_array($resultik))
{
echo '<option>';
echo $rowik['opt'];
echo '</option>';
}
echo '</select><br><br>';
}
?>
Basically, this is a online examination. I want to display all the questions if the student will login. And the questions will be order/arrange according by their course. But eventually, there's no display at all. Not even a single letter will display.
Any help would be appreciated. Thank you so much.
In this there must some POST or GET values to get the course and cat which means
$course=$row['course'];
$cat=$row['cat'];
Since the $row is empty this is the case it will not display anything. Check with isset() like following
$course = isset($row['course']) ? $row['course'] : 'COURSE';
$cat = isset($row['cat']) ? $row['cat'] : 'CAT';
The included file include('../db.php'); please check the database connectivity has established or not?.

while loop not cycling through as expected

I have a loop that runs through returned rows from a MySQL query and performs commands.
When the data is displayed on the webpage (seen at the end of the pasted code), the requested_date (from the $result_dec query) is cycling through correctly, but the memPayout(from the $emailcompleted query) is not. Where it shows the memPayout it is just listing the same number for each date.
When I run this in phpmyadmin, I see that different dates have different memPayouts..so I know there is a bug here.
I appreciate the help.
UPDATE: I've updated the old code with the new one that I adjusted. I tried to wrap the email earnings query with the original foreach. I also removed the unnecessary extra bgcolor switch. The result on my webpage is still the same as before. Any more advice is really appreciated.
<?php
//--------------------- Code for Decline TRANSACTION --------------------------------------
$u_id = $_SESSION['user_ses']['id'];
$result_dec = #mysql_query("(select trv.tr_user_id , usr.full_name ,usr.email , usr.paypal , trv.requested_date, trv.requested_status, trv.click_payment_status, trv.tracking_id
from tbl_trackvalue as trv ,tbl_tracking as t , tbl_offers as off , tblusers as usr
where t.id=trv.tracking_id and off.id=t.offer_id and usr.id=trv.tr_user_id and usr.id='1454'
and trv.payment_status='pending' and trv.requested_status='declined' group by trv.tr_user_id, trv.requested_date order by trv.requested_date asc )
union all
(select trv.tr_user_id , usr.full_name ,usr.email , usr.paypal , trv.click_request_date, trv.requested_status, trv.click_payment_status, trv.tracking_id
from tbl_trackvalue as trv ,tbl_tracking as t , tbl_offers as off , tblusers as usr
where t.id=trv.tracking_id and off.id=t.offer_id and usr.id=trv.tr_user_id and usr.id='1454'
and trv.payment_status='pending' and trv.click_payment_status='declined' group by trv.tr_user_id, trv.click_request_date order by trv.requested_date asc ) ");
$nr = mysql_num_rows($result_dec);
$categories_d = array();
while($row = mysql_fetch_array($result_dec))
{
$categories_d[] = $row;
}
if(count($categories_d)>0)
{
$counter=0;
foreach($categories_d as $index=>$rec)
{
$counter++;
if ($counter % 2 == 0)
{
$bgcolor = "#FFFFFF";
}
else
{
$bgcolor = "#F5F7D9";
}
$userId=$rec['tr_user_id'];
$EmailCompletedOffer=#mysql_query("select off.member_amount as memPayout
from tbl_trackvalue as trv ,tbl_tracking as t , tbl_offers as off , tblusers as usr
where t.id=trv.tracking_id and off.id=t.offer_id and off.offer_type='mailchimp' and usr.id=trv.tr_user_id and
trv.tr_user_id=$userId and trv.requested_date='".$requested_date."' and trv.payment_status='pending' and trv.total_conversion !=0 and trv.requested_status='declined' ");
$rowemailEarn=#mysql_fetch_array($EmailCompletedOffer);
$totalEmailEarnAmount1=$rowemailEarn['memPayout'];
?>
<div class="datarow_his">
<div class="his_onecol1"><?php echo '$'. $totalEmailEarnAmount1;?> </div>
<div class="his_onecol1"> <?php echo "Declined"; ?> </div>
<div class="his_onecol2"><?php echo date("M j,Y " ,strtotime($rec['requested_date']));?></div>
<!--<div class="his_onecol1"><?php //echo date("M j,Y " ,strtotime($rec['paid_date']));?></div>-->
</div>
<p><?php echo $totalEmailEarnAmount1?></p>
<?php /*}
} */
}
}
?>
Your code roughly looks like this:
fetch categories
if(categories not empty) {
foreach(category) {
set $bgcolor and $userId (has no effect)
}
get query results for the last $userID and set $totalEmailEarnAmount1
if(categories not empty) {
foreach(category) {
set $bgcolor again (has no effect)
generate a div using $totalEmailEarnAmount1
}
}
}
Since you set $totalEmailEarnAmount1 outside the final foreach, it has the same value on every iteration of the loop.
(If you indent your code in a way that is consistent with its structure, errors like this will become obvious. The messy indentation makes it hard for you to see what is going on.)

PHP MySQL omit result if contains phrase

I need some help with some PHP and MySQL code. At the moment I have a php file which displays the contents of a table in my database. I would like it to omit results that match "Not Booked". So the file only shows me slots which are booked. Here is my code:
<link href="../css/pagestyle.css" rel="stylesheet" type="text/css" />
<?php
include("../config.php");
include("functions.php");
if($logged["level"] == "HDJ" OR $logged["level"] == "SA") {
echo "<div class=\"head\">View Booked Slots</div>
<img src=\"../images/spacer.png\" width=\"5\" height=\"5\">
<div class=\"board\">Here you can view booked slots.</div>
<img src=\"../images/spacer.png\" width=\"5\" height=\"5\">
<table width=\"580px\" class=\"board\" border=\>";
$order = "SELECT * FROM timetable";
$result = mysql_query($order);
while ($row=mysql_fetch_array($result)){
echo ("<tr><td>$row[username]</td>");
</tr>");
}
echo "
</table>
";
} else {
echo ("<div class=\"caution\">Access is denied.</div>");
}
?>
Modify the query not to pull them in the first place.
$order = "SELECT * FROM timetable WHERE <the column> <> 'Not Booked';
Replace <the column> with the correct column name in your table where Not Booked appears.
It is often not advisable to intermix database logic and display logic as you have done here. Instead, you ought to do the query before outputting your table, and store its results in an array. Then loop over the array to display your table.
$order = "SELECT * FROM timetable WHERE somecolumn <> 'Not Booked'";
$result = mysql_query($order);
// Error checking
if (!$result) {
// output error, take other action
}
else {
while ($row=mysql_fetch_array($result)){
// Append all results onto an array
$rowset[] = $row;
}
}
Later, loop over the array to output your values. Dont' forget to escape it for HTML output with htmlspecialchars().
foreach ($rowset as $row) {
echo "<tr><td>" . htmlspecialchars($row['username']) . "</td></tr>";
}
In your mySQL code:
SELECT * FROM timetable WHERE myvariable <> 'Not Booked'
Michael's answer will only pull out results that MATCH 'Not Booked' rather than omit them. Tweak the code to:
$order = "SELECT * FROM timetable WHERE <the column> <> 'Not Booked';
And you'll get all the booked ones (assuming there are only two states)

msql fetch array no longer listing all results

I have a code that I have used over and over again before and now it's messing up. All I want to do is list information from the database into the table on the page, but now it will only show one result, instead of all the results it has found.
<table>
<tr><td style="background-color:#009745; color:#FFFFFF"><center><strong>Address Book</strong></center></td></tr>
<tr>
<?php
$getids = mysql_query("SELECT id, first_name, last_name FROM accounts WHERE s1='$id' ORDER BY id DESC", $db);
if (mysql_num_rows($getids) > 0) {
while ($gids = mysql_fetch_array($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
}
?>
<td><?= $ab_id ?> - <?= $ab_fn . " " . $ab_ln ?></td>
<?php
} else {
?>
<td><center>No Contacts</center></td>
<?php
}
?>
</tr>
</table>
please help me with this.
Thank You for your help :)
I love this site!! I can always get answers when I need them.
I saw two thing wrong
you are using mysql_fetch_array and later you are using string indexes to print the result
print the things in loop it is overriding values and just storing last row
if (mysql_num_rows($getids) > 0) {
while ($gids = mysql_fetch_assoc($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
echo '<td>'.$ab_id.' -'. $ab_fn.''.$ab_ln.' </td>';
}
In this messy code you're closing the while loop too early:
while ($gids = mysql_fetch_array($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
}
Only the last retrieved row is used later on. Also, don't use mysql_fetch_array if you're not accessing the numeric indeces of your result. Use mysql_fetch_assoc instead.

Categories