PHP - How To Insert Line Breaks In Php While Loop?
I have developed the following code, which queries a MySQL database and returns multiple results using several WHILE loops:
Code: [Select] <?php # if submit_hash is present, then pull up the attendance from specified hash if($_GET['submit_hash']) { # select all the hashers from the specified hash $query = " SELECT h.*, ha.* FROM hashes as h, hashers as ha, hash_records as hr WHERE hr.hash_id = " . $_GET['hash_id'] . " && hr.hash_id = h.hash_id && hr.hasher_id = ha.hasher_id ORDER BY ha.hasher_name "; $result = mysql_query($query) or die('Error selecting Hash attendance.'); $x = 1; while($row = mysql_fetch_array($result)) { if($x == 1) { echo '<strong>' . $row['hash_num'] . ' ' . $row['hash_name'] . ' - ' . date("D, d M Y", strtotime($row['hash_date'])) . '</strong><em>Total Hashers: ' . mysql_num_rows($result) . '</em>'; $x++; } # see if this person was the hare if($row['hare_id'] == $row['hasher_id'] || $row['hare2_id'] == $row['hasher_id'] || $row['hare3_id'] == $row['hasher_id']) { $hare = '- hare'; } else { $hare = ''; } echo $row['hasher_name'] . ' <b>' . $hare . '</b>'; } } else if($_GET['submit_hasher']) { # if submit_hasher is present, pull up all of their hashes and aliases # select all the hashes that this person has attended $a_query = " SELECT h.*, ha.* FROM hashes as h, hashers as ha, hash_records as hr WHERE hr.hash_id = h.hash_id && hr.hasher_id = ha.hasher_id && hr.hasher_id = " . $_GET['hasher_id'] . " ORDER BY h.hash_date DESC "; $a_result = mysql_query($a_query) or die('Error selecting the person\'s Hashes . '); $x = 1; while($a_row = mysql_fetch_array($a_result)) { if($x == 1) { echo '<strong>Hash Attendance Record For ' . $a_row['hasher_name'] . '</strong> <em>(' . mysql_num_rows($a_result) . ' total hashes)</em>'; $x++; } echo '#' . $a_row['hash_num'].' ' . $a_row['hash_name'] . ' on ' . date("D, d M Y", strtotime($a_row['hash_date'])); # see if this person was a hare if($a_row['hasher_id'] == $a_row['hare_id'] || $a_row['hasher_id'] == $a_row['hare2_id'] || $a_row['hasher_id'] == $a_row['hare3_id']) { echo ' - <b>hare</b>'; } echo ''; } echo ''; } echo ' <table width="100%"> <br /> <tbody> <tr> <br /> <td> '; ?> The problem is that everything that is returned from the WHILE loops is displayed in a single line. However, I want the data displayed with a line break between each result, like this: Header Return 1 from WHILE loop Return 2 from WHILE loop Return 3 from WHLIE loop How do I need to modify the code to make it display appropriately? Similar TutorialsI'm trying to insert the contents of a textarea into a MySQL database but I am wondering what the best way is to preserve the users line breaks. I know that you can use nl2br() to convert "\n" into "<br />" when the retrieve data from the database but I am looking at a way to insert these line breaks when I enter the data. Thanks for any help. Here's the code that I have: Code: [Select] <?php if (get_magic_quotes_gpc()) { function undoMagicQuotes($array, $topLevel=true) { $newArray = array(); foreach($array as $key => $value) { if (!$topLevel) { $key = stripslashes($key); } if (is_array($value)) { $newArray[$key] = undoMagicQuotes($value, false); } else { $newArray[$key] = stripslashes($value); } } return $newArray; } $_GET = undoMagicQuotes($_GET); $_POST = undoMagicQuotes($_POST); $_COOKIE = undoMagicQuotes($_COOKIE); $_REQUEST = undoMagicQuotes($_REQUEST); } function safe($value){ return mysql_real_escape_string($value); } $subject1 = "It's just a test."; $message1 = // $subject1 and message1 are actually submitted from a form on the page... "Here's a test. // so this section would really be $subject = safe($_POST['subject']); same w/ message // I did it this way to simplify... I'm pretty sure it would be the same either way. Thanks, Me"; // this is what is typed in the text area of the form. $subject = safe($subject1); $message = safe($message1); ?> When these variables are mailed using php mail(), they display like this: Code: [Select] Subject: It\'s just a test. Message: Here\'s a test.\r\n\r\nThanks,\r\nMe When they are inserted into a database, they are inserted correctly, as they were typed. My question is this: Is there a way to mail these and have them display correctly? Should I just insert them into the database, then select them again to mail? Thanks for any help. php5 I am using json_encode() to store an array of data as a string in a mysql data base. I then extract the sting from the data base and convert the back into an array using json_decode. This works great up until I have any line breaks in any of the data. When there is a line break, the json_decode() function chokes and returns nothing. I would really like to keep the line breaks. Has anyone come across this issue/have an suggestions/solutions? hello guys, suppose I want to echo out the text given below exactly as what has been set against, including the line breaks. How do I do it? coz each time i did it so, there s no line breaks but the output is usually a dense lump of words with no paragraphs. Code: [Select] I took her out it was a Friday night I wore cologne to get the feeling right We started making out and she took off my pants But then I turned on the TV And that's about the time she walked away from me Nobody likes you when you're 23 I'm still more amused by TV shows What the hell is ADD? My friends say I should act my age What's my age again? What's my age again? please help P.S. The whole set of phrase give above are treated as a single variable coz I use a WHILE loops when making an echo. tthanks I have a form which has a textarea in it. When the form is submitted the contents are submitted to a MySQL database and the contents or the textarea are stored in a text variable. What is the best was to preserve line breaks in the textarea? At the moment if the user enters to separate paragraphs into the textarea they will be merged into one. Thanks for any help. I am constructing an XML file with PHP. I read information from a template XML file and then add elements and save it. The line breaks from the template are preserved in the saved file, but all the new elements are on one line. Is there a way to break them up so it is easier to read the file? Here is the original template: Code: [Select] <InternationalShippingServiceOption> <ShippingService> token </ShippingService> <ShippingServiceAdditionalCost currencyID="CurrencyCodeType"> AmountType (double) </ShippingServiceAdditionalCost> <ShippingServiceCost currencyID="CurrencyCodeType"> AmountType (double) </ShippingServiceCost> <ShippingServicePriority> int </ShippingServicePriority> </InternationalShippingServiceOption> Here is the saved information (all the ShipToLocation elements on one line): Code: [Select] <InternationalShippingServiceOption> <ShippingService>StandardInternational</ShippingService> <ShippingServiceAdditionalCost currencyID="CurrencyCodeType">26.994</ShippingServiceAdditionalCost> <ShippingServiceCost currencyID="CurrencyCodeType">44.99</ShippingServiceCost> <ShippingServicePriority>2</ShippingServicePriority> <ShipToLocation>BE</ShipToLocation><ShipToLocation>FR</ShipToLocation><ShipToLocation>IE</ShipToLocation><ShipToLocation>LU</ShipToLocation><ShipToLocation>MC</ShipToLocation><ShipToLocation>NL</ShipToLocation><ShipToLocation>GB</ShipToLocation><ShipToLocation>DE</ShipToLocation><ShipToLocation>IT</ShipToLocation></InternationalShippingServiceOption> I am using the $doc->formatOutput = true; option. Hey I am trying to write to a csv file with the data in my database. My problem I am having is that when I echo out to the browser everything is fine, but when I try writing to the file I get a lot of line breaks and that throws everything off for the csv file. Here's my code: Code: [Select] $query = "SELECT * FROM $table"; $result = mysql_query($query); $numcolumns = mysql_num_fields($result); $numrows = mysql_num_rows($result); $file = "testFile.csv"; $fh = fopen($file, 'w') or die("can't open file"); while($row = mysql_fetch_array($result)) { for($i = 0; $i <= ($numcolumns - 1); $i++) { if($i < ($numcolumns - 1)) { $string = $row[$i] . ","; echo $string; fwrite($fh, $string); } else { $string = $row[$i]; echo $string; fwrite($fh, $string); } } $string = "\n"; echo "<br />"; fwrite($fh, $string); } fclose($fh); My output to the browser looks like this for one record.. which is how it should look: (Had to edit the content a bit for confidential reasons) Code: [Select] ######,12/31/99 ,123 Drive,City,TX ,##### ,County And here is what I get in the csv file when I open it up on notepad: Code: [Select] ######,12/31/99 ,123 Drive ,City ,TX ,##### ,County Any idea where these line breaks are coming from? Is it because the data is being pulled from a database? Any help on how to fix this would be great!! Thanks. Hi All, I am exporting data to excel, but run into a problem if the text contains a line break. When it gets to the line break, it cuts off the rest of the text. Here is my printer code: Code: [Select] $file = 'Notes_Export'; $csv_output = array(); $tmp = array(); $tmp[] = 'Created On'; $tmp[] = 'Created By'; $tmp[] = 'Note'; $csv_output[] = '"' . implode('","', $tmp) . '"'; $sql = "SELECT pn.created_on, CONCAT( u.firstname,' ', u.lastname) AS created_by, pn.note FROM prop_notes pn LEFT JOIN users u ON pn.created_by = u.user_id "; $sql .= "WHERE pn.deleted_by IS NULL AND pn.archive = '0' AND pn.property_id = '".$_GET['pid']."'"; $result = mysqli_query($connect, $sql); while($rowr = mysqli_fetch_row($result)) { $tmp = array(); for ($j=0; $j<3; $j++) {$tmp[] = $rowr[$j];} $csv_output[] = '"' . implode('","', $tmp) . '"'; } $filename = $file."_".date("Y-m-d_H-i",time()); header("Content-type: application/vnd.ms-excel"); header("Content-disposition: csv" . date("Y-m-d") . ".csv"); // header( "Content-disposition: filename=".$filename.".csv"); header("Content-disposition: attachment; filename=".$filename.".csv"); print implode("\n",$csv_output) . "\n"; exit; I have a simple contact form with a textarea field, where the visitor can type a message in. However, if the user enters paragraphs or any type of line breaks, then the email that is sent shows the "\r\n" characters. I've tried using the nl2br function to no avail. Here's a sample code snippet: Code: [Select] $message = $_POST["message"]; // 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: '. $_POST["email"]; mail($to, $subject, $message, $headers); Am I missing something? Besides the "\r\n" characters showing, everything else works fine. Hi My problem is that text that is in my database are showing up next to each other in a line rather than on seperate lines, normally I would have just used <br> but as it's generated from my sql I don't know how to do it. Code: [Select] <ul id="headlines"> <?php foreach ( $results['articles'] as $article ) { ?> <a href=".?action=viewArticle&articleId=<?php echo $article->id?>"><?php echo htmlspecialchars( $article->title )?></a> <?php } ?> </ul> Anyone have any idea? Thanks I have an XML file (differences.xml) <element> <item code="lM" name="castle" type="building"> <cost>5000</cost> </item> ...more items.... </element> I have parser.php whih parses the XML and displays all item names in a checklist for the user to select items. These selected items are method=post back to parser.php which re-parses the XML where selected item = item name and SHOULD then display all selected items' names (and more): <?php if (isset($_GET['formSubmit'])) { $option = $_POST['option']; $option = array_values($option); if (!empty($option)){ $xml = simplexml_load_file('differences.xml'); $i = 0; $count = count($option); while($i < $count) { $selected = $xml->xpath("//item[@name='".$option[$i]."']"); echo $selected[$i]['name']; $i++; } }else{ echo "No items selected, Please select:"; } }else{ $xml = simplexml_load_file('differences.xml'); $object = $xml->xpath('//item'); $count = count($object); $i = 0; echo "<form method='POST' action='parser.php'>"; while($i < $count){ $xmlname = $object[$i]['name']; echo "<input type='checkbox' name='option[".$i."]' value='$xmlname'>".$xmlname; echo "<br>"; $i++; } echo "<br><input type='submit' name='formSubmit' value='Proceed'><br>"; echo "</form>"; } ?> The problem is, the parser is only displaying the first selected item and isn't outputting the rest. To clarify the code: - The first half executes only if items have been previously selected in the form. If no items were selected, it goes to the secod half, which parses the XML file and presents the checklist form for the user to select items. THIS WORKS GREAT. - After pressing the submit button, the items are sent using POST and the page is reloaded. THIS WORKS GREAT. - After reloading, the first half executes and finds the $_POST and resets the array so that it works with the coming loop. THIS WORKS GREAT. - The loop parses the XML and returns only those item names that have been selected in the $_POST. THIS DOES NOT WORK. So my question is: what's wrong with my code? The array $options has all the proper information, but the parser is only outputting the first item. All consecutive loops result in empty space with no output. I've been at this for 2 weeks and can't find the solution. Any help is appreciated! Hi all, I'm currently rewriting our contact us form using the php Pear Mail package. It allows both html based emails and text based emails, and displays the relevant version based on the end recipients broswer capabilities. I have the html version working perfect, however the text based version spits out the whole message without line breaks. Since some of the computers in our building only except text emails (due to security) it needs to be laid out so that it is legible. I've searched around and tried various options but the emails are still arriving without breaks. So as an example: A User Inputs the following message using a textarea on the php form: Hi there, Great website, need help with such and such though. Regards Bob The email message gets collected and included in a html message. Then a duplicate text based message is made like so (Code so far): Code: [Select] $plaintxt = '-----------------------------------------' . "\n"; $plaintxt .= Website Enquiry' . "\n"; $plaintxt .= '-----------------------------------------' . "\n"; $plaintxt .= 'A visitor to our website has submitted the following enquiry:' . "\n\n"; $plaintxt .= 'Name: ' . $visitor_name . "\n"; $plaintxt .= 'Company Name: ' . $visitor_companyname . "\n"; $plaintxt .= 'Email Address: ' . $visitor_email . "\n"; $plaintxt .= 'Telephone Number: ' . $message_telephone . "\n\n"; $plaintxt .= 'Subject of Enquiry: ' . $msg_subject . "\n"; $plaintxt .= 'Enquiry: ' . "\n\n"; $plaintxt .= $message_body . "\n\n"; $plaintxt .= '-----------------------------------------' . "\n\n"; $plaintxt .= 'User IP Address:' . $ip . "\n"; $plaintxt .= 'User Browser Info:' . $httpagent . "\n"; $plaintxt .= 'Date/Time Submitted:' . $time . "\n"; $crlf = "\n"; $headers = array('From' => $contact_from_email, 'Return-Path' => $contact_from, 'Subject' => $subject, 'To' => $contact_to); // Creating the Mime message $mime = new Mail_mime($crlf); // Setting the body of the email $mime->setTXTBody($htmlmessage); //Text version of the email $mime->setHTMLBody($plaintxt); // HTML version of the email "\n"; - These were suggested by users on the pear mail manual. Then once sent and opened you'd expect to see: Quote ----------------------------------------- Website Enquiry ----------------------------------------- A visitor to our website has submitted the following enquiry: Name: Bob Company Name: Someplace Ltd Email Address: bob@someplace.com Telephone Number: 01234 567890 Subject of Enquiry: help Enquiry: Hi there, Great website, need help with such and such though. Regards Bob ----------------------------------------- User IP Address: 123.456.789.012 User Browser Info: Mozilla Date/Time Submitted: 29th September 2011 09:56 However when opened in all the email applications I have (Outlook, Gmail, Live Mail, Hotmail, Yahoo) it looks like this: Quote -----------------------------------------Website Enquiry-----------------------------------------A visitor to our website has submitted the following enquiry:Name: BobCompany Name: Someplace LtdEmail Address: bob@someplace.comTelephone Number: 01234 567890Subject of Enquiry: helpEnquiry: Hi there,Great website, need help with such and such though.RegardsBob-----------------------------------------User IP Address: 123.456.789.012User Browser Info: MozillaDate/Time Submitted: 29th September 2011 09:56 Yet if you look at the source of the email. The line breaks are there. Am I missing something? This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=347065.0 This topic has been moved to Editor Help (Dreamweaver, Zend, etc). http://www.phpfreaks.com/forums/index.php?topic=355418.0
No idea how to add a new line so it's easier to read in the terminal. Debugging this way is absolutely horrible.
Edited by Monkuar, 03 December 2014 - 09:06 AM. This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=347628.0 Hi, I want to remove all extra spaces and line breaks that I have in my PHP, HTML, CSS and JavaScript files, to reduce the file size, I do not want to go through 100+ files and do this manually. Is there a PHP script that would do this? Any suggestions where I should start looking? Thanks This topic has been moved to CSS Help. http://www.phpfreaks.com/forums/index.php?topic=358236.0 |