PHP - Outputting Tables With A Function?
At the moment I have multiple pages with different HTML tables coded in (some have 5 columns and some 6 etc) and PHP echoing out data to populate from the database. The table in each page holds different data. It looks messy to me to code a different table for every page so I'm wondering if it's possible to create a function to do this? The function would have to print tables with different amounts of columns and echo out different data depending on what the page is along with table headers etc. How would I go about that?
Similar TutorialsI have three tables that I can link up via mysql and get the results I need, but I could also query just the one table and get the info from the other two via a function, my question is which is the faster and/or better way and why? Thanks Here is function that backup mysql database. It's working fine, but I want to download file instead of creating it. /* backup the db OR just a table */ function backup_tables($host,$user,$pass,$name,$tables = '*') { $link = mysql_connect($host,$user,$pass); mysql_select_db($name,$link); //get all of the tables if($tables == '*') { $tables = array(); $result = mysql_query('SHOW TABLES'); while($row = mysql_fetch_row($result)) { $tables[] = $row[0]; } } else { $tables = is_array($tables) ? $tables : explode(',',$tables); } //cycle through foreach($tables as $table) { $result = mysql_query('SELECT * FROM '.$table); $num_fields = mysql_num_fields($result); $return.= 'DROP TABLE '.$table.';'; $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table)); $return.= "\n\n".$row2[1].";\n\n"; for ($i = 0; $i < $num_fields; $i++) { while($row = mysql_fetch_row($result)) { $return.= 'INSERT INTO '.$table.' VALUES('; for($j=0; $j<$num_fields; $j++) { $row[$j] = addslashes($row[$j]); $row[$j] = str_replace("\n","\\n",$row[$j]); if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; } if ($j<($num_fields-1)) { $return.= ','; } } $return.= ");\n"; } } $return.="\n\n\n"; } //save file $date= date("d-M-Y_h-i"); $handle = fopen('Backup-'.$date.'.sql','w+'); fwrite($handle,$return); fclose($handle); } Usage: Quote backup_tables('HOST','USER','PASS','TABLE'); But this will create backup file on server. I also tried to add following code in function (at the end): echo $return; header('Content-type: text/plain'); header("Content-Disposition: attachment; filename=\"$filename\""); How to just download file, without showing it on screen instead of using fwrite/fclose function? Hello, I'm trying to echo an additional variable using this: $numincorrect = '<div id="incorrectnum">Sorry, that number was not correct.</div>'; I want to incorperate: $code from require('send.php'); I've tried $numincorrect = '<div id="incorrectnum">Sorry, that number was not "$code".</div>'; However, it literally displays $code on output. Many thanks I have mysql table with Type, Month, Date, and Quantity. I am doing query, and writing to xml which will pass to chart. My error is coming because for each <row> I need to have same number of child tags. For instance, if there are six months represented in first row (<header>), I need to have six <number> tags in all the following rows, even when there may not be any Quantity for that particular month in mysql table. Right now, if a particular Type in my table doesn't show quantity for some months, than I end up with fewer <number> tags. My php is here, and xml structure below: Code: [Select] //start the XML output print "<chart>"; print "<chart_data>"; //output the first row that contains the years print "<row>"; print "<null></null>"; $category = mysql_query ("SELECT prMonth FROM table1 GROUP BY prMonth ORDER BY prDate"); for ( $column=0; $column < mysql_num_rows($category); $column++ ) { print "<header>".mysql_result ( $category, $column, "prMonth")."</header>"; } print "</row>"; //output row 2 to 4. Each row contains a type name and its data (Qty, Prem, Comm ...) $series = mysql_query ("SELECT prType FROM table1 GROUP BY prType ORDER BY prType"); for ( $row=0; $row < mysql_num_rows($series); $row++ ) { print "<row>"; $type = mysql_result ( $series, $row, "prType"); print "<string>$type</string>"; $data = mysql_query ("SELECT SUM(prQty) FROM table1 WHERE prType='$type' GROUP BY prMonth ORDER BY prDate"); for ( $column=0; $column < mysql_num_rows($data); $column++ ) { // Need to do something here to // get number tags to show zero // when there's no data for that // month print "<number>".mysql_result($data,$column)."</number>"; } print "</row>"; } //finish the XML output print "</chart_data>"; print "</chart>"; XML structu Code: [Select] <chart> <chart_data> <row> ----this row will be the head row---- </null> <header>Month name</header> <header>Month name</header> ... </row> <row> ----this row will start body rows---- <string>Type name</string> <number>total quantity for month, for this type</number> <number>total quantity for month, for this type</number> ... </row> ... </chart_data> </chart> Hi there i have a basic query that is simply not outputting, i just dont get it. Im pretty sure the query is sound. If you can spot anything wrong here please let me know. Code: [Select] $colname_RecordSet1 = "-1"; if (isset($_SERVER['MM_Username'])) { $colname_RecordSet1 = (get_magic_quotes_gpc()) ? $_SERVER['MM_Username'] : addslashes($_SERVER['MM_Username']); } mysql_select_db($database_swb, $swb); $query_resultp = sprintf("SELECT PlayerName, PlanetName, Class1, Class2, Class3, Class4 FROM planet WHERE PlayerName = %s", GetSQLValueString($colname_RecordSet1, "text")); $resultp = mysql_query($query_resultp, $swb) or die(mysql_error()); $row_resultp = mysql_fetch_assoc($resultp); $totalRows_resultp = mysql_num_rows($resultp); <?php do { echo 'Class: '; echo $row_resultp['PlanetName']; echo $row_resultp['Class1']; echo $row_resultp['Class2']; echo $row_resultp['Class3']; echo $row_resultp['Class4']; ?> <?php } while ($row_resultp = mysql_fetch_assoc($resultp)); mysql_free_result($resultp); ?> Thanks I'm doing the following query where "ctext" comes from the clues table and "answerid" and "atext" come from the answers table... Code: [Select] $sql = "SELECT * from clues, answers WHERE clues.quizid = '{$_GET['quizid']}' AND answers.quizid = '{$_GET['quizid']}'"; $result = mysql_query($sql, $connection); if (!$result) { die("Database query failed: " . mysql_error()); } else { while ($info=mysql_fetch_array($result)) { echo "<tr><td>" . $info['answerid'] . "</td>"; echo "<td>".$info['ctext']."</td>"; echo "<td>".$info['atext']."</td>"; } echo "</tr>"; } } But when this displays in the browser, it's outputting each result set twice and kinda mixed up. For example, it looks like this... 1 monkey funny 1 cat funny 2 monkey boring 2 cat boring But I want (i.e. was expecting) it to display as... 1 monkey funny 2 cat boring Can anyone tell me why it's showing TWO rows for each and seemingly mixing up the returned results? Ultimate question is this. Do I have to break apart the mysql queries in order to get PHP to display the results how I want? I gotta think there is a way to do just one query and do what I want, but I obviously can't figure it out Hi all How do I modify the below code to search multiple tables in mySQL database? $query = "select * from store_items where description like \"%$trimmed%\" or title like \"%$trimmed%\" or dimensions like \"%$trimmed%\" order by id ASC"; $numresults=mysql_query($query); $numrows=mysql_num_rows($numresults); It is for a search function and I need it to search another table called 'about_text' and 'faq_text' Thanks Pete This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=320494.0 What is the proper way to output the contents of a class? (We will assume that Getters and Setters are evil...) Let's say I have the following class... class FormHandler2 { // Define Variables. private $myFormArray; // Constructor. public function __construct($param){ $this->myFormArray = $param; } } ...and I want to be able to output its contents either via a variable dump OR by printing something to the screen. How would I do that? TomTees Hi All, I'm working on an X-Cart site. Looking through the pages, any page with an apostrophe in the content is being loaded as an � instead. The sites' char set is UTF-8. Changing it to ISO then creates an issue in itself with bulleted lists. Just wondering if anyone has had the problem in the past and if they have solved it? Any help appreciated. Cheers Hi
I have a self calling script which does the following:
Stage 1: First run, it detects that $_POST is empty, and so displays a chunk of html which prompts for a password.
Stage 2: When resubmitted, it detects $_POST and displays another chunk of html which prompts the user for some values
Stage 3; When resubmitted the second time, $_POST is detected, along with the user values and some php is executed and a menu displayed.
So, question is this, what is the best method to output the html at stage 1 and stage 2?
I have tried using echo statements and wrapping each chunk in a function = messy.
I have tried using HEREDOCS (<<<VARNAME), better but ties my HTML to my script which is a pain
I am thinking to use file_get_contents("../html/chunk1.htm") this seems quite elegant and allows me to get someone else on our team to design the HTML keeping it out of my script
Thoughts and suggestions?
Thanks as ever
p.s. who pays for this site, are donation accepted?
The code below is in a PHP file, but is really HTML with nested PHP. <img src="<?php echo WEB_ROOT; ?>images/BeachSunset.jpg" width="200" alt="Pictu Beach Sunset." title="Pictu Beach Sunset." /> I want to put it in a MySQL record and output it using PHP. So how do I re-write this code so that it can be displayed with the same end effect using a PHP Echo statement?? (I seem to be having trouble figuring things out with MySQL in the way?! Thanks, Debbie On my website, I have Sticky Forms that use the following style code... <input id="firstName" name="firstName" type="text" maxlength="30" value="<?php if(isset($firstName)){echo htmlspecialchars($firstName, ENT_QUOTES);} ?>" /><!-- Sticky Field --> Do I need to use htmlspecialchars($firstName, ENT_QUOTES); anytime I output data to the screen?? For example, in this code do I need to wrap $username?? echo ' <div class="userInfo"> <a href="#" class="username"> <strong>' . $username . '</strong> </a>'; Debbie Hello guys. I am facing a little problem on my website when I am trying to output the data from the database in the form of a table. If you go to http://sigmalogistix.com/track-trace/ and enter any on of the following B/L No's: 123456789 987651234 543216789 You can see that the table is being created but the data is not being shown to the user. If I switch back to the old code in which there was no table, then the data is being shown to the user upon entering the B/L No. Please help me guys. Attached below are the codes which I have inside the function.inc.php file and the index.php file. function.inc.php Code: [Select] <?php include 'db.inc.php'; function search_results($keywords) { $returned_results = array(); $where = ""; $keywords = preg_split('/[\s]+/', $keywords); $total_keywords = count($keywords); foreach($keywords as $key=>$keyword){ $where .= "`keywords` LIKE '%$keyword%'"; if ($key != ($total_keywords - 1)) { $where .= " AND "; } } $results = "SELECT `Bill_No`, `Origin_City`, `Origin_Country`, `Destination_City`, `Destination_Country`, `Status`, `Current_Location` FROM `billoflading` WHERE $where"; $results_num = ($results = mysql_query($results)) ? mysql_num_rows($results) : 0; if ($results_num === 0) { return false; } else { while ($results_row = mysql_fetch_assoc($results)) { $returned_results[] = array ( 'Bill_No' => $results_row['Bill_No'], 'Origin_City' => $results_row['Origin_City'], 'Origin_Country' => $results_row['Origin_Country'], 'Destination_City' => $results_row['Destination_City'], 'Destination_Country' => $results_row['Destination_Country'], 'Status' => $results_row['Status'], 'Current_Location' => $results_row['Current_Location'] ); } return $returned_results; } } ?> index.php Code: [Select] <?php include 'func.inc.php'; ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>search</title> </head> <body> <form action="" method="POST"> <p> <input type="text" name="keywords" size="17" maxlength="9" value="Enter B/L No." onfocus="if(this.value == 'Enter B/L No.'){this.value = '';}" /> <input type="submit" class="formbutton" value="Track" /> </p> </form> <?php if (isset($_POST['keywords'])) { $suffix = ""; $keywords = mysql_real_escape_string(htmlentities(trim($_POST['keywords']))); $errors = array(); if (empty($keywords)) { $errors[] = ''; } else if (strlen($keywords)<9) { $errors[] = '<br><strong>Your Bill of Lading Number must contain 9-digits.</strong>'; } else if (search_results($keywords) === false) { $errors[] = '<br><strong>Please enter a valid Bill of Lading Number.</strong>'; } if (empty($errors)) { $results = search_results($keywords); $results_num = count($results); $suffix = ($results_num !=1) ? 's' : ''; foreach($results as $result) { echo '<br><table> <thead> <tr> <th><strong>B/L No.</strong></th> <th><strong>Origin City</strong></th> <th><strong>Origin Country</strong></th> <th><strong>Destination City</strong></th> <th><strong>Destination Country</strong></th> <th><strong>Status</strong></th> <th><strong>Current Location</strong></th> </tr> </thead> <tbody> <?php while ($row = mysql_fetch_assoc($results) { ?> <tr> <td><?php echo $row["Bill_No"]; ?></td> <td><?php echo $row["Origin_City"]; ?></td> <td><?php echo $row["Origin_Country"]; ?></td> <td><?php echo $row["Destination_City"]; ?></td> <td><?php echo $row["Destination_Country"]; ?></td> <td><?php echo $row["Status"]; ?></td> <td><?php echo $row["Current_Location"]; ?></td> </tr> <?php } ?> </tbody> </table>'; } } else { foreach($errors as $error) { echo $error, '</br>'; } } } ?> </body> </html> Hello guys i am doing a search function whereby users can check whether a setting is Pass or Fail. After user press the search button, it will return the file which contain the settings the user wants. However i have encountered a problem, currently i am using if statement and && operator to search for file so if the file is missing a string whereby the preg_match function couldn't find it, it will not output the file if i check another setting. Hence i am interested on what other options can i use. Also, Is it possible to use while loop? I tried for awhile and my browser just keeps loading and loading. Thanks for the help! Example: I want to check File 1 for Maximum Password Age settings but it does not contain Service Pack Requirement string... if ((preg_match("/\bService Pack Requirement:(.*)./", $allFiles)) && (preg_match("/\bMaximum Password Age Requirement:(.*)./", $allFiles)) && (preg_match("/\bMinimum Password Length:(.*)./", $allFiles)) && (preg_match("/\bAudit Account Logon Events:(.*)./", $allFiles)) { echo "<a href=\"$file\" target=\"_blank\"> $file </a><br />"; } Hi guys, I am very simply inserting text into a table with php and mysql, and outputting it, it all works fine but when I use paragraphs when inserting it, and then try to ouput it, all the paragraphs are gone and it looks like one big block of text, I suppose the way to go around this is to use <br> instead of just enters as it probably doesnt read this, but is it possible to make this text area do read and insert <br>'s where people use enter to make paragraphs? Much help appreciated, I realize this must be a very beginner question but I am not really sure how to word this so I wasn't sure on specific search on this. I have converted xml into an array with no problems, however I'm having difficulty outputting the various attributes. Here is a sample: Code: [Select] [0] => Array ( [@attributes] => Array ( [YourId] => 1082-1 [Name] => Woodwards Metals [Description] => ) ) The bit that is confusing me is the @attributes part. How would I output the 'Name' element for example? I am trying to load all rows from a table in a database into a table on a webpage. I cannot understand why the following code does not work: Code: [Select] <?php ... echo "You are currently in a fleet. The details of the fleet are below.<br>"; $fleetName = $_SESSION['charFleetName']; $sqlFleetDetails = "SELECT * FROM `$fleetName`"; $queryFleetDetails = mysql_query($sqlFleetDetails); echo "<table>"; echo "<tr>"; echo "<th>Pilot</th>"; echo "<th>Ship</th>"; echo "<th>Type</th>"; echo "</tr>"; while($rowFleetDetails = mysql_fetch_array($queryFleetDetails)) { $charId = $rowFleetDetails['charId']; $charName = $rowFleetDetails['charName']; $shipHull = $rowFleetDetails['shipHull']; $shipType = $rowFleetDetails['shipType']; echo "<tr>"; echo "<td><a href=\"#\" onClick=\"CCPEVE.showInfo{1377, " . $charId . "}>" . $charName . "</a></td>"; echo "<td>" . $shipHull . "</td>"; if($shipType == 1) echo "<td>Logistics</td>"; if($shipType == 2) echo "<td>DPS Boat</td>"; if($shipType == 3) echo "<td>Sniper 120Km+</td>"; if($shipType == 4) echo "<td>Off-grid Booster</td>"; echo "</tr>"; } echo "</table><br>"; I originally had the $rowFleetDetails['charId'] and others in the echo instead of loading them into variables then echoing the variables but changed it to see if that was working, neither is. If I add an extra line outside of the while loop to echo the output of the array then the information is displayed fine, so I know that the information is being transferred from the table into the array correctly, but why is it not outputting properly in the While loop? Hi, It's been a while since I've been on here... I've got a script that takes an image url and resizes it, then outputs it to the screen (using image headers etc). I've then got a htaccess file that changes my nice url, such as: 'images/thumb/50-70/logo.jpg' to: 'incudes/resize.php?width=50&height=70&img=logo.jpg' Which is the resize script, so I can use a nice url in img tags. The width and height are just the maximum allowed, so sometime the image will be smaller. Now, this all works correctly, but I am now trying to find out the width and height of the thumbnailed image, from outside of the resize.php script. I thought that I could use getimagesize, but this doesn't seem to work... I first tried it using the 'nice' url: '/images/thumb/50-70/logo.jpg' Thinking that .htaccess would re-direct, but no. I then tried a direct link to the resize file: '/incudes/resize.php?width=50&height=70&img=logo.jpg' But that returns a file not found error... Although I can access the file directly. Trying the direct url without the get variables, however, successfully finds the file, but it doesn't seem to be able to detect the image dimensions. I just get a blank result.. Is PHP able to recognise htaccess re-directs? Is PHP able to parse a php file that outputs as an image? (I have all the correct headers etc set!) Thanks I'm outputting my DB to a table. I want to include a JOIN so the table shows name, email, and company (which is in a different table). Not sure where to put the join. 2 other things I'd like to do: Not all users have email and I want any NULL to output as N/A instead of NULL. Would like the rows to alternate background color between white and blue for each row. Any hints appreciated. $query= "select * from Managers"; $result=mysql_query($query); echo mysql_error(); echo '<table align="center" cellspacing="1" cellpadding="2"> <tr> <td align="left"><b>Name</b></td> <td align="left"><b>Email</b></td> <td align="left"><b>Company</b></td> </tr> '; while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo '<tr bgcolor="' . $bg . '"> <td align="left">' . $row['name'] . '</td> <td align="left">' . $row['email'] . '</td> <td align="left">' . $row['company.name'] . '</td> //Need JOIN here </tr> '; } |