PHP / MySQL Simple IF / ELSE not so simple - php

I think my mind must be going through a Boxing Day mess.
I am building a basic comment section for every game a sports team plays.
So, when no comments are entered (in the MySQL DB), I simply want to display "Be the first to enter a comment"; otherwise, display the comment results table in html format.
I can easily display the comment result table.
For some reason, I can't get the IF no comments to work properly. Feel so amateurish right now . . . :-)
I have declared row count:
$row_count = 0;
I am adding to the count inside the while statement
while($row = mysql_fetch_array($result))
{
// adding to count
$row_count++;
My count is working as I can display the row number to the screen.
Here is IF / ELSE my code:
if ($row_count === 0) {
echo "<p>Be the first to enter a game comment and earn points toward your next fan badge.</p>";
} else {
// no need to show code as this already works!

you can use
mysql_num_rows($queryReference)
Hope this helps.
Thanks.

Please do one thing print this value using below function and tell me what is output
var_dump($row_count);
or you can use == instead of ===

$query = mysql_query("SELECT * FROM comments");
$c = mysql_num_rows($query);
if($c==0) {
echo "<p>Be the first to enter a game comment and earn points toward your next fan badge.</p>";
}
else {
while($row = mysql_fetch_array($query))
{
$vars = $row[index];
}
}

$row_count = 0;
I am adding to the count inside the while statement
while($row = mysql_fetch_array($result))
{
// adding to count
$row_count++;
}
My count is working as I can display the row number to the screen.
Here is IF / ELSE code:
if ($row_count == 0) {
echo "<p>Be the first to enter a game comment and earn points toward your next fan badge.</p>";
} else {
// no need to show code as this already works!
}

Related

How to Exclude selection and all related (MySQL + PHP)

I am trying to solve a mysteries code that writing a number in a choice I will get all opposite of that number
I did almost done with that the only problem with it I might have the opposite recalled as he does have another recorded in another course
In more word my PHP about courses when I do ask MY PHP course it well give me all people how did not take course 1 but some people were recalled as they have other courses
The Problem when I choose For Example Course X I do get All Who Did not Take Course X But Some where Called From The same Table cause They Do Have Taken Other Courses In the same table
I did resolve The first Problem Using the following code
if(isset($_GET['course_guid']) && $_GET['course_guid']!="" )
$f.=" AND s.course_guid != '".$_GET['course_guid']."'";
And I Did Create Another page Select.php To Omit All Identified People from Orig.php using The Following Code
<?php
if(isset($_GET['id']))
foreach($_GET as $key => $post)
$_GET[$key]=m($post);
$ff="";
if(isset($_GET['id']) && $_GET['id']!="")
$ff.=" AND cs.id = '".$_GET['id']."' ";
$prns =(isset($_GET['prn'])? $_GET['prn']:'');
if(isset($prns) && $prns!="")
$ff.=" AND cs.prn = '".$prns."' ";
$course_guids =(isset($_GET['course_guid'])? $_GET['course_guid']:'');
if(isset($course_guids) && $course_guids!="")
$ff.=" AND cs.course_guid = '".$course_guids."' ";
$from_time=system_time();
$date_from= date("d",$from_time)."-".date("m",$from_time)."-".date("Y",$from_time);
$date_to=date("d",system_time())."-".date("m",system_time())."-".date("Y",system_time());
if(isset($_GET['alldates']) && $_GET['alldates']=="on") {
$t_f=mktime(0,0,0,6,1,2011);
$t_t=system_time();
} else {
$t_f=mktime(0,0,0,substr($date_from,3,2),substr($date_from,0,2),substr($date_from,6,4));
$t_t=mktime(23,59,59,substr($date_to,3,2),substr($date_to,0,2),substr($date_to,6,4));
}
$query="SELECT cs.id,cs.prn,cs.course_guid FROM courses_attend cs
WHERE cs.time BETWEEN $t_f AND $t_t
$ff
";
//echo "$prns";
$rs22 = mysql_query($query) or die(mysql_error());
// $total22 = mysql_num_rows($rs22);
/*
while($row22=mysql_fetch_assoc($rs22))
{
$prnss =(isset($row22['prn'])? $row22['prn']:'');
print($prnss);
}
*/
?>
print($prnss); // this should be the code needed to be recalled In Orig.php
and It should Be Called Inside a loop mysql_fetch_array which is cannot be Used In orig.php Cause I do already Have a structure and Another Loop In that page Cause real Output Interface is there
as far as I do know I do think function callback() would be a solve on the other hand I do not know how to create one
// Answer
for ($i= 0; $i < mysql_num_rows($rs22);$i++) {
$row22 = mysql_fetch_assoc($rs22);
$prnss = $row22['prn'];
// echo "$prnss"; // return print all Omitted data
// echo "<br />\n";
$f.=" AND s.prn != '".$prnss."' ";
}
Solved By Adding This In Orig.php
On the other hand and after testing Select.php DATA can be added TO the Orig.php
Best regards

Displaying results from SQL query in PHP in a table

I am having some trouble with displaying some SQL query results.
Goal: I want to display the Helper 'name' in the table that is being generated if there is a helper signed up in the 'signup' table for that event 'eid' (event id).. If (1)there is no helper then display 'waiting for help', (2) there is a helper then display 'name -- awaiting approval..' and (3) else just display the name of helper..
Tried running the SQL query in phpMyAdmin with hard coded values and I get the results that I want so I know it is not my query. Have a suspicion that it is just the print out of the info into the table that is wrong somewhere. The table will display the data up until the ZIP from the address and then the next column which is the 'Helper' column does not display anything at all. So it makes me think I have a simple typo somewhere based on my if() statement logic BUT also find it interesting also that when I do the line:
echo "testing method -> ".getHelperIdOrName(2, 80)."<br>";
I cant get the table to print out at all. Not sure if this is related to my exact issue but it seems it could be. After I put this function in stuff stopped working so it seems like it could be culprit. The return of the function should either return an ID (int), a name "string", or just a generic value X (string)..
Any and all help is appreciated!
function getHelperIdOrName($x, $eid){
//Get the helper name first
$helperName = "";
$helperId = 0;
$sql = "SELECT id, first FROM users WHERE id IN (SELECT helper FROM signup WHERE gner = '".$userId."' AND eid = '".$eid."')";
$result = mysqli_query($db,$sql);
$row = $result->fetch_assoc();
if ($x == 2){
$helperName = $row["first"];
return $helperName;
}
else if ($x == 1){
$helperId = $row["id"];
return $helperId;
}
else {
return "X";
}
}
echo "testing method -> ".getHelperIdOrName(2, 80)."<br>";
//look for calendar and/or business approved events (approved=1) to display on page
$sql = "SELECT s.gner, s.helper, s.eid, s.approved, e.name, e.date, e.summary, e.street, e.city, e.state, e.zip
FROM signup s
INNER JOIN events e ON e.id = s.eid
INNER JOIN users u ON u.id = s.gner
WHERE s.gner = '".$userId."'";
$result = mysqli_query($db,$sql);
echo "<h3 class=\"text-center\">Events I'm Going To</h3>";
echo "<table class=\"table table-hover\"><tr><th>Event Name</th><th>Date</th><th>Summary</th><th>Location</th><th>Helper</th><th>Remove</th></tr>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["name"]."</td><td>".$row["date"]."</td><td>".$row["summary"]."</td><td>".$row["street"].", "
.$row["city"].", ".$row["state"]." ".$row["zip"]."</td>";
$tmp_eid = $row["eid"];
if (getHelperIdOrName(2, $temp_eid) == "X"){
echo "<td>Waiting for help..</td>";
}
else if ($row["approved"] == 0){
echo "<td>".getHelperIdOrName(2, $temp_eid)." -- Awaiting Approval (see below)</td>";
}
else {
echo "<td>".getHelperIdOrName(2, $temp_eid)."</td>";
}
echo "<td><form method=\"post\" action=\"remove.php\">
<button type=\"submit\" name=\"remove\" value=\"".$row["eid"]."\">Not Going</button></form></td></table>";
}
}
else echo "</table><br><p class=\"text-center\">You are not signed up for any events. Click here to sign up for events near you!</p>";
Thanks for that Jeff. The issue was that inside of the function it indeed did not know what $userId was even though I had the include statement at the top of my php file. I had to add this line into my function at the top..
global $db; //is part of my db my connection info in my config.php file
and then I also passed the $userId to the function as a parameter
these lines are what I used to help me see the errors:
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);
i also had some ending < /table > tags inside some if logic so that fixed the funky displays I was getting (2nd row of table being outside of the table)

How to display one banner ad every third row in php?

Sorry for my English,
I need to display a banner ad from a database every third row in php. Banner ads and rows with the classified are selecting from database. To this moment I create something like this:
Rows with the classifieds from database:
while(#$row_select_kat = mysql_fetch_assoc($results_select_kat))
{
... //classifieds from database
if(($row_select_kat['id_ogloszenia']%3)==0)
{
$lim = 1;
echo"<div id=\"rek_poz_a\">";
modAddsDisplayHelper::wyswietlReklamyPozA();
echo"</div>";
}
}
Selecting banner ads from databes:
public static function wyswietlReklamyPozA()
{
$baza_danych = &JFactory::getDbo();
$query_sel_all_banners = "SELECT * FROM juxhv_banners";
$baza_danych->setQuery($query_sel_all_banners);
$baza_danych->query();
$banner_ads = $baza_danych->loadObjectList();
echo$query_sel_all_banners;
echo"Liczba x= ".$l_ogloszen;
foreach($banner_ads as $banner_ad)
{
if($banner_ad->state==1)
{
echo"$banner_ad->name<br/><img src=\"images/$banner_ad->username/bannerwerbung/$banner_ad->zdjecie\" width=\"434px\" height=\"94px\" />";
}
else
{
echo"No banner";
}
}
}
When I doing this in that way at every three rows displaying all three banner ads. How can I display only one banner ad every three rows?
URL: http://www.nachbarhilft.de
Greetings
You need to use external counter variable which will be incremented on each iteration and depending on its condition you can check modulo condition: Please see the following updated code.
[code]
$recordCount = 0;
while(#$row_select_kat = mysql_fetch_assoc($results_select_kat))
{
if(($recordCount%3)==0)
{
echo"<div id=\"rek_poz_a\">";
modAddsDisplayHelper::wyswietlReklamyPozA();
echo"</div>";
}
$recordCount++;
}
if($banner_ad->state == 1) {
echo"$banner_ad->name<br/><img src=\"images/$banner_ad->username/bannerwerbung/$banner_ad->zdjecie\" width=\"434px\" height=\"94px\" />";
break;
}
In this way you only print one banner, but always will be the first with state == 1 in the database.
Maybe is better improve the query:
$query_sel_all_banners = "SELECT * FROM juxhv_banners WHERE state = 1 LIMIT 1";
That will give you the same result, I think.
I hope it helps

PHP Function Dependent on presence of MySQL data entry

I code a weekly trivia program for one of my clients through facebook.
I have a bit of code commented out where we display the winner when we need to. Currently I just remove the comment brackets and update when it's time to display. I'm trying to make this so someone non-savvy can handle updates so I've moved my code into an include:
winner-display.php
I am trying to write a function so that if the winner is set in MySQL, it includes the file in-line, and if the winner field is empty in the database, it does not.
Here is what I have so far, any ideas?
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = '$target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
$displayvalue = $row ['topic_desc'];
}
if ( $displayvalue != 'null') {
include('../includes/winner-display.php');
} else {
}
?>
Ok, thanks for helping guys, got it to work as:
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = '$target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
foreach ($row as $field) {
if ($field != null) {
include('../includes/winner-display.php');
}
}
}
?>
You can definitely put an include within an if. That solution that you posted should work as you would like it to, although I personally would have used a function instead of a completely separate file to include (although that is personal preference).
All you have to do to make it work is remove the quotes around 'null'.
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = $target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
$displayvalue = $row ['topic_desc'];
}
if ( $displayvalue != null) {
include('../includes/winner-display.php');
}
?>
Keep in mind that if your query returns more than one row, only the last row will be retained. I don't know if that is the functionality you want (in which case, there are some changes you could make, just ask me to edit my answer), but I didn't change that.

When listing information from a database using php and mysql how would you make the first row look different to the rest?

Basically I have articles in my database and I want to alter the way the first record displays. I want the lastest (Posted) article to be the focus and the older article just to list, (see F1.com). I need to know how to get the first of my values in the array and get it to display differently but I am not sure how to do this, I can do it so all rows display the same just not how to alter the first row. I also need to know how to tell the rest of the rows to display the same afterwards im guessing you use an if statement there and before that some kind of count for the rows.
Current code:
$result = mysql_query("SELECT * FROM dbArticle WHERE userID='".$_SESSION["**"]."' ORDER BY timestamp DESC");
while($row = mysql_fetch_array($result))
{
echo "<h2 class=\"heading1\">". $row['title'] ."</h2>";
echo "By: ".$row['username']." Type: ".$row['type']." Posted: ".$row['timestamp']."
$body = $row['body'];
echo "<br/><p>";
echo substr("$body",0,260);
echo "...<span class=\"tool\"><a class=\"blue\" href=\"index.php?pageContent=readArticle&id=".$row['id']."\">Read More</a></span></p><hr/>";
}
mysql_close($con);
Ok I have taken Luke Dennis's code and tried to test it, but I am getting this error: Warning: Invalid argument supplied for foreach() this is the line of the foreach statment. Something that has just come to mind is that I will only want 5 or so of the older articles to display. This is what I have thats creating the error:
<? $con = mysql_connect("localhost","****","***");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("******", $con);
$result = mysql_query("SELECT * FROM dbArticle ORDER BY timestamp DESC");
$first = true;
foreach($result as $row){
if($first)
{
echo"".$row['title']."";
echo"this is the headline";
$first = false;
}
else
{
echo"".$row['title']."";
}
}
?>
Do I need to add mysql_fetch_array somewhere to set the array up?
I would just iterate through the results and apply a css class to the first entry:
$first = true;
while ($row = mysql_fetch_assoc($result)) {
$cssClass = '';
if ($first) {
$cssClass = 'highlight';
}
echo '<p class="' . $cssClass . '">' . $row['text'] . '</p>';
$first = false;
}
It's a bit crude, but I often hard-code a variable to designate the first run through a loop. So something like:
$first = true;
foreach($list_of_items as $item)
{
if($first)
{
// Do some stuff
$first = false;
}
else
{
// Do some other stuff
}
}
A simple if statement when looping through your results will usually do the trick. You can use a boolean to indicate if you've output the first row of results or now. If you haven't then give it a particular style and then set the boolean to true. Then all subsequent rows get a different style.
All of the above are correct. Luke Dennis' post is of course fleshed-out a bit more.
As Brian Fisher said, add some CSS styling to the first link when you encounter it per Luke's post.
I took a look at the article list on the F1 website. Pretty well constructed site - "One would expect that." :-)
Anyway, the article listings are contained within a two row table (summary="Latest Headlines") in descending order (newest first).
Just place a class in the second column (<td class="first-news-article">). Then add the class name and appropriate styling values in the css file - probably your' modules.css. There's already quite a few class values associated with articles in that file, so you may be able to just use an existing value.
That should be about it - other than actually doing it!
By the way, judging by the quality of the underlying html, I'm assuming there's already an "article list emitter." Just find that emitter and place the appropriate conditional to test for the first record.
Darrell
I just noted your code addition. I assume that you were showing the F1 site as an example. Anyway, I think you're on your way.
I presume you have some code that loops through your resultset and prints them into the page? Could you paste this code in, and that might give us a starting point to help you.
I don't know PHP, so I'll pseudocode it in Perl. I wouldn't do it like this:
my $row_num = 0;
for my $row ($query->next) {
$row_num++;
if( $row_num == 1 ) {
...format the first row...
}
else {
...format everything else...
}
}
The if statement inside the loop unnecessarily clutters the loop logic. It's not a performance issue, it's a code readability and maintainability issue. That sort of thing just BEGS for a bug. Take advantage of the fact that it's the first thing in the array. It's two different things, do them in two different pieces of code.
my $first = $query->next;
...format $first...
for my $row ($query->next) {
...format the row...
}
Of course, you must make the first row stand out by using tags.
I'd use array_shift():
$result = mysql_fetch_assoc($resultFromSql); // <- edit
$first = array_shift($result);
echo '<h1>'.$first['title'].'</h1>';
foreach ($result as $row) {
echo '<h2>'.$row['title'].'</h2>';
}
The best way to do this is to put a fetch statement prior to the while loop.
Putting a test inside the while loop that is only true for one iteration can be a waste of time for a result of millions of rows.

Categories