PHP - How To Print Single Variable In While Loop
I currently have a problem where I'm trying to list alot of products with the category heading only being returned once and then the long list of products within that category being listed.
For Example Football boots Nike Addidas Puma etc Whereas at the moment I'm getting. Football boots Nike Football boots Addidas Football boots Puma My current code for this is as follows. <?php while($row = $db->fetchrow($stuff)) { ?> <li><a href="store-<?php echo $row['cat_id']; ?>/<?php echo seo_makeSafeURI($row['cat_title']); ?>.html"><strong><?php echo stripslashes(htmlentities($row['cat_title'])); ?></strong></a></li> <li><a href="store-<?php echo $row['cat_id']; ?>-<?php echo $row['prod_id']; ?>/<?php echo seo_makeSafeURI($row['prod_title']); ?>.html"><?php echo stripslashes(htmlentities($row['prod_title'])); ?></a></li> <?php } ?> Any help would be much appreciated. Similar Tutorialswhy it giving me single row data?? what i m missing here ... any help wil b appreciated.. <?php$comments= "";$result = mysql_query("SELECT * FROM comment");while($row = mysql_fetch_array($result)) { $serials= $row['serial']; $names= $row['name']; $emails= $row['email']; $msges= $row['msg']; $date_added= $row['date']; $comments= "$names <br /> $msges <br /> $date_added"; } ?>() I am trying to get the code at the bottom of the script to print just once during the loop but it either doesn't print at all or repeats with the loop im am using if (!$i++) to print once and i works the first time i use it. foreach($uploadFilename as $key => $myvar) { if (!$i++) print "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> <html xmlns=\"http://www.w3.org/1999/xhtml\"> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /> <title>Upload Complete....</title> </head> <body> <body onload=\"document.forms.formname.submit);\"> <form id=\"formname\" name=\"form1\" method=\"post\" action=\"reg5.php\">\n"; echo "<input type=\"hidden\" name=\"image$key\" value=\""; echo end(explode('/',$myvar)); echo "\">\n"; if (!$i++) print "</form> </body> </html>\n"; } Hi all, This has just been bugging me forever, I actually just hardcoded the line it in years ago to just be done with it. But when I use the while loop to pull up the data for this table, it prints out every row but the last one. I've wracked my brain for years trying to fix it, and just cannot find the solution. Below is the entire page code I'm using and you can see at the bottom what I have sadly hardcoded in to make the last row display. That's the row that will not show up. If you want to see the actual live page it's he https://www.lakerstats.com/numerical-roster/ The UNK line at the end if the one that never prints out that I hardcoded. Page code as mentioned above. Appreciate any help! [php] $db = mysql_connect("localhost", "xxxx", "xxxx"); mysql_select_db("lakerstats",$db); echo "<table class=numeric WIDTH=100% cellpadding=0 cellspacing=0 border=0> <tr><td class=left colspan=\"2\" height=10><font size=\"2\" color=#000000>Current players are listed in ALL CAPS.<br />Retired uniforms are listed in <b><font color=\"#FF0000\">red</font></b>.<br /></font></td></tr><tr>"; $uniforms = "SELECT p.fname, p.lname, p.playerid, u.number, p.current_roster, u.retired, u.retired_player, p.profile_name, p.uniform_1, p.uniform_2 FROM player p, uniforms u WHERE u.number = p.uniform_1 or u.number = p.uniform_2 or u.number = p.uniform_3 or u.number = p.uniform_4 ORDER BY u.number+0, p.years, p.lname, p.fname"; $uniresult = mysql_query($uniforms) or die ("Query failed"); $numofrows = mysql_num_rows($uniresult); //let's get the number of rows in our result so we can use it in a for loop $temp = "0"; $sHTMLTemp = ""; while ($unirow = mysql_fetch_array($uniresult)) // Where $result is your result set { if ($temp != $unirow['number']) { $temp = $unirow['number']; if ($unirow['number'] == "100") { $unirow['number'] = "0"; } else if ($unirow['number'] == "101") { $unirow['number'] = sprintf("%02d", 0); } else if ($unirow['number'] == "102") { $unirow['number'] = "UNK"; } else { $unirow['number'] = $unirow['number']; } $sHTMLTemp = preg_replace("/(.+),/","\\1",$sHTMLTemp); print $sHTMLTemp ; print "</tr>"; $sHTMLTemp = ""; if ($unirow[retired] == "yes") { echo "<tr><td class=left height=10><font size=\"2\" color=\"#FF0000\"><b>#" . $unirow[number] . "</b></font><font size=\"2\"> - "; } else { echo "<tr><td class=left height=10><font size=\"2\" color=\"#000000\">#" . $unirow[number] . "</font><font size=\"2\"> - "; } } if ($unirow[current_roster] == "yes") { $unirow[fname] = strtoupper($unirow[fname]); $unirow[lname] = strtoupper($unirow[lname]); } else { $unirow[fname] = $unirow[fname]; $unirow[lname] = $unirow[lname]; } if ($unirow[retired_player] == $unirow[playerid]) { $sHTMLTemp .= "<b><a href=\"/player-stats-bio/?pname=".$unirow['profile_name']."\"><font color=\"#FF0000\">" . $unirow['fname'] . " " . $unirow['lname'] . "</font></a></b>, "; } else { $sHTMLTemp .= "<a href=\"/player-stats-bio/?pname=".$unirow['profile_name']."\">" . $unirow['fname'] . " " . $unirow['lname'] . "</a>, "; } } echo "<a href=\"/player-stats-bio/?pname=jim_fritsche\">Jim Fritsche</a>, <a href=\"/player-stats-bio/?pname=bobby_watson\">Bobby Watson</a>"; echo "</font></td></tr>"; echo "</font></td></tr></table>"; mysql_close($db); [/php] Edited September 14, 2020 by ban5150 i have a while loop that builds up a table of records, each row has a button that needs to have an action to delete that specific record. I can think of the obvious way around this and add a form around each row and set the button to type="submit". However there is a problem i have the entire table of records wrapped within in a form object for other functionalities. Does anyone have a solution for this problem? Hi I have a db that has the following Data for example: PolicyNumber, StoreId, ConsultantName,ClientName, ClientSurname I would like to have a report that will give me a list of policies done for that day seperated by store printed to PDF. So Basically Store - 12CEL 24Hr001 Bob Joe Soap 24Hr002 Bill Gill Henry Store - 1156 24Hr003 Luke Manfred Kiy 24Hr004 Peter Ursula Jent I currently use R&OS for pdf Printing http://www.ros.co.nz/pdf The Code below Gives me all policies, I just need to now seperate them in the PDF //include pdf class include ('class.ezpdf.php'); //Include PHP Mailer Class require("class.phpmailer.php"); //Connect to database mysql_connect("localhost", "root", ""); @mysql_select_db("mobility") or die("Unable to select database"); $queryP= mysql_query("SELECT * FROM tblpolicies WHERE CaptureDate='2006-04-03' ORDER BY StoreId"); $pdf =& new Cezpdf(); //$pdf->addJpegFromFile('policy.jpg',60,$pdf->y-750,500,0); $pdf->selectFont('./fonts/Helvetica.afm'); $p = 750; While($x=mysql_fetch_array($queryP)){ $pdf->addText(50,$p,7,"{$x['PolicyNumber']}"); $pdf->addText(80,$p,7,"{$x['StoreId']}"); $pdf->addText(120,$p,7,"{$x['NickName']}"); $pdf->addText(220,$p,7,"{$x['ClientsName']}"); $pdf->addText(330,$p,7,"{$x['DateReceived']}"); $pdf->addText(410,$p,7,"{$x['Comments']}"); $p = $p - 10; if($p == 10){ $pdf->ezNewPage(); $p = 750; } } $pdf->ezText("\n\n\n\n\n\n\n" . $body,16,array('justification'=>'centre')); $pdf->output(); $pdf->ezStream(); //write pdf stream to pdf file $pdfcode = $pdf->ezOutput(); $fp=fopen('policy.pdf','wb'); fwrite($fp,$pdfcode); fclose($fp); Hi, I am able to parse php variable in double quote but not in single quote. How can I parse in single quote. Following example shows 2 results and I want same result in both. First Name : Zohaib First Name : $firstname Code: [Select] // Connecting, selecting database $link = mysql_connect('localhost', 'root', 'password'); mysql_select_db('dbname'); // Performing SQL query $query = 'SELECT first_name FROM tablename'; $result = mysql_query($query); // Printing results in HTML while ($row = mysql_fetch_assoc($result)) { $firstname=$row['first_name']; } echo"<table> <tr> <td>First Name : </td> <td>$firstname</td> </tr></table>"; echo'<table> <tr> <td>First Name : </td> <td>$firstname</td> </tr></table>'; What are the changes I need to do to achieve same result. Any solution ? - Thanks. Hi there im trying to set a single variable multiple rows of data that are echoed using a single variable. The trouble is i just cant seem to make it work by trying to add a while or do loop.. The variable is $alderaanfleetalt and consists of: Code: [Select] $fleetname = "FleetName"; $shipname = "Ship Name"; Which is just text stored in two other variables. The select query row of data is added the $alderaanfleetalt variable. Code: [Select] $alderaanfleetalt = $fleetname." ".$row_Alderaanfleet['FleetName']."</br>".$shipname." ".$row_Alderaanfleet['ShipName']; At the moment only a single row appears. ive tried to add a while/do loop so that multiple rows are outputted but its not working. Code: [Select] do{ $alderaanfleetalt = $fleetname." ".$row_Alderaanfleet['FleetName']."</br>".$shipname." ".$row_Alderaanfleet['ShipName']; } while ($row_Alderaanfleet = mysql_fetch_assoc($Alderaanfleet)); Im a bit lost here and not even sure it can be done this way... Any help would be ace. Thank you Hello, Having a bit of a tough time understanding what is going on in my brain! I'm basically pulling some data from an API using CuRL, which is working fine. The structure of the data is: [data][tickets] - tickets being an array of support tickets in the system, which then contains ticketNumber, title, content. I want to display these values in a list, I have this code currently: if ($err) { echo "cURL Error #:" . $err; } else { $return = json_decode($response, true); foreach($return as $key) { echo $key["tickets"][1]['ticketNumber']." - "; echo $key["tickets"][1]['title']." - "; echo $key["tickets"][1]['content']; } } Which obviously returns the ticketNumber, title & content of the first support ticket in the array, but I want to loop through and display that information for each ticket! Can anyone advise as to where I am going wrong? I think I need to utilise the ["tickets"][x] but not sure how!
Thanks in advance! Steve I currently have a search page on my site that prints the products but it prints the products more than once if its in more than one category I have tried getting distinct item in my SQL. But this doesnt work so im trying an if statement that if there is more than one specific result then to just print this once. I was wondering if anyone had any ideas of how to do this using an if statement I just dont know how to go about just printing the result just once if its greater than 1. The code is below to make it clearer. $searchterm = $_POST['searchterm']; trim ($searchterm); /*check if search term was entered*/ if (!$searchterm){ echo 'Please enter a search term.'; echo $searchterm; } /*add slashes to search term*/ if (!get_magic_quotes_gpc()) { $searchterm = addslashes($searchterm); } /*query the database*/ $query = "SELECT * from (products LEFT JOIN categories_products_link ON products.prod_id = categories_products_link.prod_id) LEFT JOIN categories ON categories_products_link.cat_id = categories.cat_id WHERE prod_title LIKE '%" . $searchterm . "%' ORDER BY cat_title, prod_title"; $result = mysql_query($query); /*number of rows found*/ $num_results = mysql_num_rows($result); echo '<p><h1>Search Results: '.$num_results.'</h1></p><br />'; /*loops through results*/ for ($i=0; $i <$num_results; $i++) { $num_found = $i + 1; $row = mysql_fetch_assoc($result); echo "$num_found. "?><a href="store-<?php echo $row['cat_id'];?>-<?php echo $row['prod_id']; ?>/<?php echo seo_makeSafeURI($row['prod_title']); ?>.html"><strong><?php echo $row['prod_title']; ?></strong></a> <br /> Say I have two variables like below. I basically want to select one of them, but through random choice. How do I do that? $orange = 'Orange'; $apple = 'Apple';
I have two arrays, X and Y, which contain names. The arrays are of the same size. The arrays are related to each other such that for each pair X[n] , Y[n] X is friends with Y. For example: X[0,1,2] = [Link, Cloud, Cloud, Mario, Mario, Luigi] Y[0,1,2] = [Zelda, Barrett, Tifa, Luigi, Bowser, Mario] Link is friends with Zelda Cloud is friends with Barrett and Tifa Mario is friends with Luigi and Bowser Luigi is friends with Mario I want to loop through these arrays and, for each unique name, find all of that person's friends. I then want to print the results to a text file, like so: Link, Zelda Cloud, Barrett, Tifa Mario, Luigi Luigi, Mario I know how to do this theoretically, but I just need help with the PHP syntax. Thanks very much. I have a class that I created, halfway down my page I call a function from the class which prints some code and also changes a variable inside the class. It's a search class basically it prints out the search results and saves the total amount of results into the variable. I want to display the amount of results above the results like so:- echo $Search->results; $Search->GetResults('foo'); The problem is that $Search->results will be equal to NULL until the variable is updated in the function GetResults. Hope that makes sense, am I going about this wrong? PHP script return 20 UL LIST values like, < ul >
A < /ul > How to display UL LIST into row wise 5 columns like
A B C D I am using a htmltable() function in FPDF and while in a MySQL While() loop I need to change the variable name each time it loops through. So basically $html needs to be $html1 on the next loop, $html2 on the next, and so on. Its probably simple, but its late and I'm tired, I can't seem to figure this one out. Here is my unfinished attempt: $htmlnum = 0; $endo = mysql_query("SELECT * FROM endorse WHERE endonum = '$endonum' AND agency = '$agency' ORDER BY ID DESC LIMIT 1"); while($endofetch = mysql_fetch_array($endo)){ $endotype = $endofetch['type']; $htmlnum = $htmlnum++; $p->htmltable($html); } i have a variable called $cake it needs to have this loop inside it so I can call it out Code: [Select] while( $r = $DB->fetch_row() ){ if ( $r['last_activity'] > (time() - 900) ) $r['status'] = "<span style=float:right;><span class=desc4><b>Online</b></span></span>"; else $r['status'] = "<span style=float:right;><span class=desc4>Offline</span></span>"; $column++; if ($ibforums->member['settings']['2'] or (!$ibforums->member['id'])){ $color = "{$r['color']}"; $colors = explode(",", $color); if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') ){ { $r['color'] = ($r['color']) ? "style=\"padding:1px 1px 1px 2px;color:#{$colors[0]};filter:Glow(color=#{$colors[1]},strength=3)\"":""; } }else{ $r['color'] = ($r['color']) ? "style=\"color:#{$colors[0]};text-shadow:#{$colors[1]} 2px 1px 1px\"":""; } } $test = explode(";", $info['pdata']); $r['avatar'] = ($r['avatar']) ? "<img src={$r['avatar']} width=64 height=64>" : ""; $r['star'] = ($r['star']) ? "<img class=top3 src=style_images/1/icons/{$r['star']}.png>":""; $r['name'] = "<a href=?i={$r['friendid']}>{$r['name']}{$r['star']}</a>"; $this->to_print .= <<< LOL <dl class="LOL LEFT flm" style="margin-right:5px"><dt2>{$r['name']}</dt2><dd class=padding4>{$r['avatar']}<div class="RIGHT">{$r['status']}</div></dd></dl> LOL; } I tried: Code: [Select] $cake = ' while( $r = $DB->fetch_row() ){ if ( $r['last_activity'] > (time() - 900) ) $r['status'] = "<span style=float:right;><span class=desc4><b>Online</b></span></span>"; else $r['status'] = "<span style=float:right;><span class=desc4>Offline</span></span>"; $column++; if ($ibforums->member['settings']['2'] or (!$ibforums->member['id'])){ $color = "{$r['color']}"; $colors = explode(",", $color); if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') ){ { $r['color'] = ($r['color']) ? "style=\"padding:1px 1px 1px 2px;color:#{$colors[0]};filter:Glow(color=#{$colors[1]},strength=3)\"":""; } }else{ $r['color'] = ($r['color']) ? "style=\"color:#{$colors[0]};text-shadow:#{$colors[1]} 2px 1px 1px\"":""; } } $test = explode(";", $info['pdata']); $r['avatar'] = ($r['avatar']) ? "<img src={$r['avatar']} width=64 height=64>" : ""; $r['star'] = ($r['star']) ? "<img class=top3 src=style_images/1/icons/{$r['star']}.png>":""; $r['name'] = "<a href=?i={$r['friendid']}>{$r['name']}{$r['star']}</a>"; $this->to_print .= <<< LOL <dl class="LOL LEFT flm" style="margin-right:5px"><dt2>{$r['name']}</dt2><dd class=padding4>{$r['avatar']}<div class="RIGHT">{$r['status']}</div></dd></dl> LOL; }'; but not working Hi - To me, this doesn't make sense. My Order form uploads product weights in an array . If I echo out those weights they are fine ie 25.25 However, when I try to update the DB for some reason, the for loop strips out all but the first digit, so 25.25 becomes '2' or indeed if I had entered 9999999 it just '9' is entered in to the DB. I have tried using number_format to pre-process the decimals, - but I get an error saying you can not use it in a write format. Many Thanks to anyone who can help with this !! PS - I have abbreviated the below code for clarity: Code: [Select] $weight = $_POST['weight']; for ($i = 0; $i < $numloops ; $i++) { $sql =" UPDATE `confirmedorder` SET orderid = '$orderid[$i]', weight='$weight[$i]',status='finished', ordervalue='$ordervalue' WHERE customerid = $customerid "; $this->db->query($sql); } I want to save the results of a loop as a variable ie $output. I have tried encasing the php within quotes but it does not work. Is there a way to save the complete results as a variable? $result = mysql_query("SELECT * FROM $table2 WHERE $db_item_1 OR $db_item_2", $connection); if (!mysql_num_rows($result)) { echo "Error 13424 - not working"; exit(); } while ($row = mysql_fetch_array($result)) { echo "<tr><td scope=\"col\" style=\"font-size: 16px; color: #333333; padding: 10px 8px; border-bottom: 1px solid #919191;\"><div align=\"left\" style=\"font-size: 20px;\">" . $row['date'] . "</div></td> <td scope=\"col\" style=\"font-size: 16px; color: #333333; padding: 10px 8px; border-bottom: 1px solid #919191;\"><div align=\"left\"></div></td> <td scope=\"col\" style=\"font-size: 16px; color: #333333; padding: 10px 8px; border-bottom: 1px solid #919191;\"><div align=\"left\" style=\"font-size: 20px;\">" . $row['title'] . "</div></td> <td scope=\"col\" style=\"font-size: 16px; color: #333333; padding: 10px 8px; border-bottom: 1px solid #919191;\"><div align=\"left\"></div></td> <td scope=\"col\" style=\"font-size: 16px; color: #333333; padding: 10px 8px; border-bottom: 1px solid #919191;\"><div align=\"left\" style=\"font-size: 20px;\">" . $row['cost'] . "</div></td> </tr>"; }echo $complete;() The part I want as one result (ie. $complete) is the result of the while loop. There is always at least one result but sometimes 10 which means that it creates 10 table rows. I need to do it this way as later on in the page I use a pdf converter which does not allow loop checks within it otherwise I would just place it within the converter. I'm trying to take a number of items from a database using a while loop and put the results into a variable so that I can send one email with all the results. I'm having trouble figuring this out though. Can anyone please give me any ideas as to how to make this work? Here's what I've done so far... all it does is result in an email with the first set of results in the while loop, not all of them. Code: [Select] <?php include("conf.inc.php"); $result = mysql_query("SELECT `to`,`from`,`subject`,`message`,`date` FROM allmsgs WHERE reported = 'n' ORDER BY `messid` ASC"); $row = mysql_fetch_row($result); $cdate = date('m-d-Y'); $sendto = "List@emails.here"; $emailsubject = "Webstats Report For $cdate."; while ($row = mysql_fetch_row($result)) { $to = $row[0]; $from = $row[1]; $subject = $row[2]; $message = $row[3]; $datetime = $row[4]; $eachmessage = "<p> <table width=\"400\"> <tr> <td> <hr width=\"400\"> To: $to<br> From: $from<br> On $datetime<br> <br> $subject<br> <br> $message </td> </tr> </table> </p>"; } $emailmessage = "<html> <body> <p>Here is a list of the messages that have been exchanged in the last 24 hours using the webstat system system.</p> $eachmessage </body> </html>"; // To send HTML mail, the Content-type header must be set $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Additional headers $headers .= 'From: Webstats <reports@webstats.com>' . "\r\n"; // Mail it mail($sendto, $emailsubject, $emailmessage, $headers); ?> I am new at php. I am trying to loop a number in each click of a button. See attached picture for reference. 1 should iterate after the click of the button and will stop to iterate when it gets to 5.
Here is my code: <!DOCTYPE html> <html> <body> <div>Question <?php $num = 5; $n = 1; $n <= $num; echo $n; ?> of <?php echo $num;?></div> <form method="post"> <button id="button" class="button" value="add" name="add">Click</button> </form> </body> </html>
If I try to loop it this way, <!DOCTYPE html> <html> <body> <div>Question <?php $num = 5; for($i = 1; $i <= $num; $i++){ echo $i; } ?> of <?php echo $num;?></div> <form method="post"> <button id="button" class="button" value="add" name="add">Click</button> </form> </body> </html> the result is Question 12345 of 5.
Hi, I've been scratching my head for a while now about how to do this, I'm relatively new to php and mysql and perhaps foolishly taking on creating a user area for a website. I have everything else working, all of my register account functions and confirmations and all of the login scripts etc. I have created a profile page which returns various information to the user (this bit works fine) and I've got some nice show/hide toggles running with some javascript/css but my intention is to allow the user to change thier information (e-mail address, contact phone number and also whether they are subscribed to the e-mail list), it also displays any support tickets or messages. So after the long intro, here's what I'm struggling with... I have a form in a visibility toggled <div> which submits a 'change_email' script, so a user wants to change their e-mail, clicks on change, the <div> appears, they bang in the new e-mail and hit submit. My php script appears to work (because it doesn't throw up any errors), until you realise that actually it's not updated the record in the db... I'm using mysql_query("UPDATE users SET email='$new_email' WHERE username='$user'"); Do I need to setup variables for all of the information in the db (name, username, password, email, contno etc etc) and include them in the command to get it to work or should that just pick the correct record and then update it? If that is the case is there a way I can include 'blank' variables so I don't have to set them all up... e.g. mysql_query("UPDATE users SET user='',password='',email='$new_email', etc WHERE username='$user'"); Many thanks in anticipation |