PHP - Dynamic Dependent Select Box With One Table
I have a table in a database that I need to filter upon using dependent select boxes. The database was poorly designed and would be difficult to break into separate tables without affecting code written in other places. I have found some good code and understanding of how to implement the dependent select boxes if you have two tables with one column functioning as a lookup value between the two.
I have provided a short bit of sql of what the table looks like with some column names changed. I would need to first sort by lastname and have firstname dependent on the selection of lastname. Any help would be greatly appreciated. Code: [Select] create table `user` ( `id` int(3) Not Null Auto_increment, `firstname` varchar (60), `lastname` varchar (24), `age` double , `hometown` varchar (75), `job` varchar (75), `birthdate` date ); insert into `user` (`id`, `firstname`, `lastname`, `age`, `hometown`, `job`, `birthdate`) values ('1','Peter','Griffin','41','Quahog','Brewery','1960-01-01'), ('2','Lois','Griffin','40','Newport','Piano Teacher','1961-08-11'), ('3','Joseph','Swanson','39','Quahog','Police Officer','1962-07-23'), ('4','Glenn','Quagmire','41','Quahog','Pilot','1960-02-28'), ('5','Megan','Griffin','16','Quahog','Student','1984-04-24'), ('6','Stewie','Griffin','2','Quahog','Dictator','2008-03-03'); Similar TutorialsBrand new to the forum, and have only been working with HTML, PHP, & MySQL for about 3 months. I've run into an issue I can't seem to figure out how to work around. I want to have two select boxes, that are dependent on one another. For Example: First box lists types of games: RPG LARP Board Game Miniatures CCG The second box displays game names of the type selected above. I have a MySQL table setup for the second box. To be honest I kinda already have it working... with one small but MAJOR glitch. I select the first box and the page submits using onchange='this.form.submit()'. When the page reloads the first select box reverts back to it's default setting, but the second box does correctly filter & show the content based on the selection that was made in the first box. My Question: How do I set this up so that the first box displays the user selected setting while also passing the $_POST information to the second box? My Code: <table> <tr> <td width=50%> Game Type: </td> <td width=50%> <form name='game_type' action='event_submit.php' method='post'> <select name='game_type' align=center onchange='this.form.submit()' style="width:150px;margin:5px 0 5px 0;"> <option value=''>Chose a Game Type</option> <option value='RPG'>RPG</option> <option value='LARP'>LARP</option> <option value='Board Game'>Board Game</option> <option value='CCG'>Collectable Cards & Games</option> <option value='Miniatures'>Miniatures</option> </select> </form> </td> </tr> <tr> <td width=50%> Game System: </td> <td width=50%> <?php $game_type = $_POST['game_type']; echo "$game_type"; if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("DrowCon", $con); $result = mysql_query("SELECT * FROM Games WHERE Type='$game_type' ORDER BY System ASC"); echo "<form name='game_system' action='event_submit_form.php' method='post'>"; echo "<select name='game_system' align=center style='width:150px;margin:5px 0 5px 0;'>"; echo "<option value=''>Chose a Game System</option>"; while($row_game = mysql_fetch_array($result)) { echo "<option value=''>".$row_game['System']."</option>"; } echo "</form>"; mysql_close($con); ?> </td> </tr> </table> Dear Support, Here is my code: <?php if ( strtolower($_SERVER['REQUEST_METHOD']) === 'post' ) { $name = isset($_POST['name]) ? htmlspecialchars($_POST['name']) : ""; $area = isset($_POST['area']) ? htmlspecialchars($_POST['area']) : ""; $choice = isset($_POST['choice ']) ? htmlspecialchars($_POST['choice ']) : ""; //Do Others } ?> <form class="customersForm" method="post"> <div class=""> <p>Name<br /> <select style="width:120px;" name="name"> <?php $sql = "select * from `name_info` order by `name`"; $query = mysql_query($sql); $dd = '<option>Name</option>'; while($row = mysql_fetch_object($query)) { $dd .= '<option>'.$row->name.'</option>'; } echo $dd; ?> </select> </p> </div> <div class=""> <p>Area<br /> <select style="width:120px;" area="area"> <?php $sql = "select * from `area_info` order by `area`"; $query = mysql_query($sql); $dd = '<option>Area</option>'; while($row = mysql_fetch_object($query)) { $dd .= '<option>'.$row->area.'</option>'; } echo $dd; ?> </select> </p> </div> <div class=""> <p>Choice<br /> <select style="width:120px;" choice="choice"> <?php $sql = "select * from `choice_info` where `name`='".$name."' and `area`='".$area."' order by `choice`"; $query = mysql_query($sql); $dd = '<option>Choice</option>'; while($row = mysql_fetch_object($query)) { $dd .= '<option>'.$row->choice.'</option>'; } echo $dd; ?> </select> </p> </div> ......//Others input fields ...some text fields ... </ form> I have the above code, where I would like to show the choice Drop-down box, depends on $name and $area match of the choice_info table. $name field and $area field needs to have any dependency and straight from the MySQL table. But, choice needs to depend on $name & $area. How can I do it without much using Javacript? I do not mind to use JavaScript, but prefer to minimal. By the way, I will have some other input fields too. It's an input form but, one drop-down box will be depends on two others choice. Thanks for your help. Thanks in advance for any help that you may be able to provide. I'm a graphic designer with VERY limited knowledge of php, javascript, etc. I'm trying to create a form on my company's website that will allow customers to view specifications for particular products. I'm trying to use selection boxes to narrow the customer's search, with the selection from the second box dependent on the first, and the resulting information displayed dependent on the choice from the second list. So far, I've only been able to adapt some code I found in a tutorial to display the data in the first selection box. No matter what I've tried, I can't seem to get any information to display in the second box, let alone information that is dependent on the first selection. I am brand new to php and javascript, and I didn't even know AJAX, JSON, or JQuery even existed until only a few days ago. Below is the three php files I'm using to try and make this work. If someone could point out what is wrong with it, I would be eternally grateful. Here is the code from db.php, the file I'm using to connect to my database: Code: [Select] <?php /*changing "db_username" to "root", changing "db_password" to "xxXXXX", changing "database" to "trailers" */ mysql_connect("localhost", "root", "xxXXXX") or die(mysql_error()); mysql_select_db("trailers") or die(mysql_error()); ?> Here is the code from func.php, the file with all the functions and database queries: Code: [Select] <?php //************************************** // Page load dropdown results - changing tier_one to tnttrailer_brand, changing two_drops to trailerquote, changing 'tier_one' to 'tnttrailer_brand' // //************************************** function getTierOne() { $result = mysql_query("SELECT DISTINCT tnttrailer_brand FROM trailerquote") or die(mysql_error()); while($tier = mysql_fetch_array( $result )) { echo '<option value="'.$tier['tnttrailer_brand'].'">'.$tier['tnttrailer_brand'].'</option>'; } } //************************************** // First selection results - changing two_drops to trailerquote, changing tier_one to tnttrailer_brand, changing 'tier_two' to 'trailer_description', // //************************************** if($_GET['func'] == "drop_1" && isset($_GET['func'])) { drop_1($_GET['drop_var']); } function drop_1($drop_var) { include_once('db.php'); $result = mysql_query("SELECT trailer_description FROM trailerquote WHERE tnttrailer_brand='$drop_var'") or die(mysql_error()); echo '<select name="tier_two" id="tier_two"> <option value=" " disabled="disabled" selected="selected">Choose one</option>'; while($drop_2 = mysql_fetch_array( $result )) { echo '<option value="'.$drop_2['trailer_description'].'">'.$drop_2['trailer_description'].'</option>'; } echo '</select> '; echo '<input type="submit" name="submit" value="Submit" />'; } ?> Finally, this is the code from index.php, the file with the form, javascript and the AJAX: Code: [Select] <?php include('db.php'); include('func.php'); ?><!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>Chained Select Boxes using PHP, MySQL and jQuery</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#wait_1').hide(); $('#drop_1').change(function(){ $('#wait_1').show(); $('#result_1').hide(); $.get("func.php", { func: "drop_1", drop_var: $('#drop_1').val() }, function(response){ $('#result_1').fadeOut(); setTimeout("finishAjax('result_1', '"+escape(response)+"')", 400); }); return false; }); }); function finishAjax(id, response) { $('#wait_1').hide(); $('#'+id).html(unescape(response)); $('#'+id).fadeIn(); } </script> </head> <body> <p> <form action="" method="post"> <select name="drop_1" id="drop_1"> <option value="" selected="selected" disabled="disabled">Select a Category</option> <?php getTierOne(); ?> </select> <span id="wait_1" style="display: none;"> <img alt="Please Wait" src="ajax-loader.gif"/> </span> <span id="result_1" style="display: none;"></span> </form> </p> <p> <?php if(isset($_POST['submit'])){ $drop = $_POST['drop_1']; $tier_two = $_POST['trailer_description']; echo "You selected "; echo $drop." & ".$tier_two; } /* changed 'tier_two' to 'trailer_description' */ ?> </body> </html> Here's the page on my website. I'm using Joomla for my website, and the above php is loaded into a module at the bottom of the page: http://www.tnttrailer.com/index.php/dimensions.html This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=347324.0 Hi, I wonder if I somebody can help me I have three drop down lists which are populated from data thats stored in my sql database. I also have a table which is echoed from the database all on the same page. What i want to do is allow users to select values in the drop down lists which will then echo different results below in the table. Is this possible. So on page load it will show all of the info in the html table. Then when the user changes the drop downs and clicks submit it will change the query to something SELECT dropdown1 value FROM users where Dropdown2 = 1 AND Dropdown3 = 2 etc. Is this possible to display this information on the same page using the dropdown list or does it need to load a different page as the client side is trying to edit a server side script? If its possible please can someone give me an example. Thanks in advance Edd I'm having trouble getting the dynamic data from my <select> menus to write into my MYSQL database. Can anyone see what I'm doing wrong here? First post btw The output looks like this, which is obviously wrong: Code: [Select] <html> <head> </head> <link rel="stylesheet" type="text/css" href="./css/newuser.css" /> <body> <?php session_start(); require 'default.inc.php'; ?> <?php if (isset($_POST['amount'])): $host = 'localhost'; $user = 'user'; $pass = 'password'; $conn = mysql_connect($host, $user, $pass); if (!$conn) { exit('<p>Unable to connect to the database server</p>'); } if (!@mysql_select_db('spikesusers')) { exit('<p>Unable to locate the database</p>'); } $locationname = $_POST['donor']; $donorid = mysql_query("SELECT id FROM donors WHERE locationname='$locationname'"); $amount = $_POST['amount']; $year = $_POST['year']; $type = $_POST['type']; $typeid = mysql_query("SELECT id FROM donationtype WHERE type='$type'"); $player = $_POST['player']; //$playerid = mysql_query("SELECT id FROM players WHERE $sql = "INSERT INTO donations SET donorid='$donorid', amount='$amount', yearofdonation='$year', typeid='$typeid'"; mysql_query($sql); ?> <div class='standard'> <h1>Donation Management</h1> <?php if ($sql) { echo "New donation added "; echo "<p></p>"; echo "<a href=managedonations.php>Back to donation management</a>"; exit(); } else { echo "Error adding new donation"; echo "<a href=adddonation.php>Try again</a>"; exit(); } ?></div> <?php else: $host = 'localhost'; $user = 'user'; $pass = 'pass'; $conn = mysql_connect($host, $user, $pass); if (!$conn) { exit('<p>Unable to connect to the database server</p>'); } if (!@mysql_select_db('spikesusers')) { exit('<p>Unable to locate the database</p>'); } $donor=@mysql_query('SELECT id, locationname FROM donors'); ?> <div class='standard'> <h1>Donation Management</h1> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <label>Donor: <select class="text" name="donor"> <option value=new>Add a new donor...</option> <?php while ($donors=mysql_fetch_array($donor)) { $donorname=$donors['locationname']; echo "<option value='<?php echo $donorname;?>'>$donorname</option>"; //echo "<option value='hi'>hi</option>"; } ?> </option> </select> </label><br /> <label>Amount: <input class="text" type="text" name="amount" class="text" /></label><br /> <label>Year of donation: <select class="text" name="year"> <option value='2011'>2011</option> <option value='2010'>2010</option> <option value='2009'>2009</option> </select> </label><br /> <?php $player=@mysql_query('SELECT id, firstname, lastname FROM players'); ?> <label>Player: <select class="text" name="player"> <option value="player" selected="selected"></option> <?php while ($players=mysql_fetch_array($player)) { $playerfirstname=$players['firstname']; $playerlastname=$players['lastname']; echo "<option value=player>$playerfirstname $playerlastname</option>"; } ?> </select> </label><br /> <?php $type=@mysql_query('SELECT id, type FROM donationtype'); ?> <label>Donation type: <select class="text" name="type"> <?php while ($types=mysql_fetch_array($type)) { $donationtype=$types['type']; echo "<option value=type>$donationtype</option>"; } ?> </select> </label><br /> <input type="submit" value="SUBMIT" class="buttons"/> <input type="button" name="Cancel" value="CANCEL" onclick="window.location = 'managedonations.php'" class="buttons"/> </form> </div> <?php endif; ?> </body> </html> Hi, sorry for being a newbie, but I need help setting up a dynamic form. The form will be a reservation type form. I have a single table, which I will post below. What I am looking to do is choose a month from a select box and then have it populate another select box with the available dates. Here is my table info from mysql... Code: [Select] CREATE TABLE `daterange` ( `RID` int(5) NOT NULL auto_increment, `DEND` date NOT NULL, `MONTH` varchar(50) NOT NULL, `DATE` varchar(50) NOT NULL, `SITE` varchar(50) NOT NULL, `PRICE` varchar(10) NOT NULL, `STATUS` varchar(1) NOT NULL default 'A', `FNAME` varchar(50) NOT NULL, `LNAME` varchar(50) NOT NULL, `ADDR1` varchar(50) NOT NULL, `ADDR2` varchar(50) NOT NULL, `CITY` varchar(50) NOT NULL, `STATE` varchar(2) NOT NULL, `ZIP` varchar(5) NOT NULL, `PHONE1` varchar(3) NOT NULL, `PHONE2` varchar(3) NOT NULL, `PHONE3` varchar(4) NOT NULL, `EMAIL` varchar(50) NOT NULL, PRIMARY KEY (`RID`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=83 ; Here is a sample mysql dump... Code: [Select] INSERT INTO `daterange` VALUES(1, '2011-05-15', 'May 2011', '5/15-5/22/11', 'Carterville Pond/Adirondack', '$2625.00', 'N', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''); INSERT INTO `daterange` VALUES(2, '2011-05-22', 'May 2011', '5/22-5/29/11', 'Carterville Pond/Adirondack', '$2625.00', 'A', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''); INSERT INTO `daterange` VALUES(3, '2011-05-29', 'May 2011', '5/29-6/5/11', 'Carterville Pond/Adirondack', '$2625.00', 'A', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''); Finally, here is a php form that I started to develop but it only has a single select box, which works but I wanted another select box that will filter the list down a little... Code: [Select] <? // script to display all the Available Reservations in the daterange table // connection information $hostName = "my_host"; $userName = "my_user"; $password = "my_pass"; $dbName = "my_db"; // make connection to database mysql_connect($hostName, $userName, $password) or die("Unable to connect to host $hostName"); mysql_select_db($dbName) or die("Unable to select database $dbName"); // Select all the fields in all the records of the daterange table $query = "SELECT * FROM daterange WHERE DEND > DATE(NOW()) AND STATUS='A' ORDER BY RID, DATE, SITE"; $result = mysql_query($query); // Determine the number of reservation dates $number = mysql_numrows($result); // Create drop-down menu of reservation dates print "<font size=\"3\" face=\"Arial\"><b>Select Reservation Date:</b> <form action=\"test.php\" method=\"post\"> <select name=\"RID\"> <option value=\"\">Choose One</option>"; for ($i=0; $i<$number; $i++) { $RID = mysql_result($result,$i,"RID"); $DATE = mysql_result($result,$i,"DATE"); $SITE = mysql_result($result,$i, "SITE"); $PRICE = mysql_result($result,$i, "PRICE"); print "<option value=\"$RID\">$DATE, $SITE, $PRICE</option>"; } print "</select><p align=left><label><font size=\"3\" face=\"Arial\">First Name: <input type=\"text\" name=\"FNAME\" size=\"50\" maxlength=\"50\" tabindex=\"1\"<br>"; print "<p align=left><label>Last Name: <input type=\"text\" name=\"LNAME\" size=\"50\" maxlength=\"50\" tabindex=\"2\"<br>"; print "<p align=left><label>Address Line 1: <input type=\"text\" name=\"ADDR1\" size=\"50\" maxlength=\"50\" tabindex=\"3\"<br>"; print "<p align=left><label>Address Line 2: <input type=\"text\" name=\"ADDR2\" size=\"50\" maxlength=\"50\" tabindex=\"4\"<br>"; print "<p align=left><label>City: <input type=\"text\" name=\"CITY\" size=\"50\" maxlength=\"50\" tabindex=\"5\"<br>"; print "<p align=left><label>State (abbrev.): <input type=\"text\" name=\"STATE\" size=\"2\" maxlength=\"2\" tabindex=\"6\"<br>"; print "<p align=left><label>Zip Code: <input type=\"text\" name=\"ZIP\" size=\"5\" maxlength=\"5\" tabindex=\"7\"<br>"; print "<p align=left><label>Contact Phone Number: (<input type=\"text\" name=\"PHONE1\" size=\"3\" maxlength=\"3\" tabindex=\"8\""; print "<label>)<input type=\"text\" name=\"PHONE2\" size=\"3\" maxlength=\"3\" tabindex=\"9\""; print "<label>-<input type=\"text\" name=\"PHONE3\" size=\"4\" maxlength=\"4\" tabindex=\"10\"<br>"; print "<p align=left><label>Email: <input type=\"text\" name=\"EMAIL\" size=\"50\" maxlength=\"50\" tabindex=\"11\"<br>"; print "<p align=left><label>Payment Method: <select name=\"PM\"> <option value=\"\">Choose One</option> <option value=\"Visa\">Visa</option> <option value=\"Mastercard\">Mastercard</option> <option value=\"Discover\">Discover</option>"; print "</select><p align=left><label>Credit Card Number: <input type=\"text\" name=\"C1\" size=\"4\" maxlength=\"4\" tabindex=\"12\""; print "<label> <input type=\"text\" name=\"C2\" size=\"4\" maxlength=\"4\" tabindex=\"13\""; print "<label> <input type=\"text\" name=\"C3\" size=\"4\" maxlength=\"4\" tabindex=\"14\""; print "<label> <input type=\"text\" name=\"C4\" size=\"4\" maxlength=\"4\" tabindex=\"15\"<br>"; print "<p align=left><label>Expiration Month: <select name=\"EXM\"> <option value=\"\">Choose One</option> <option value=\"January\">January</option> <option value=\"February\">February</option> <option value=\"March\">March</option> <option value=\"April\">April</option> <option value=\"May\">May</option> <option value=\"June\">June</option> <option value=\"July\">July</option> <option value=\"August\">August</option> <option value=\"September\">September</option> <option value=\"October\">October</option> <option value=\"November\">November</option> <option value=\"December\">December</option>"; print "</select><p align=left><label> Expiration Year: <select name=\"EXY\"> <option value=\"\">Choose One</option> <option value=\"2011\">2011</option> <option value=\"2012\">2012</option> <option value=\"2013\">2013</option> <option value=\"2014\">2014</option> <option value=\"2015\">2015</option> <option value=\"2016\">2016</option> <option value=\"2017\">2017</option> <option value=\"2018\">2018</option> <option value=\"2019\">2019</option> <option value=\"2020\">2020</option>"; print "</select><p align=left><label>Security Code (3 or 4 digits): <input type=\"text\" name=\"CSC\" size=\"4\" maxlength=\"4\" tabindex=\"16\"<br>"; print "<p align=left><input type=\"submit\" value=\"Book Now!\" name=\"submit\"></form>"; print " <input type=\"reset\" value=\"reset\" name=\"reset\"></form>"; // Close the database connection mysql_close(); ?> Sorry this is so long, any help would be appreciated...... -Bob I want to create 2 select menus - one static (Menu 1) and the other (Menu 2) populated according to the selection made in Menu 1. Data will will be pulled from a CSV file. Menu 2 will not have any values in it until an option from Menu 1 has been selected. Then, the options available will be limited based on the Item 1 selection. PHP must be used to read the CSV file and to capture the data (using arrays) I met this problem before and my approach then was to call a function using the onChange event for Menu1 ... <script type = "text/javascript">function update_select(obj){ window.location.href="./call_stats_main.php?choice=" + obj.value;} </script> onchange="update_select(this) This would reload the page passing a parameter to the URL (?choice=) I could then use $_GET['choice'] to capture the selected value and dynamically populate Menu 2 according to this value. It is the onchange event that triggers the population of menu 2. I would like to know IF THERE IS A BETTER WAY, other than using ajax ? Steven M Hi, I had a form which contains, 8 select boxes. In those 8 select boxes, 3 of the boxes are interlinked, like, I am able to generate data in other 2 select boxes, if one box is been selected. i.e. based upon selection of one select box, and i am able to generate data in other select box. So, 3 select boxes are interlinked. And remaining 5 selects are optional, if the user selects, then we need to generate data based upon selection of the user. Here the main issue is how to grab data in the post back form, like, how to capture the number of selects boxes selected and what are those selected, and based upon that we need to generate data. Here one more important thing is that, in the report generation form(postback form), I need to show the data in a table. So , in table I had 9 columns and these would be common to whatever the selection made, but, only the requeired data would be changed based upon the selection of the remaining 5 optional boxes. Hope you got me!!!! I have 2 queries that I want to join together to make one row
Hello I am trying to display some results in a while loop, and would prefer to do this in a table instead of just echoing to the screen... This is my code: Code: [Select] while ($row = mysql_fetch_assoc($results)) { $issue = $row[name]; echo $issue; } Showing these in a single column table would be fine, but not sure how... Thanks i'm trying to achive this results layout: example: catagory comment comment comment catagory catagory catagory comment what is being pulled now is if their is 2 comments two 1 catagory then 2 catagorys are being returned with the same id. what i want is to return one cataogry with many comments. thanks in advance for your help. Code: [Select] <?php require_once('Connections/Del_Comments.php'); ?> <?php $all_ids = array(); $str_ids = ""; // first parent query $maxRows_sourceType = 10; $pageNum_sourceType = 0; if (isset($_GET['pageNum_sourceType'])) { $pageNum_sourceType = $_GET['pageNum_sourceType']; } $startRow_sourceType = $pageNum_sourceType * $maxRows_sourceType; mysql_select_db($database_Del_Comments, $Del_Comments); $query_sourceType = "SELECT a.Id, a.Type, a.Dates, a.UIdFk, b.Id as Did, b.comment, b.dates as Day, b.sfk as Sfk , c.sfk as sfk1, d.Memo as memo FROM asstatusupdate as a left join asstatusdata as b on a.id = b.sfk left join asmanystatusupdate as c on b.sfk = c.sfk left join ascomments as d on d.id = c.cfk where a.uidfk='1' order by Dates asc"; $query_limit_sourceType = sprintf("%s LIMIT %d, %d", $query_sourceType, $startRow_sourceType, $maxRows_sourceType); $sourceType = mysql_query($query_limit_sourceType, $Del_Comments) or die(mysql_error()); $row_sourceType = mysql_fetch_assoc($sourceType); if (isset($_GET['totalRows_sourceType'])) { $totalRows_sourceType = $_GET['totalRows_sourceType']; } else { $all_sourceType = mysql_query($query_sourceType); $totalRows_sourceType = mysql_num_rows($all_sourceType); } $totalPages_sourceType = ceil($totalRows_sourceType/$maxRows_sourceType)-1; // add the array while ($row_source = mysql_fetch_assoc($sourceType)) { $all_ids[] = $row_source['Sfk']; $str_ids .= $row_source['Sfk'].','; } // remove the array $str_ids = (substr($str_ids,-1) == ',') ? substr($str_ids, 0, -1) : $str_ids; echo $str_ids; //echo $all_ids; //second child query $maxRows_sourceComments = 10; $pageNum_sourceComments = 0; if (isset($_GET['pageNum_sourceComments'])) { $pageNum_sourceComments = $_GET['pageNum_sourceComments']; } $startRow_sourceComments = $pageNum_sourceComments * $maxRows_sourceComments; mysql_select_db($database_Del_Comments, $Del_Comments); $query_sourceComments = "SELECT c.sfk as sfk1, d.Memo as memo FROM asmanystatusupdate as c left join ascomments as d on d.id = c.cfk where c.uidfk0='1' and c.sfk in ($str_ids)"; $query_limit_sourceComments = sprintf("%s LIMIT %d, %d", $query_sourceComments, $startRow_sourceComments, $maxRows_sourceComments); $sourceComments = mysql_query($query_limit_sourceComments, $Del_Comments) or die(mysql_error()); $row_sourceComments = mysql_fetch_assoc($sourceComments); if (isset($_GET['totalRows_sourceComments'])) { $totalRows_sourceComments = $_GET['totalRows_sourceComments']; } else { $all_sourceComments = mysql_query($query_sourceComments); $totalRows_sourceComments = mysql_num_rows($all_sourceComments); } $totalPages_sourceComments = ceil($totalRows_sourceComments/$maxRows_sourceComments)-1; $resultComments = @mysql_query($query_sourceComments, $Del_Comments); $numComments = @mysql_num_rows($resultComments); $result = @mysql_query($query_sourceType, $Del_Comments); $num = @mysql_num_rows($result); // column count for parent $thumbcols = 1; // column count for parent query $thumbrows = 1+ round($num / $thumbcols); // column count for child query $thumbrowsComments = 1+ round($numComments/$thumbcols); // header print '<br />'; print '<table align="center" width="500" border="3" cellpadding="0" cellspacing="0">'; if (!empty($num)) { print '<tr><td colspan="3" align="center"><strong>Returned Num of Record Sets: ' .$num. ' and comments count' .$numComments. '</strong></td></tr>'; } // table layout for parent query function display_table() { // global variables global $num, $result, $thumbrows, $thumbcols, $resultComments, $numComments, $thumbrowsComments ; // row count for parent for ($r=1; $r<=$thumbrows; $r++) { // print table row print '<tr>'; //format the columns for ($c=1; $c<=$thumbcols; $c++) { print '<td align="center" valign="top">'; $row = @mysql_fetch_array($result); $row1 = @mysql_fetch_array($resultComments); $Id = $row['Id']; $Type = $row['Type']; $Dates = $row['Dates']; $Comment = $row['Comment']; $Sfk1 = $row['sfk1']; $Memo = $row['memo']; // test if not empty show record sets if (!empty($Id)) { // print output from parent query // grab type dates comment and format for there column echo '<td valign="top" align="center">'; echo "$Type"; echo ' '; echo "$Dates"; echo '<br />';echo '<br />';echo '<br />'; echo "$Comment"; echo '</td>'; echo '<td>'; echo "$Id"; echo '</td>'; echo '<td>'; echo "$str_ids"; echo '</td>'; echo '<tr>'; echo '<td>'; echo "$Sfk1"; echo '</td>'; echo '<td>'; echo "$Memo"; echo '</td>'; echo '</tr>'; } // closing the $id loop else { print ' '; } print '</td>'; //closing the table data } //closing the rows print '</tr>'; } // closing the outter loop //} //closing fk id loop print '</td>'; //closing the table data } //closing the rows print '</tr>'; //} // closing the main loop // call the main table display_table() ; print '</table>'; ?> <?php var_dump(substr('a', 1)); // bool(false) ?> I think that I am in way over my head here... What I want is a connection to a bunch of tables at once. (eg: name1_tbl, name2_tbl name3_tbl...etc....) I want to get those names without the "_tbl" from a different table that displays them like this: name1, name2, name3...etc. I THINK i want the end output to be something like this: Code: [Select] <?php $name1 = mysql_query = ('SELECT* FROM name1_tbl ORDER BY user_id DESC'); $name2 = mysql_query = ('SELECT* FROM name2_tbl ORDER BY user_id DESC'); $name3 = mysql_query = ('SELECT* FROM name3_tbl ORDER BY user_id DESC'); // for how ever many there are ?> i just dont know how to get to that point, and dont want to add them manually when a new person and table is added.. I dont know if this makes any sense...if anyone could help it would be much appreciated.. Hi, I want to be able to sort table columns dynamically, like clicking on a header arrow? I have no idea where to start. I did a google search and I found lots of pre-made extensions bu not a simple tutorial to get me started. Can you point me in the right direction? Thanks I am trying to export a dynamically created table (one that has been filtered from user inputs) into a csv file format. I have simplified the database and code for ease of use. I also have generated the export file which will extract all information from the table in the database, but I need the information that is filtered by the user to be extracted. Files are shown below. How might I modify my export.php file (or other files) to accomplish this? Thanks in Advance export.php <?php include 'config.php'; $table = 'user'; $file = 'export'; $result = mysql_query("SHOW COLUMNS FROM ".$table.""); $i = 0; if (mysql_num_rows($result) > 0) { while ($row = mysql_fetch_assoc($result)) { $csv_output .= $row['Field'].", "; $i++; } } $csv_output .= "\n"; $values = mysql_query("SELECT * FROM ".$table.""); while ($rowr = mysql_fetch_row($values)) { for ($j=0;$j<$i;$j++) { $csv_output .= $rowr[$j].", "; } $csv_output .= "\n"; } $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"); print $csv_output; exit; ?> config.php <?php $con = mysql_connect('localhost', 'root', ''); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("test", $con); ?> index.php <?php include('config.php'); //Include the database connections in it's own file, for easy integration in multiple pages. $lastname_result = mysql_query("SELECT lastname FROM user GROUP BY lastname"); $result = mysql_query("SELECT * FROM user"); ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <link href="start/jquery-ui-1.8.4.custom.css" rel="stylesheet" type="text/css"/></link> <link href="../themes/style.css" rel="stylesheet" type="text/css" media="print, projection, screen" /></link> <link href="../common.css" rel="stylesheet" type="text/css"></link> <script type="text/javascript" src="jquery-1.4.2.min.js"></script> <script type="text/javascript" src="jquery.tablesorter.js"></script> <script type="text/javascript" src="jquery-ui-1.8.4.custom.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#myTable").tablesorter({widgets: ['zebra']}); $("#options").tablesorter({sortList: [[0,0]], headers: { 3:{sorter: false}, 4:{sorter: false}}}); } ); function reSort(par) { $("#tableBody").empty(); var vfrom = document.getElementById('from').value; var vto = document.getElementById('to').value; $.get('table.list.php?from='+vfrom+'&to='+vto+'&lastname='+par,function(html) { // append the "ajax'd" data to the table body $("#tableBody").append(html); // let the plugin know that we made a update $("#myTable").trigger("update"); // set sorting column and direction, this will sort on the first and third column var sorting = [[0,0]]; // sort on the first column $("#myTable").trigger("sorton",[sorting]); }); } function getNames() { var vfrom = document.getElementById('from').value; var vto = document.getElementById('to').value; $("#selectbox").empty(); $.get('select.list.php?from='+vfrom+'&to='+vto,function(html) { $("#selectbox").append(html); }); } </script> </head> <body> <table width="100%" border="0" cellspacing="0" cellpadding="5" class="main"> <tr> <td width="160" valign="top"></td> <td width="732" valign="top"> <table width="90%" border="0" align="center"> <form method="post"> <label for="from">From</label> <input type="text" id="from" name="from" onkeyup="getNames();"/> <label for="to">to</label> <input type="text" id="to" name="to" onkeyup="getNames();"/> <select id="selectbox" name="area" onchange="reSort(this.value);"> <option value="">Select an lastname</option> <option value=""></option> <?php while(list($lastname)=mysql_fetch_array($lastname_result)) { echo "<option value='$lastname'>$lastname</option>"; } ?> </select> </form> <form action="export.php"> <input type="Submit" value="Export to Excel"></input> </form> </table> <table id="myTable" class="tablesorter" border="0" cellpadding="5" cellspacing="1"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Age</th> <th>Birthday</th> <th>Hometown</th> <th>Job</th> </tr> </thead> <tbody id="tableBody"> <?php //added id to the tbody so we could change the content via javascript ?> </tbody> </table> <p> </p> <p> </p> <p align="right"> </p> </td> <td width="196" valign="top"> </td> </tr> </table> </body> </html> select.list.php <?php include('config.php'); //database connections. if(!isset($_GET['to']) && !isset($_GET['from'])) { //if the uri parameters are not there send em to google. header('Location: http://google.com'); exit(); } $from = (isset($_GET['from'])) ? date('Y-m-d',strtotime($_GET['from'])) : NULL; $to = (isset($_GET['to'])) ? date('Y-m-d',strtotime($_GET['to'])) : NULL; if($from != NULL && $to != NULL) { $where = " WHERE birthdate BETWEEN '$from' AND '$to'"; } elseif($from != NULL) { $where = " WHERE birthdate >= '$from'"; } elseif($to != NULL) { $where = " WHERE birthdate <= '$to'"; } $query = "SELECT lastname FROM user $where GROUP BY lastname"; //write the query. //echo $query; $lastname_result = mysql_query($query) or die($query . ' ' . mysql_error()); //execute the query, or die trying. echo '<option value="">Select an lastname</option> <option value=""></option> '; while(list($lastname)=mysql_fetch_array($lastname_result)) { echo "<option value='$lastname'>$lastname</option>"; } ?> table.list.php <?php include('config.php'); //database connection. if(!isset($_GET['lastname'])) { //if the proper get parameter is not there, redirect to google. header('Location: http://google.com'); exit(); } $lastname = preg_replace('~[^A-Za-z]+~','',$_GET['lastname']); //strip out anything but alpha for the name. $lastname = trim($lastname); //trim the name from all whitespace. if($lastname != '') { //check against an empty string. could have just used "empty()". $where = ' WHERE lastname = \'' . $lastname . '\''; //write the where clause. } else { //if lastname is empty, the where clause will be to, and it will return all names. $where = NULL; unset($lastname); } $from = (isset($_GET['from'])) ? date('Y-m-d',strtotime($_GET['from'])) : NULL; $to = (isset($_GET['to'])) ? date('Y-m-d',strtotime($_GET['to'])) : NULL; if($from != NULL && $to != NULL) { $where .= (isset($lastname)) ? ' AND ' : ' WHERE '; $where .= " birthdate BETWEEN '$from' AND '$to'"; } elseif($from != NULL) { $where .= (isset($lastname)) ? ' AND ' : ' WHERE '; $where .= " birthdate >= '$from'"; } elseif($to != NULL) { $where .= (isset($lastname)) ? ' AND ' : ' WHERE '; $where .= " birthdate <= '$to'"; } $query = "SELECT * FROM user $where"; $result = mysql_query($query); //get the database result. while($row=mysql_fetch_assoc($result)){ //loop and display data. ?> <tr> <td><?php echo $row['firstname']; ?></td> <td><?php echo $row['lastname']; ?></td> <td><?php echo $row['age']; ?></td> <td><?php echo $row['birthdate']; ?></td> <td><?php echo $row['hometown']; ?></td> <td><?php echo $row['job']; ?></td> </tr> <?php } // End while loop. ?> sql code Code: [Select] create table `user` ( `id` double , `firstname` varchar (60), `lastname` varchar (24), `age` double , `hometown` varchar (75), `job` varchar (75), `birthdate` date ); insert into `user` (`id`, `firstname`, `lastname`, `age`, `hometown`, `job`, `birthdate`) values('1','Peter','Griffin','41','Quahog','Brewery','1960-01-01'); insert into `user` (`id`, `firstname`, `lastname`, `age`, `hometown`, `job`, `birthdate`) values('2','Lois','Griffin','40','Newport','Piano Teacher','1961-08-11'); insert into `user` (`id`, `firstname`, `lastname`, `age`, `hometown`, `job`, `birthdate`) values('3','Joseph','Swanson','39','Quahog','Police Officer','1962-07-23'); insert into `user` (`id`, `firstname`, `lastname`, `age`, `hometown`, `job`, `birthdate`) values('4','Glenn','Quagmire','41','Quahog','Pilot','1960-02-28'); insert into `user` (`id`, `firstname`, `lastname`, `age`, `hometown`, `job`, `birthdate`) values('5','Megan','Griffin','16','Quahog','Student','1984-04-24'); insert into `user` (`id`, `firstname`, `lastname`, `age`, `hometown`, `job`, `birthdate`) values('6','Stewie','Griffin','2','Quahog','Dictator','2008-03-03'); I am trying to create a dynamic table that gets generated based upon users selection of last name (via a select menu) as well as the ability to filter all the table contents between two ages. Additionally, I would like the ability to select all last names between two ages as well. Each item I would hope to have a onchange command. Thanks in advance for any help on the above items. Here is the main php code <?php $con = mysql_connect('localhost', 'root', ''); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("test", $con); $lastname_result = mysql_query("SELECT lastname FROM user GROUP BY lastname"); $result = mysql_query("SELECT * FROM user"); ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <link href="../themes/style.css" rel="stylesheet" type="text/css" media="print, projection, screen" /></link> <link href="../common.css" rel="stylesheet" type="text/css"></link> </head> <body> <table width="100%" border="0" cellspacing="0" cellpadding="5" class="main"> <tr> <td width="160" valign="top"></td> <td width="732" valign="top"> <table width="90%" border="0" align="center"> <form action="test3.php" method="post"> <select name="area" onchange="submit"> <option value="">Select an lastname</option> <option value=""></option> <?php while(list($lastname)=mysql_fetch_array($lastname_result)) { echo "<option value='$lastname'>$lastname</option>"; }?> </select> <label for="startage">From</label> <input type="text" id="from" name="from"/> <label for="endage">to</label> <input type="text" id="to" name="to"/> <input type="submit" name="Submit" value="Refresh" /> </form> </table> <table id="tablesorter" class="tablesorter" border="0" cellpadding="0" cellspacing="1"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Age</th> <th>Hometown</th> <th>Job</th> </tr> </thead> <tbody> <?php while($row=mysql_fetch_assoc($result)){ ?> <tr> <td><?php echo $row['firstname']; ?></td> <td><?php echo $row['lastname']; ?></td> <td><?php echo $row['age']; ?></td> <td><?php echo $row['hometown']; ?></td> <td><?php echo $row['job']; ?></td> </tr> <?php } // End while loop. ?> </tbody> </table> <p> </p> <p> </p> <p align="right"> </p></td> <td width="196" valign="top"> </td> </tr> </table> </body> </html> and here is the sql code to generate a test database. Code: [Select] CREATE DATABASE /*!32312 IF NOT EXISTS*/`test` /*!40100 DEFAULT CHARACTER SET latin1 */; DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `firstname` varchar(20) NOT NULL, `lastname` varchar(20) NOT NULL, `age` int(3) NOT NULL, `hometown` varchar(25) NOT NULL, `job` varchar(25) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1; /*Data for the table `user` */ insert into `user`(`id`,`firstname`,`lastname`,`age`,`hometown`,`job`) values (1,'Peter','Griffin',41,'Quahog','Brewery'), (2,'Lois','Griffin',40,'Newport','Piano Teacher'), (3,'Joseph','Swanson',39,'Quahog','Police Officer'), (4,'Glenn','Quagmire',41,'Quahog','Pilot'), (5,'Megan','Griffin',16,'Quahog','Student'), (6,'Stewie','Griffin',2,'Quahog','Dictator'); Hi guys, i have a shopping cart made in php, now it works very well but i have a problem with sending its content to my email. So basicly when a customer chooses all the stuff he wants to buy i need it to send me the cart content to my email.
Here si the while loop :
while($row=mysql_fetch_array($query)) { $subtotal=$_SESSION['cart'][$row['product_id']]['quantity']*$row['price']; $totalprice+=$subtotal; ?> <tr> <td><?php echo $row['name'] ?></td> <td><input type="text" name="quantity[<?php echo $row['product_id']?>]" size="5" value="<?php echo $_SESSION['cart'][$row['product_id']]['quantity'] ?>"/></td> <td><?php echo $row['price']?>€</td> <td><?php echo $_SESSION['cart'][$row['product_id']]['quantity']*$row['price']?>€</td> </tr> <?php }So how could i copy the content of the cart that is created in this while loop and send it to email. I used <form action="checkout.php" method="post"> <textarea name="message">Full price: <?php echo $totalprice; ?></textarea> </form>Which send me a total price but i can't figure out how to send all the bought products with it. Please help me with some guidance. I want to allow users to create their own html forms by choosing different form elements (textfields, textareas, lists, ratios, etc) I guess something similar to http://wufoo.com/ but much more basic. I'm having some trouble deciding which approach I should take. Database tables or files? For tables I was thinking to create a table for each form element, e.g TEXTFIELD TABLE ID TEXTFIELD_NAME USER TEXTAREA TABLE ID TEXTAREA_NAME USER etc for all form elements and then just query all of them with.. WHERE user=$user Or should I generate php files on the server for each form created? Hello I want product filter groups by category. There will be different options. Ex: http://prntscr.com/sr00ay Product Table : http://prntscr.com/sr00rm Option Groups Table : http://prntscr.com/sr013r Options Table : http://prntscr.com/sr01fk Product Option Table : http://prntscr.com/sr01r3 How can I build this structure? And how should it be sql for filtering? Is the structure correct? I'm waiting for your help. Edited May 31, 2020 by Atakan |