MySQL return result if 0 rows returned - php

I have this PHP code:
$query = "SELECT name, COUNT(message) FROM guestbook_message WHERE name='".$req_user_info['username']."' GROUP BY name";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo "Messages posted: ". $row['COUNT(message)'] ."";
echo "<br />";
}
Which will show the amount of comments a user has posted.
How do I make it return a value if there is no messages posted from that user? Currently is displays nothing at all. But I want it to show "Messages posted: 0"
Any ideas?

Check the number of results returned in result using mysql_num_rows.
$query = "SELECT name, COUNT(message) FROM guestbook_message WHERE name='".$req_user_info['username']."' GROUP BY name";
$result = mysql_query($query) or die(mysql_error());
if(mysql_num_rows($result) > 0)
while($row = mysql_fetch_array($result))
{
echo "Messages posted: ". $row['COUNT(message)'] ."";
echo "<br />";
}
else
echo "NO Messages posted. <br />";

if ($row = mysql_fetch_array($result)) {
echo "Messages posted: ". $row['COUNT(message)'] . "";
echo "<br />";
}
else {
echo "Messages posted: 0";
echo "<br />";
}

Replace $row['COUNT(message)'] with the tertiary operator:
( $row['COUNT(message)'] > 0 ? $row['COUNT(message)'] : 0 )
This is basically a compacted if... else... statement.

Related

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.

Display data from database depending on the how many I have entered

In my database and more specific in the table named portfolio a user with a speficic username can store more than one data. The columns of the database are id,username,portfolio and portfolio_description
and I want to echo in my web page all the data for this username for example username=nbourlai. Until now I can echo only the first row for each username what is the loop that i can use in order to echo as many time is the id number.
Below is the current result and i want to create Portfolio and Portfolio description to be displayed with the appropriate values as many time as the highest id number is for the specific user.
Here is my code...
$portfolio = queryMysql("SELECT portfolio,portfolio_description FROM portfolio WHERE username='nbourlai'");
$row = mysql_fetch_row($portfolio);
echo "<h2>Portfolio</h2>";
echo "Portfolio: ";
echo stripslashes($row[0]) . "<br/>Portfolio Description: ";
echo stripslashes($row[1]) . "<br clear=left /><br />";
Can you help me please?
Are you looking for while loop like this?
$portfolio = queryMysql("SELECT portfolio,portfolio_description FROM portfolio WHERE username='nbourlai'");
echo "<h2>Portfolio</h2>";
while($row = mysql_fetch_row($portfolio)){
echo "Portfolio: ";
echo stripslashes($row[0]) . "<br/>Portfolio Description: ";
echo stripslashes($row[1]) . "<br clear=left /><br />";
}
or, like this?
$portfolio = queryMysql("SELECT username,portfolio,portfolio_description FROM portfolio ORDER BY username");
$username = '';
while($row = mysql_fetch_row($portfolio)){
if($username != $row[0]){
echo "<h1>".$row[0]."</h1>";
echo "<h2>Portfolio</h2>";
echo "Portfolio: ";
echo stripslashes($row[1]) . "<br/>Portfolio Description: ";
echo stripslashes($row[2]) . "<br clear=left /><br />";
}else{
echo "Portfolio: ";
echo stripslashes($row[1]) . "<br/>Portfolio Description: ";
echo stripslashes($row[2]) . "<br clear=left /><br />";
}
$username = $row[0];
}

Single row repeating instead of displaying

I'm pretty new at PHP/MySQL, so please be patient with me.
I am trying to get a list of members in a table to show up on a page. Right now it's showing the first member about 10 times and not displaying anyone else's name. I DID have it working, but I don't know what happened. I just want it to display everyone's name once. Here is my code:
<?php $select = mysql_query("SELECT * FROM `member_staff` WHERE `username`='$_SESSION[USR_LOGIN]' AND `status`='Active'");
$row = mysql_fetch_array($select);
$rows = mysql_num_rows($select);
$teaching = $row[teaching];
if ($rows==0){echo "Sorry, you don't appear to be a professor.";}
else { ?>
<?php }
$select2 = mysql_query("SELECT * FROM `classes_enrolled` WHERE `course`='" . $teaching . "' ORDER BY `student_name`") or die(mysql_error());
$count = mysql_num_rows($select2);
$row2 = mysql_fetch_array($select2);
$student=$row2[student_name];
if($count==NULL) {
echo "<table width=\"80%\">\n";
echo "<tr><td><center>Nobody has registered for your class yet!</center></td></tr>\n";
echo "</table>\n";
echo "<br /><br />\n\n";
}
else {
echo "<center><font size=\"3\"><b>YEAR 1, TERM 2</b></font></center>";
echo "<table width=\"80%\" class=\"table-stripes\">\n";
echo "<tr><td width=\"50%\"><b>STUDENT</b></td></tr>\n";
$select3 = mysql_query("SELECT * FROM `members` WHERE `username`='" . $student . "'") or die(mysql_error());
$row3 = mysql_fetch_array($select3);
while($row2 = mysql_fetch_array($select2)) {
$house=$row3[house];
echo "<tr><td><strong class=\"$house\">$student</strong></td></tr>";
}
echo "</table>"; }
?>
I miss look on your code, since it is mess, but disregard the mysqli and mysql thing, you want to show how many student in the teacher's classes.
<?php $select = mysql_query("SELECT * FROM `member_staff` WHERE `username`='$_SESSION[USR_LOGIN]' AND `status`='Active'");
$row = mysql_fetch_array($select);
$rows = mysql_num_rows($select);
$teaching = $row[teaching]; <--- This only get first row of the course, if you want multiple course under same username, you need to loop it.
if ($rows==0){echo "Sorry, you don't appear to be a professor.";}
else { ?>
<?php }
$select2 = mysql_query("SELECT * FROM `classes_enrolled` WHERE `course`='" . $teaching . "' ORDER BY `student_name`") or die(mysql_error());
$count = mysql_num_rows($select2);
$row2 = mysql_fetch_array($select2);
$student=$row2[student_name]; <----- This only get the first row of the student name, if you want multiple student under a course, you need to loop it.
if($count==NULL) {
echo "<table width=\"80%\">\n";
echo "<tr><td><center>Nobody has registered for your class yet!</center></td></tr>\n";
echo "</table>\n";
echo "<br /><br />\n\n";
}
else {
echo "<center><font size=\"3\"><b>YEAR 1, TERM 2</b></font></center>";
echo "<table width=\"80%\" class=\"table-stripes\">\n";
echo "<tr><td width=\"50%\"><b>STUDENT</b></td></tr>\n";
$select3 = mysql_query("SELECT * FROM `members` WHERE `username`='" . $student . "'") or die(mysql_error());
$row3 = mysql_fetch_array($select3);
while($row2 = mysql_fetch_array($select2)) {
$house=$row3[house]; <----This only show the first row of $house under same student, so you need to loop it too.
echo "<tr><td><strong class=\"$house\">$student</strong></td></tr>";
}
echo "</table>"; }
?>
So what you really want to do is
<?php
$select = mysql_query("SELECT * FROM `member_staff` WHERE `username`='$_SESSION[USR_LOGIN]' AND `status`='Active'");
$rows = mysql_num_rows($select);
if ($rows==0){echo "Sorry, you don't appear to be a professor.";}
else { ?>
<?php }
while( $row = mysqli_fetch_array( $select ) ) {
$teaching = $row[teaching];
$select2 = mysql_query("SELECT * FROM `classes_enrolled` WHERE `course`='" . $teaching . "' ORDER BY `student_name`") or die(mysql_error());
$count = mysql_num_rows($select2);
if($count==NULL) {
echo "<table width=\"80%\">\n";
echo "<tr><td><center>Nobody has registered for your class yet!</center></td></tr>\n";
echo "</table>\n";
echo "<br /><br />\n\n";
} else {
while( $row2 = mysql_fetch_array($select2) ) {
$student=$row2[student_name];
echo "<center><font size=\"3\"><b>YEAR 1, TERM 2</b></font></center>";
echo "<table width=\"80%\" class=\"table-stripes\">\n";
echo "<tr><td width=\"50%\"><b>STUDENT</b></td></tr>\n";
$select3 = mysql_query("SELECT * FROM `members` WHERE `username`='" . $student . "'") or die(mysql_error());
while($row3 = mysql_fetch_array($select3)) {
$house=$row3[house];
echo "<tr><td><strong class=\"$house\">$student</strong></td></tr>";
}
echo "</table>";
}
} // END ELSE
}
} // END ELSE
?>

Only Displaying one row Mysql

I want this data to display all the results, in the query I get 129 results. But when I display it on the page I only get one row. I have used very similar code to get multiple results before, so I know it`s something simple, but I just can't get it. Any thoughts would be greatly appreciated!
<?php
$sql = "SELECT SUM(datamb) AS value_sum FROM maindata GROUP BY phonenumber";
$sql1 = "select dataplan as currentplan from maindata GROUP BY phonenumber";
$sql2 = "SELECT DISTINCT phonenumber AS value_sum1 FROM maindata";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
$result1 = mysql_query($sql2);
if (!$result1) {
echo "Could not successfully run query ($sql1) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result1) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
$result2 = mysql_query($sql2);
if (!$result2) {
echo "Could not successfully run query ($sql2) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result2) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)){
echo "<TABLE id='display'>";
echo "<td><b>Data Usage This Period: ". ROUND ($row["value_sum"],2) . "MB</b></td> ";
}
while ($row1 = mysql_fetch_assoc($result1)){
echo "<TABLE id='display'>";
echo "<td><b>Data Plan: ". $row1["currentplan"] . "</b></td> ";
}
while ($row2 = mysql_fetch_assoc($result2)){
echo "<TABLE id='display'>";
echo "<td><b>Phone Number: ". $row2["value_sum1"] . "</b></td> ";
}
?>
Updated based on suggestions - Very helpful thank you, I am very close, all values are correct but I can not get them in the same table, thoughts?
TRY To use ,
Loop in you code eg.
$result1 = mysql_query("SELECT DISTINCT phonenumber AS value_sum1 FROM maindata");
echo '<table>';
echo '<tr>';
echo '<th>id</th>';
echo '</tr>';
while($record = mysql_fetch_assoc($result))
{
echo '<tr>';
foreach ($record as $val)
{
echo '<td>'.$val.'</td>';
}
echo '</tr>';
}
echo '</table>';
Add
"LIMIT 0, 1" at the end of query
or
edit query like "select TOP 1 from....."
Lets make it easy on you ;)
have a look here how to use mysql_fetch_assoc
http://php.net/manual/en/function.mysql-fetch-assoc.php
follow the examples, you will be done in a sec.

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