PHP - Checkbox Form Selects From Mysql Table Column With Datatype Em
have a database with a column of datatype EM (multiple selection, say apples, oranges, grapes)
I want to have a form with checkboxes for those values (apples, oranges, grapes etc) so one can select a breakfast basket type that contains for example, oranges and grapes. It would pull from the database those baskets with those selection of fruits (specified in the column 'Fruits', which is a EM datatype column. (I have a multiple selection when entering the values for the column.) Can it be done? Should I make another table with FruitNames? Similar TutorialsI do not have code yet, i just want a general idea how to get started.
I have a database with +/- 15 columns. 6 people are using this database. Not all columns are relevant for each user.
So my idea was that each user will be able to make his preference by checking checkboxes for each column -> store this in the database so that when he logs in , his preference will be retrieved and used to make the right query.
second question, how do i make the headers so that they are the same als the preferences from the user ?
Just put me on the right track (or if someone has it on the shelf, post the code)
thanks in advance
I have a mysql table named songs with 3 columns, id, artist,title. Most of the songs in the artist column are correct, ex: artist ------------------ John Denver Loretta Lynn Shania Twain Luke Bryan But some of the songs in the artist column are reveresed with a comma, ex: artist ----------------- Dever, John Lynn. Loretta Twain, Shania Bryan, Luke Is there an easy php code snippet or mysql statement that i can use to reverse the order of first name and last name and remove the comma in the last example so the artst columd matches the first example? I hope this makes sense, thanks, Dale. Hi guys I hope I am in the right place on this forum, if not I apologise. A have been working with CS-Cart and had so much trouble trying to update product combinations so I searched for help on the data feeds I am using and found that there was a script that would update my products for os-commerce, this has worked out even worse. All I really need is for a script to update one column called amount in a Mysql table by referring to the product_code column, Eg If product_code NS324 is= to 5 ad 5 to the amount column. This sounds simple but I think it might be complex. Here is the Table Generated b\: phpM\Admin 3.4.9 / M\SQL 5.5.20-log SQL quer\: SELECT * FROM `cscart_product_options_inventor\` LIMIT 0, 30 ; Rows: 30 Column1-----------Column2---------------Column3--------------Column4----------Column5-------Column6-------Column7 product_id-----product_code---------combination_hash-----combination-------amount----------temp-----------position --29813--------------NS3455----------- --1447985068-----------738_3059-----------0-----------------N-------------------0 So if I can update the amount column using the product_code would solve all of my problems. So this is what I need to do, I need to add an amount to the amount column related to the product_code NS3455 or update amount or even replace amount it don't matter. Due to the nature of the feeds I receive I cannot use product_id or combination_hash or combination. Please help me do this. Lets see who is the clever one. Thanks for you time I have a table of restaurant menu items called menu_items. This table has a float row(3,2) called price. I have a query that looks like this: $query = mysql_query("SELECT * FROM menu_items WHERE restaurant = '".$restaurantid."'"); How would I find the average of the price row from that query? Basically I want to find the average item price for a restaurants menu. I was wondering just a general question here. I am just going through a text book on the main aspects of a problem solving approach to PHP, but when I was just trying out one of my own theories on this particular one of my own: <html> <body> <h1>User Input set as functions</h1> <tt>Please enter a value below:</tt> <br> <form id="userInput" name="userInput" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get"> <input type="text" id="input" name="input" value="" /> <input type="submit" value="Send This" /> </form> <?php function mistake($errorvalue) { echo $errorvalue; } function getValue($userInput) { return $userInput; } if(!isset($_GET['input']) || $_GET['input'] == '') { mistake("No value received yet!"); // calls the error function } else { $input = $_GET['input']; echo "You did enter something, this was: "; $userInput = getValue($input); echo "$userInput"; } ?> </body> </html> I am quite impressed with what I have done there, though I know its nothing special and could obviously be done not using functions at all, just wanted to see if I could get one that returns something, in this case the 'getValue()' function. But when I've set it to work out what type of variable ie gettype is it? (going off completely memory here), its always a string, even if all I do is enter a 1, even tried not using the GET method for the form and used the POST one instead it still says that a single integer is a string. Why just out of question is it doing this? Just quite interested thats all. Thanks for your time and I look forward to any replies, Jeremy. Hey guys, I'm a little confused to how I can do this.
I am basically wanting to give my first column a 'NOT NULL AUTO_INCREMENT' and give each row it's own 'id'. The issue I am having is that the script I am using truncates the whole SQL table with a CSV file that is cron'd daily to update data.
I am currently using this script:
<?php $databasehost = "localhost"; $databasename = ""; $databasetable = ""; $databaseusername=""; $databasepassword = ""; $fieldseparator = ","; $lineseparator = "\n"; $enclosedbyquote = '"'; $csvfile = "db-core/feed/csv/csv.csv"; if(!file_exists($csvfile)) { die("File not found. Make sure you specified the correct path."); } try { $pdo = new PDO("mysql:host=$databasehost;dbname=$databasename", $databaseusername, $databasepassword, array( PDO::MYSQL_ATTR_LOCAL_INFILE => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ) ); } catch (PDOException $e) { die("database connection failed: ".$e->getMessage()); } $pdo->exec("TRUNCATE TABLE `$databasetable`"); $affectedRows = $pdo->exec(" LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." REPLACE INTO TABLE `$databasetable` FIELDS OPTIONALLY ENCLOSED BY ".$pdo->quote($enclosedbyquote)." TERMINATED BY ".$pdo->quote($fieldseparator)." LINES TERMINATED BY ".$pdo->quote($lineseparator)." IGNORE 1 LINES"); echo "Loaded a total of $affectedRows records from this csv file.\n"; ?>Is it possible to amend this script to ignore my first column and truncate all of the data in the table apart from the first column? I could then give all of the rows in the first column their own ID's any idea how I could do this? I am still very nooby so please go easy on me Hey Everyone, I'm creating a site that will show images uploaded for certain days working on a job site. Kind of a day-to-day photo journal for the customer. On the site, the user gets here, sees 3 large images, and a series of thumbnails if more than 3 images exist for that day (works fine). However, underneath that I want to display a 3-4 column setup of "Archived Dates" that provide a link to the images of the other dates. I have this working correctly, but the results are displayed as follows: Date 1: Date 2: Date 3: etc.... I want them to display like this; Day 1 Day 4 Day 2 Day 5 Day 3 Day 6 and so on..... in a 3 column format. Here is the code I have right now just looping through to display these link results, not the rest of the page. I am trying to do it tableless right now, but if that isn't the right way to go, please let me know. Thanks to anyone in advance, Nick $SQLRowe = "SELECT DISTINCT RoweImgDate from tblRowe WHERE RoweImgDate !='" . $_GET['date'] . "' Order by RoweImgDate DESC Limit 0, 30"; //echo $SQLRowe; $rsSQLRowe = mysql_query($SQLRowe); <span class="rowe">Archived Photos:</span><br/> <div id="archive"> <?php while($row = mysql_fetch_array($rsSQLRowe)){ //echo "<a href='index.php?id="' . $row[RoweImgID] . '"' class='link'>$row[RoweImgDate]</a></br>"; echo "<div id='archivedates'>"; echo "<a href='index.php?date=" . $row[RoweImgDate] . "' class='link'>$row[RoweImgDate]</a>"; echo "</div>"; //echo "<img src='images/$row[RoweImage]'/><br/>"; //echo "<span class='FeatDesc'><p>$row[RoweImgDesc]</p></span><br/>"; } ?> </div> Hi all, I have a table... id | Name | Downloads | 01 | tom | 5 02 | thomas | 2 03 | tommy | 15 I need a button in my page whcih on submit would resent the 'downloads' column so all values are set to 0, Is this possible and how if it is? Thanks for any advice Hey all I'm working on an auction website. I've added a new column to the 'Auctions' table, however the 'sell.php' page now does not work with this new column (I've deleted the column and tested again and it works, so that's definitely the cause). The new column can not be in a separate table as it needs to pull 'id' values from the 'Auctions' table for various functions. My question to you is, is there any PHP snippet I can use to tell sell.php to stop reading the 'Auctions' table once it reaches the column I've added? The new column is called 'shipped' if that's of any relevance. Below is some of the PHP I'm working on on the sell.php page. #//Populate arrays $UPLOADED_PICTURES[] = $file; $UPLOADED_PICTURES_SIZE[] = filesize($image_upload_path.session_id()."/".$file); } } } $_SESSION["UPLOADED_PICTURES"] = $UPLOADED_PICTURES; $_SESSION["UPLOADED_PICTURES_SIZE"] = $UPLOADED_PICTURES_SIZE; $_SESSION["GALLERY_UPDATED"]=true; if($sessionVars['SELL_action']=='edit') { $sessionVars["OLD_GALLERYFEE"] = $SETTINGS["picturesgalleryvalue"] * count($UPLOADED_PICTURES); } else { $sessionVars["OLD_GALLERYFEE"] = 0; } } } } $with_reserve = $sessionVars["SELL_with_reserve"]; $reserve_price = $sessionVars["SELL_reserve_price"]; $minimum_bid = $sessionVars["SELL_minimum_bid"]; $duration_hours = $sessionVars["SELL_duration_hours"]; $duration_minutes = $sessionVars["SELL_duration_minutes"]; $pict_url=$sessionVars["SELL_pict_url"]; $imgtype = $sessionVars["SELL_file_uploaded"]; $title = $sessionVars["SELL_title"]; $description = stripslashes($sessionVars["SELL_description"]); $pict_url = $sessionVars["SELL_pict_url"]; $atype = $sessionVars["SELL_atype"]; $adultonly = $sessionVars["SELL_adultonly"]; $TPL_item_value = $item_value = $sessionVars["SELL_item_value"]; $TPL_number_of_bids =$number_of_bids=$sessionVars["SELL_number_of_bids"]; $TPL_bid_value = $bid_value = $sessionVars["SELL_bid_value"]; $iquantity = $sessionVars["SELL_iquantity"]; $buy_now = $sessionVars["SELL_with_buy_now"]; $buy_now_price = $sessionVars["SELL_buy_now_price"]; $duration = $sessionVars["SELL_duration"]; $duration_second = $sessionVars["SELL_duration_second"]; $minimum_users = $sessionVars["SELL_minimum_users"]; $relist = $sessionVars["SELL_relist"]; $increments = $sessionVars["SELL_increments"]; $customincrement = $sessionVars["SELL_customincrement"]; $international = ($sessionVars["SELL_international"])?"on":""; $sellcat = $_SESSION['sellcat']; $private = $sessionVars["SELL_private"]; if($private != 'y') $private = 'n'; $sendemail = $sessionVars["SELL_sendemail"]; $txt = $sessionVars["SELL_txt"]; $num = $sessionVars["SELL_num"]; $buy_now_only = $sessionVars["SELL_buy_now_only"]; and... $auction_id=$sessionVars['SELL_auction_id']; } elseif ($sessionVars["SELL_action"] == "reopen") { $query = "UPDATE BPLA_auctions set title = '".addslashes($sessionVars["SELL_title"])."', starts = '".$a_starts."', starts_second = '".$a_starts_second."', description = '".addslashes($sessionVars["SELL_description"])."', pict_url = '".addslashes($sessionVars["SELL_pict_url"])."', category = ".$sessionVars["SELL_sellcat"].", minimum_bid = '".$sessionVars["SELL_minimum_bid"]."', reserve_price = '".(($sessionVars["SELL_with_reserve"]=="yes")?$sessionVars["SELL_reserve_price"]:"0")."', buy_now = '".(($sessionVars["SELL_with_buy_now"]=="yes")?$sessionVars["SELL_buy_now_price"]:"0")."', bn_only = '".$sessionVars["SELL_buy_now_only"]."', auction_type = '".$sessionVars["SELL_atype"]."', adultonly = '".$sessionVars["SELL_adultonly"]."', duration = '".$sessionVars["SELL_duration"]."', duration_second = '".$sessionVars["SELL_duration_second"]."', minimum_users = ".intval($sessionVars["SELL_minimum_users"]).", increment = ".doubleval($sessionVars["SELL_customincrement"]).", international = '".(($sessionVars["SELL_international"])?"1":"0")."', ends = '".$a_ends."', ends_second = '".$a_ends_second."', photo_uploaded = ".(($sessionVars["SELL_file_uploaded"])?"1":"0").", quantity = ".$sessionVars["SELL_iquantity"].", relist=".intval($sessionVars["SELL_relist"]).", relisted=0, closed='0', private='n', item_value = '".$sessionVars["SELL_item_value"]."', number_of_bids = '".$sessionVars["SELL_number_of_bids"]."', bid_value = '".$sessionVars["SELL_bid_value"]."', suspended='".$SUSPENDED."',"; $query .= "current_bid=0, num_bids=0, WHERE id = '".$sessionVars["SELL_auction_id"]."'"; $backtoclosed=true; if($BPLowbidAuction_TESTMODE == 'yes'){ echo $ERR = $ERR_9999; }else{ $res=mysql_query($query); if (!$res) { MySQLError($query); exit; } $auction_id=$sessionVars['SELL_auction_id']; $sessionVars["SELL_auction_id_old"]=$auction_id; $query = "DELETE FROM BPLA_bids WHERE auction='$auction_id'"; $res = @mysql_query($query); if(!$res) { MySQLError($query); exit; } Thanks in advance for any help and replies! Here is one of those purely conceptual questions, which involves no code. I'm trying to create a select query which among other things, allows a user of a website to search other members who fall within a particular age range. I have a column in the table where the members' information are stored which records their ages. Which brings us to the problem. On any given day, a member's age may increase by one year compared to what it was the previous day, hence the need to update this column periodically. I can't think of any way to automatically update this column on a daily basis. So my solution is to run an initial update query every time a member tries to search other members based on age, which updates the age column for all other members, before running the select query which eventually retrieves the desired age range. This leads to the second problem. Imagine there are thousands of users using the website. At any given instance, there could be hundreds of members, trying to search others based on age. This means hundreds of users will be updating a single column (the age column) in one table at the same time. Is this feasible? Can it cause the server to crash? Or is there really a more reasonable way to do all of this? Thank you all for taking your time to read this. Appreciate any responses. I have a kind of search and react on my site. The user can search for a number in a column as below $search = mysqli_real_escape_string($link, $_POST["query"]); $query = "SELECT * FROM $table[$i] WHERE oemnr LIKE '".$search."%' ORDER BY model";
The code works fine but I want to expand the function to get match for other numbers also. The oemnr column today can be 12345 which shows up if the user type 12.... I want to expand the oemnr column as 12345/03124/34713, numbers separated with / or another character. If the user type 03... or 34... I want to find and show 12345 because it is on the same row and corresponds to the numbers on the same row. Is it possible to do in mysql? In php that kind of operation can be done with the explode function but I don't know how to use with mysql. Edited February 14 by jiggaSo I've spent 2 days now searching the web on how to make my checkbox array on my form insert the value selected by the user into my database. Here is the code that I've written. All fields except for the checkbox array works fine. <?php virtual('/budgets/Connections/connAdmin.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if (isset($_POST['submit'])) { $workStyle = $_POST['art_photos']; // Setting up a blank variable to be used in the coming loop. $allStyles = ""; // For every checkbox value sent to the form. foreach ($workStyle as $style) { // Append a string called $allStyles with the current array element, and then add a comma and a space at the end. $allStyles .= $style . ", "; } // Delete the last two characters from the string. $allStyles = substr($allStyles, 0, -2); echo "<p>The resulting string is: <strong>$allStyles</strong></p>\r\n"; } if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) { $insertSQL = sprintf("INSERT INTO daily_budget (rundate, slug, reporter, budgetInfo, notes, `section`, deadline, art_photos sidebar, sBudget) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['rundate'], "text"), GetSQLValueString($_POST['slug'], "text"), GetSQLValueString($_POST['reporter'], "text"), GetSQLValueString($_POST['budgetInfo'], "text"), GetSQLValueString($_POST['notes'], "text"), GetSQLValueString($_POST['section'], "text"), GetSQLValueString($_POST['deadline'], "text"), GetSQLValueString($_POST['art_photos'], "text"), GetSQLValueString($_POST['sidebar'], "text"), GetSQLValueString($_POST['sBudget'], "text")); mysql_select_db($database_connAdmin, $connAdmin); $Result1 = mysql_query($insertSQL, $connAdmin) or die(mysql_error()); } ?> <!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>Budget Record</title> </head> <body> <?php if (isset($error)) { echo '<ul>'; foreach($error as $alert) { echo "<li class='warning'>$alert</li>\n"; } echo '</ul>'; } ?> <form action="<?php echo $editFormAction; ?>" method="POST" name="form1" id="form1"> <table align="center" width="60%" border="2" bgcolor="#FFFFFF"> <tr valign="baseline"> <td width="14%" align="right" nowrap="nowrap"><STRONG>Rundate:</STRONG></td> <td width="86%"> <input type="text" name="rundate" size="30" value="" id="jQueryUICalendar2"/> <script type="text/javascript"> // BeginWebWidget jQuery_UI_Calendar: jQueryUICalendar2 jQuery("#jQueryUICalendar2").datepicker(); // EndWebWidget jQuery_UI_Calendar: jQueryUICalendar2 </script></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><STRONG>Section:</STRONG></td> <td> <select name="section"> <option value=""></option> <option value="A1">A1</option> <option value="Pickup All">Pickup All</option> <option value="Region">Region</option> <option value="Atlantic">Atlantic</option> <option value="Business">Business</option> <option value="Features">Features</option> <option value="Sports">Sports</option> </select> </td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Slug:</strong></td> <td><span id="sprytextfield2"> <input type="text" name="slug" value="" size="32" /> <span class="textfieldRequiredMsg">REQUIRED</span></span><span style="color: #F00; font-weight: bold; font-size: 10px;"></span></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Budget Information:</strong></td> <td><span id="sprytextarea1"> <textarea name="budgetInfo" cols="50" rows="4"></textarea> <span class="textareaRequiredMsg">Required.</span></span><span style="color: #F00; font-weight: bold; font-size: 11px;"></span></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Notes:</strong></td> <td><input type="text" name="notes" value="" size="32" /></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Reporter:</strong></td> <td><span id="sprytextfield3"> <input type="text" name="reporter" value="" size="32" /> <span class="textfieldRequiredMsg">Required.</span></span><span style="color: #F00; font-weight: bold; font-size: 10px;"></span></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Deadline:</strong></td> <td><input type="text" name="deadline" size="30" value="Enter date" id="jQueryUICalendar1"/><script type="text/javascript"> // BeginWebWidget jQuery_UI_Calendar: jQueryUICalendar2 jQuery("#jQueryUICalendar1").datepicker(); // EndWebWidget jQuery_UI_Calendar: jQueryUICalendar2 </script> </td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Artwork:</strong></td> <td><label> <input type="checkbox" name="art_photos[]" value="factbox" id="art_photos_0" /> Factbox</label> <label> <input type="checkbox" name="art_photos[]" value="graphic" id="art_photos_1" /> Graphic</label> <label> <input type="checkbox" name="art_photos[]" value="photo" id="art_photos_2" /> Photo</label> <label> <input type="checkbox" name="art_photos[]" value="video" id="art_photos_3" /> Video</label> <br /></td> </tr> <tr> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"> <strong>Sidebar:</strong></td> <td valign="baseline"><span id="spryradio2"> <label> <input type="radio" name="sidebar" value="y" id="sidebar_0" /> Yes</label> <br /> <label> <input type="radio" name="sidebar" value="n" id="sidebar_1" /> No</label> <br /> <span class="radioRequiredMsg"><strong style="font-size: 11px">REQUIRED.</strong></span></span> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Sidebar Information:</strong></td> <td><input type="text" name="sBudget" value="" size="32" /></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"> </td> <td><input type="submit" value="Insert record" /></td> </tr> </table> <input type="hidden" name="MM_insert" value="form1" /> </form> <p> </p> <h3><a href="/new_budget/admin/manage_budgets.php"><strong>View your budget entry, make changes or delete your budget.</strong></a></h3> <script type="text/javascript"> <!-- jQuery("#jQueryUICalendar1").datepicker(); jQuery("#jQueryUICalendar2").datepicker(); var sprytextfield2 = new Spry.Widget.ValidationTextField("sprytextfield2", "none", {maxChars:15, validateOn:["change"]}); var sprytextarea1 = new Spry.Widget.ValidationTextarea("sprytextarea1", {validateOn:["change"]}); var sprytextfield3 = new Spry.Widget.ValidationTextField("sprytextfield3"); var spryradio2 = new Spry.Widget.ValidationRadio("spryradio2"); //--> </script> </body> </html> Hi Guys, I am a typical newbie with a twist, i program in VB, recently moved to PHP. I need help, preferable an example, but first let me explain what i have. I have a .tpl page that has 3 drop down boxes, one of these is populated from within the .tpl page itself. The other 2 i waant to pupulate from a SELECT on a database from a .php file. The .TPL file i have so far is:- Code: [Select] <style type="text/css"> <!-- .style7 { color: #006600; font-weight: bold; font-size: 18px; } .style14 {color: #003300; font-weight: bold; } .style16 { color: #000066; font-style: italic; } .style25 { color: #FF0000; font-weight: bold; font-size: 12px; } .style28 { font-size: 12px; color: #330000; } .style29 { font-size: 12px } .style31 {color: #003300; font-weight: bold; font-size: 16px; } .style33 { color: #000099; font-weight: bold; font-style: italic; font-size: 18px; } .style34 { color: #FF0000; font-weight: bold; font-size: 24px; } .style35 {font-size: 12px; color: #003300; } .style36 { color: #FF0000; font-weight: bold; font-size: 14px; font-style: italic; } .style38 {color: #003300; font-weight: bold; font-size: 16px; font-style: italic; } --> </style> <script src="Scripts/AC_RunActiveContent.js" type="text/javascript"></script> <h1 align="center" class="style34">Scotbirds Alertz - Rare and Scarce</h1> <h3 align="center" class="style36">Soon Only VIP Members will be able to Access this Page</h3> <h3 align="center" class="style14">If you have seen something unusual / rare then please call it in on -- <span class="style33">Hotline: 0333 5772473</span></h3> <p align="center" class="style14"> <table width="90%" border="0" align="center" cellpadding="5"> <tr> <?php print $_SERVER['PHP_SELF']; $the_date_filter = $_GET["DATE_FILTER"];?> <td width="1%"><td width="5%"><td width="2%"><td width="2%"><td width="2%"><form action="alertz_VIP.php" method="post"> <td width="2%"><td width="2%"><td width="5%"><span class="style38">Date</span><td width="3%"></td> <td width="12%"><span class="style14"> <select name=DATE_FILTER size="1" id=DATE_FILTER onchange="this.form.submit()"> <option value="All Dates">All Dates</option> <option value="Today">Today</option> <option value="Last 48hrs">Last 48hrs</option> <option value="Last week">Last Week</option> <option value="last month">Last Month</option> </select> </span></td> <td width="1%"> </td> <td width="7%"><span class="style16"><span class="style14"><span class="style31">Region</span></span></span></td> <td width="22%"><span class="style16"><span class="style14"> <select name=REGION_FILTER size="1" id=REGION_FILTER onchange="this.form.submit()"> <option value="AllRg">All Regions</option> <option value={REGION_FILTER}></option> </select> </span></span></td> <td width="1%"> </td> <td width="8%"><span class="style16"><span class="style14"><span class="style31">Species</span></span></span></td> <td width="20%"><span class="style16"><span class="style14"> <select name=SPECIES_FILTER size="1" id=SPECIES_FILTER onchange="this.form.submit()"> <option value="AllSpec">All Species</option> <option value={SPECIES_FILTER}></option> </select> </span></span></td> <td width="9%"><input type="Submit" name="submit2" value="Search" method="get" action="alertz_VIP.php" /></td> </table> <p> </p> <table width="870" border="1" align="center" cellpadding="0" cellspacing="0" bordercolor="#99CC99"> <tr> <th width="178" class="style31" scope="col">Region</th> <th width="184" class="style31" scope="col">Species</th> <th width="96" class="style31" scope="col">Date</th> <th width="96" class="style31" scope="col">Time</th> <th width = "304" class="style31" scope="col">Comments</th> </tr> <!-- BEGIN alerts --> <tr> <th class="style7 style29" scope="col">{alerts.REGION}</th> <th class="style25" scope="col">{alerts.SPECIES}</th> <th class="style35" scope="col">{alerts.DATE} </th> <th scope="col"><span class="style35">{alerts.TIME} </span></th> <th scope="col"><span class="style28">{alerts.COMMENTS} </span></th> </tr> <!-- END alerts --> </table> <p align="center" class="style14"> </p> Now from here i expect the user to select a date from the date box, ( Ideally i would like the other 2 options to only become visible once a selection on the date has been made, i would also like to retain the selected in the date box once the form has been submited. Now the code i have for the PHP so far is quite long winded as my PHP skills are not so good, although i am learning fast. Code: [Select] <?php /*************************************************************************** * Alertz.php * ------------------- * begin : 30/10/04/10 * copyright : (C) 2010 Andy Guppy * email : webmaster@scotbird.co.uk * * ***************************************************************************/ define('IN_ICYPHOENIX', true); if (!defined('IP_ROOT_PATH')) define('IP_ROOT_PATH', './'); if (!defined('PHP_EXT')) define('PHP_EXT', substr(strrchr(__FILE__, '.'), 1)); // Include files include(IP_ROOT_PATH . 'common.' . PHP_EXT); include_once(IP_ROOT_PATH . 'includes/functions_groups.' . PHP_EXT); include(IP_ROOT_PATH . '/alerts/alertsconfig.'.PHP_EXT); // Page Authorise $cms_page_id = 'scotalertz'; $cms_page_nav = (!empty($cms_config_layouts[$cms_page_id]['page_nav']) ? true : false); $cms_global_blocks = (!empty($cms_config_layouts[$cms_page_id]['global_blocks']) ? true : false); $cms_auth_level = (isset($cms_config_layouts[$cms_page_id]['view']) ? $cms_config_layouts[$cms_page_id]['view'] : AUTH_ALL); check_page_auth($cms_page_id, $cms_auth_level); // Obtain Select Criteria $temp_region_filter = $_REQUEST["REGION_FILTER"]; $temp_species_filter = $_REQUEST["SPECIES_FILTER"]; $temp_date_filter = $_REQUEST["DATE_FILTER"]; // Filter characters if required $region_filter =str_replace(" & ", "&", $temp_region_filter); $species_filter = $temp_species_filter; $date_filter = $temp_date_filter; // standard session management $userdata = session_pagestart($user_ip); // Check to see if user is logged in if ((!$userdata['session_logged_in']) ) // No he isnt { redirect(append_sid(LOGIN_MG . '?redirect=alerts.' . PHP_EXT)); } else // Yes they are { init_userprefs($userdata); // set page title $page_title = "ScotBird alerts - VIP's ONLY !! "; // standard page header include(IP_ROOT_PATH . 'includes/page_header.'.PHP_EXT); // Connect to the database $db = new sql_db($alerts_mysql_host,$alerts_mysql_username,$alerts_mysql_password,$alerts_mysql_db,false); if(!$db) { die("Database Connection Failed:- Please Contact Site Admin" . mysql_error()); } $template->set_filenames(array('body' => 'alertz_VIP.tpl')); if (!isset($_REQUEST['DATE_FILTER'])) { // if date is NOT set then perform this echo 'Date has not been set'; $sql2 = "SELECT * FROM alerts ORDER BY Date DESC, time DESC "; $sql3 = "SELECT DISTINCT species FROM alerts GROUP BY species"; $sql = "SELECT DISTINCT region FROM alerts GROUP BY region"; echo $sql2; } else { // if date is set then perform this $year =date("Y"); $month = date("m"); $day = date("d"); $theenddate = $year . '-' .$month . '-' . $day ; echo 'the choice selected was :- '.$_REQUEST['DATE_FILTER']; switch ($date_filter) { case "All Dates": $sql2 = "SELECT * FROM alerts ORDER BY Date DESC, time DESC "; break; case "Today": $sql2 = "SELECT * FROM alerts WHERE Date = '".$theenddate ."' ORDER BY Date DESC, time DESC "; $sql3 = "SELECT DISTINCT species FROM alerts WHERE Date = '".$theenddate ."' GROUP BY species"; $sql = "SELECT DISTINCT region FROM alerts WHERE Date ='".$theenddate ."' GROUP BY region"; break; case "Last 48hrs": $year =date("Y"); $month = date("m"); $day = date("d")-1; $thestartdate = $year . '-' .$month . '-' . $day ; $sql2 = "SELECT * FROM alerts WHERE Date BETWEEN '".$thestartdate ."' AND '".$theenddate ."' ORDER BY Date DESC, time DESC "; $sql3 = "SELECT DISTINCT species FROM alerts WHERE Date BETWEEN '".$thestartdate ."' AND '".$theenddate ."' GROUP BY species"; $sql = "SELECT DISTINCT region FROM alerts WHERE Date BETWEEN '".$thestartdate ."' AND '".$theenddate ."' GROUP BY region"; break; case "Last week": $year =date("Y"); $month = date("m"); $day = date("d")-7; $thestartdate = $year . '-' .$month . '-' . $day ; $sql2 = "SELECT * FROM alerts WHERE Date BETWEEN '".$thestartdate ."' AND '".$theenddate ."' ORDER BY Date DESC, time DESC "; $sql3 = "SELECT DISTINCT species FROM alerts WHERE Date BETWEEN '".$thestartdate ."' AND '".$theenddate ."' GROUP BY species"; $sql = "SELECT DISTINCT region FROM alerts WHERE Date BETWEEN '".$thestartdate ."' AND '".$theenddate ."' GROUP BY region"; break; case "last month": $year =date("Y"); $month = date("m")-1; $day = date("d"); $thestartdate = $year . '-' .$month . '-' . $day ; $sql2 = "SELECT * FROM alerts WHERE Date BETWEEN '".$thestartdate ."' AND '".$theenddate ."' ORDER BY Date DESC, time DESC "; $sql3 = "SELECT DISTINCT species FROM alerts WHERE Date BETWEEN '".$thestartdate ."' AND '".$theenddate ."' GROUP BY species"; $sql = "SELECT DISTINCT region FROM alerts WHERE Date BETWEEN '".$thestartdate ."' AND '".$theenddate ."' GROUP BY region"; break; case "last 3 months": $year =date("Y"); $month = date("m")-3; $day = date("d"); $thestartdate = $year . '-' .$month . '-' . $day ; $sql2 = "SELECT * FROM alerts WHERE Date BETWEEN '".$thestartdate ."' AND '".$theenddate ."' ORDER BY Date DESC, time DESC "; $sql3 = "SELECT DISTINCT species FROM alerts WHERE Date BETWEEN '".$thestartdate ."' AND '".$theenddate ."' GROUP BY species"; $sql = "SELECT DISTINCT region FROM alerts WHERE Date BETWEEN '".$thestartdate ."' AND '".$theenddate ."' GROUP BY region"; break; default: // Default is the last 48hrs $year =date("Y"); $month = date("m"); $day = date("d")-1; $thestartdate = $year . '-' .$month . '-' . $day ; $sql2 = "SELECT * FROM alerts WHERE Date BETWEEN '".$thestartdate ."' AND '".$theenddate ."' ORDER BY Date DESC, time DESC "; $sql3 = "SELECT DISTINCT species FROM alerts WHERE Date BETWEEN '".$thestartdate ."' AND '".$theenddate ."' GROUP BY species"; $sql = "SELECT DISTINCT region FROM alerts WHERE Date BETWEEN '".$thestartdate ."' AND '".$theenddate ."' GROUP BY region"; } } $result2 = $db->sql_query($sql2); if (!($result2 = $db->sql_query($sql2))) { die("Database Query Failed" . mysql_error()); } $i = 1; while ( $row2 = $db->sql_fetchrow($result2) ) { $template->assign_block_vars('alerts', array( 'POS' => $i , 'REGION' => str_replace("&", " & ", $row2['region']), 'SPECIES' => str_replace("%", "'",$row2['species']), 'DATE' => $row2['Date'], 'TIME' => $row2['time'], 'COMMENTS' => str_replace("'", "%",$row2['comments']), ) ); $i++; } $template->assign_vars(array( 'USERNAME' => htmlspecialchars($userdata[username]), 'REGION_FILTER' => str_replace("&", " & ", $region_filter_options), 'SPECIES_FILTER' => $species_filter_options, ) ); $result = $db->sql_query($sql); if (!($result = $db->sql_query($sql))) { die("Database Query Failed" . mysql_error()); } // This is where you would add a new VARS Array if you intend to use your own custom VARS. while ($row = $db->sql_fetchrow($result)) { $region_filter_options .= '<option value="' . $row['region'] . '">' . $row['region'] . '</option>'; } $result = $db->sql_query($sql3); if (!($result = $db->sql_query($sql3))) { die("Database Query Failed" . mysql_error()); } // This is where you would add a new VARS Array if you intend to use your own custom VARS. while ($row = $db->sql_fetchrow($result)) { $species_filter_options .= '<option value="' . $row['species'] . '">' . $row['species'] . '</option>'; } $template->assign_vars(array( 'USERNAME' => htmlspecialchars($userdata[username]), 'REGION_FILTER' => str_replace("&", " & ", $region_filter_options), 'SPECIES_FILTER' => $species_filter_options, ) ); // Build the page $template->pparse('body'); // standard page footer include(IP_ROOT_PATH . 'includes/page_tail.'.PHP_EXT); } ?> Now my questions are these:- 1) In the .tpl file hows can i submit from any of the dropdown boxes and retain the selection after submission 2) How can i have it so that the second and third drop down boxes are only visible after the previous one, ie the first box ( date ) has to have a selection before the Region ( 2nd one ) is visible and so 3) How can i reduce the amount of code to cover all options in building a select statement or is Switch - case the best way. I would greatly appreciate help with this and even more so for some example of what i am asking for so i can learn from them. Hi good people, i'm vary new in this and i'm having trouble with PHP while writing some project for school and because i find many answers on this forum till now i decide to post this.. so here is my problem: I'm trying to make a web page for students and profesors where students (when they are loged in) will be able to sign a date for their exam so i made a form like this : Code: [Select] <form method="POST" action=""> choose exam: <p><select name="exams"> <option value="k1D">exam 1</option> <option value="k2D">exam 2</option> <option value="k3D">exam 3</option> </select></p> choose date: <p><select name="dates"> <optgroup label="Zimski rokovi"> <option value="2011-02-01">01.02.2011.</option> <option value="2011-02-07">07.02.2011.</option> <option value="2011-02-15">15.02.2011 </option> <optgroup label="Ljetni rokovi"> <option value="2011-05-21">21.05.2011.</option> <option value="2011-05-28">28.05.2011.</option> <option value="2011-06-04">04.06.2011.</option> </select></p> <input type="submit" value="Prijavi ispit" name="prijavi"> </form> table for students in mysql has columns for every exam (k1D , k2D..) but how can i make so that student can pick wich exam he wants to sign on some of dates (wich column he wants to fill with wich of dates) ? i tryed some variations of : Code: [Select] $k1D = $_POST['dates']; $kol = $_POST['exams']; mysql_query(" UPDATE studenti SET '$kol' = '$k1D' WHERE ID = '3'"); but i'm just getting different errors.. Hi,
I would like to store sql query strings in a database. A query might look this like:
SELECT * from ListTable where id = '$id'
The idea would be to retrieve the string and run it as a SQL string. $id would be defined in the procedure so the idea is that when I send the SQL String through, $id would be replaced with its value and everything would work.
Under normal circumstances, the code would look like this:
$id = "somevalue"; $lcSQL = "SELECT * from ListTable where id = '$id'";I would pass the SQL select off to mySQL and all is right with the world. I just want to store the string in a database, retreieve it and use it. Thanks for your help in advance... Please help me. I'm fairly new to php and have been looking for answers on Goog for about two weeks or so with not an answer. This is my first post on a forum of any type. I have a form on a php page that when submitted sends a value to a confirm php page Code: [Select] <form action='buyconfirmorder.php' method='post'> Purchase: <input type='text' name='ask_shares'><br /><br /> You Will Pay:  <input type='text' name='ask'><br /><br /> <input type='hidden' name='postcardname' value='$postcardname'> <input type='submit' name='submit' value='Order'> </form> I need to take the users input from the form and subtract each row from a mysql DB one at a time until the users input is down to a remainder and then I need the remainder (I'll be working with the remainder as well). Code: [Select] $query = mysql_query(" SELECT * FROM ask, search WHERE search.id = ask.card_search_id AND search.card_name = '$postcardname' ORDER BY ask_price ASC"); The array will be numbers only. So an example would be: User input from the form is 100.00 Code: [Select] while($rows = mysql_fetch_array($query)) { $ask_price = $rows['ask_price']; } Let's say the array is 50.50, 40.50, 35.00 I need some code to do: 100.00 - 50.50 = 49.50 49.50 - 40.50 = 9.00 9.00 - 35.00 = <0 does not do anything so remainder = 9.00 would it be something like Code: [Select] $new_ask_shares = $_POST['ask_shares']; //some sort of a loop or array or combo of both ($new_ask_shares - $ask_price); the numbers are just an example as the actual numbers will be different each time I query my DB. Thanks in advance Windows 7, Apache 2.2.21 / PHP 5.3.5. What does the below error mean? I am new and fighting through this particular piece of code. Thank you in advance for your help. Warning: mysql() expects parameter 3 to be resource, string given in C:\website\do_createtable.php on line 3 <? $db_name="booster"; $connection=mysql("localhost", "USERNAME", "PASSWORD") or die (mysql_error()); $db=mysql_select_db($db_name, $connection) or die (mysql_error()); $sql="CREATE TABLE $_POST[table_name] ("; for ($i=0; $i < count($_POST[field_name]); $i++) { $sql .= $_POST[field_name][$i]." ".$_POST[field_type][$i]; if ($_POST[field_length][$i] != "") { $sql .= " (".$_POST[field_length][$i]."),"; } else { $sql .= ","; } } $sql=substr($sql,0,-1); $sql .= ")"; $result=mysql_query($sql,$connection) or die (mysql_error()); if ($result) { $msg="<P>".$_POST[table_name]." has been created!</P>"; } ?> <HTML> <HEAD> <TITLE>Create a Database Table: Step 3</TITLE> </HEAD> <BODY> <h1>Adding table to <? echo "$db_name"; ?>....</h1> <? echo "$msg"; ?> </BODY> </HTML> My Php Buddies, I have mysql tbl columns these:
id: Now, I want to display their row data by excluded a few columns. Want to exclude these columns: date_&_time account_activation_code account_activation_status id_verification_video_file_url password
So, the User's (eg. your's) homepage inside his account should display labels like these where labels match the column names but the underscores are removed and each words' first chars CAPITALISED:
Id: 1
For your convenience only PART 1 works. Need help on Part 2 My attempted code:
PART 1 <?php // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Query to get columns from table $query = $conn->query("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'members' AND TABLE_NAME = 'users'"); while($row = $query->fetch_assoc()){ $result[] = $row; } // Array of all column names $columnArr = array_column($result, 'COLUMN_NAME'); foreach ($columnArr as $value) { echo "<b>$value</b>: ";?><br><?php } ?> PART 2 <?php //Display User Account Details echo "<h3>User: <a href=\"user.php?user=$user\">$user</a> Details</h3>";?><br> <?php $excluded_columns = array("date_&_time","account_activation_code","account_activation_status","id_verification_video_file_url","password"); foreach ($excluded_columns as $value2) { echo "Excluded Column: <b>$value2</b><br>"; } foreach ($columnArr as $value) { if($value != "$value2") { $label = str_replace("_"," ","$value"); $label = ucwords("$label"); //echo "<b>$label</b>: "; echo "$_SESSION[$value]";?><br><?php echo "<b>$label</b>: "; echo "${$value}";?><br><?php } } ?> PROBLEM: Columns from the excluded list still get displayed. Edited November 19, 2018 by phpsane |