PHP - Assign A Default Value In A Field With A Sql Select Query With Php
I created a drop-down menu using a MySQL statement in php for a form.
My drop down menu works fine, but I want to assign a default value to it (normal text) the value will never change, thus I do not need to extract the default value from the table, I already know the value. Here is the basic snippet from the script: <?php include("../includes/xxx.php"); $cxn = mysqli_connect($host,$user,$password,$dbname); $query = "SELECT DISTINCT `plant_id` FROM `plant` ORDER BY `plant_id`"; $result = mysqli_query($cxn,$query); while($row = mysqli_fetch_assoc($result)) { extract($row); echo "<option value='$plant_id'>$plant_id</option>\n"; } ?> Similar TutorialsOk, i can't understand whats wrong with the DATE field in MySQL and PHP. I have a form in PHP witch has 3 birth day dropdown menus that looks like this (YYYY-MM-DD). An in my database i have a birth_day colum with DATE as type and i've tried to set the default value to "None" and "0000-00-00" but nothing works. Everytime i try to input something (e.g. 1993-16-05) i get this error: Incorrect date value: '05' for column 'birth_day' at row 1 I've tried to set the value for the "Day" dropdown in the PHP form to both 5 and 05 but still nothing, what am i doing wrong? I have a few dropdown forums and would like it to select the current values that are requested. Code: [Select] global $filename,$fileid,$filetype,$filedir,$fileby; global $months,$pg; echo "<h2>Search Files</h2>"; echo "<p>"; echo "<form name = 'File_Search' action = '#' method = 'POST'>"; echo "<table border=\"0\" width=\"100%\"><tr>"; echo "<td>File Name<br><input type = 'text' name = 'name'></td><td>File Type<br><select name = 'type'> <option value = '0'>All Types</option> <option value = 'o'>Official Files</option> <option value = '1'>Quests</option> <option value = '2'>Graphic/Spritesheets</option> <option value = '3'>Entity/Scripts</option> <option value = '4'>Sound/Music</option> <option value = '5'>QuestPack/Programs</option> <option value = '6'>Miscellaneous</option> </select></td>"; echo "<td>Order By<br><select name = 'order'> <option value = '0'>Last Updated</option> <option value = '1'>ID</option> <option value = '2'>Name</option> <option value = '3'>Downloads</option> <option value = '4'>Rating</option> <option value = '5'>Points</option> <option value = '6'>Random</option> </select></td>"; echo "<td>Acending?<br><select name = 'dir'><option value = '0'>False</option><option selected value = '1'>True</option></select></td>"; echo "</tr><tr><td rowspan = '4'><input type = 'submit' name = 'search' value = 'search'></td></tr></table></form>"; echo "</p>"; So if the $filetype equals 2 I want the dropdown box to show "Graphic/Spritesheets" by default. BTW Official Files is not actually a type so that's why I chose to give it a small letter o and will work the same way as All Types but run a different function. $fileby is used for the OrderBy field. $filedir is for the Acending field. The other data is for the other parts of the script. If you like you can give advice on the name's default because you may have a better method then what I have in my head. Hey guys. Me again... Essentially what i am doing is pulling data from a MySQL database about the number of thumbnails on a page. The user can then change this using a <select> dropdown menu. How ever, i want the <select> to default to the amount already specified by the Database. I know i can do this by inserting a Selected attribute to one of the <options> but what is the best way of doing this? Heres my code.. $NumberOfThumbnails = mysql_result($data, 0,"NumberOfThumbnails"); <select name="numberofthumbnails"> <option value="0">None</option> <option value="2">2</option> <option value="4">4</option> <option value="6">6</option> <option value="8">8</option> <option value="10">10</option> <option value="12">12</option> <option value="14">14</option> <option value="16">16</option> <option value="18">18</option> <option value="20">20</option> <option value="22">22</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> </select> Thanks - Danny Originally, I would get both, and unfortunately would inconsistently use both. Then, I wanted more consistently, so configured php.ini to only return objects as I felt accessing them was more concise. And then later, I found myself needing arrays more often, and initially would just typecast them to arrays but eventually my standard was to set the PDO's fetch style to an array. And now I find myself almost always explicitly requesting arrays and occasionally requesting columns or named values. Do you configure ATTR_DEFAULT_FETCH_MODE, and if so to what? PS. Anyone use FETCH_CLASS, FETCH_INTO or FETCH_NUM? If so, what would be a good use case? Hello all,
Based on the suggestion of you wonderful folks here, I went away for a few days (to learn about PDO and Prepared Statements) in order to replace the MySQLi commands in my code. That's gone pretty well thus far...with me having learnt and successfully replaced most of my "bad" code with elegant, SQL-Injection-proof code (or so I hope).
The one-and-only problem I'm having (for now at least) is that I'm having trouble understanding how to execute an UPDATE query within the resultset of a SELECT query (using PDO and prepared statements, of course).
Let me explain (my scenario), and since a picture speaks a thousand words I've also inlcuded a screenshot to show you guys my setup:
In my table I have two columns (which are essentially flags i.e. Y/N), one for "items alreay purchased" and the other for "items to be purchased later". The first flag, if/when set ON (Y) will highlight row(s) in red...and the second flag will highlight row(s) in blue (when set ON).
I initially had four buttons, two each for setting the flags/columns to "Y", and another two to reverse the columns/flags to "N". That was when I had my delete functionality as a separate operation on a separate tab/list item, and that was fine.
Now that I've realized I can include both operations (update and delete) on just the one tab, I've also figured it would be better to pare down those four buttons (into just two), and set them up as a toggle feature i.e. if the value is currently "Y" then the button will set it to "N", and vice versa.
So, looking at my attached picture, if a person selects (using the checkboxes) the first four rows and clicks the first button (labeled "Toggle selected items as Purchased/Not Purchased") then the following must happen:
1. The purchased_flag for rows # 2 and 4 must be switched OFF (set to N)...so they will no longer be highlighted in red.
2. The purchased_flag for row # 3 must be switched ON (set to Y)...so that row will now be highlighted in red.
3. Nothing must be done to rows # 1 and 5 since: a) row 5 was not selected/checked to begin with, and b) row # 1 has its purchase_later_flag set ON (to Y), so it must be skipped over.
Looking at my code below, I'm guessing (and here's where I need the help) that there's something wrong in the code within the section that says "/*** loop through the results/collection of checked items ***/". I've probably made it more complex than it should be, and that's due to the fact that I have no idea what I'm doing (or rather, how I should be doing it), and this has driven me insane for the last 2 days...which prompted me to "throw in the towel" and seek the help of you very helpful and intellegent folks. BTW, I am a newbie at this, so if I could be provided the exact code, that would be most wonderful, and much highly appreciated.
Thanks to you folks, I'm feeling real good (with a great sense of achievement) after having come here and got the great advice to learn PDO and prepared statements.
Just this one nasty little hurdle is stopping me from getting to "end-of-job" on my very first WebApp. BTW, sorry about the long post...this is the best/only way I could clearly explaing my situation.
Cheers guys!
case "update-delete": if(isset($_POST['highlight-purchased'])) { // ****** Setup customized query to obtain only items that are checked ****** $sql = "SELECT * FROM shoplist WHERE"; for($i=0; $i < count($_POST['checkboxes']); $i++) { $sql=$sql . " idnumber=" . $_POST['checkboxes'][$i] . " or"; } $sql= rtrim($sql, "or"); $statement = $conn->prepare($sql); $statement->execute(); // *** fetch results for all checked items (1st query) *** // $result = $statement->fetchAll(); $statement->closeCursor(); // Setup query that will change the purchased flag to "N", if it's currently set to "Y" $sqlSetToN = "UPDATE shoplist SET purchased = 'N' WHERE purchased = 'Y'"; // Setup query that will change the purchased flag to "Y", if it's currently set to "N", "", or NULL $sqlSetToY = "UPDATE shoplist SET purchased = 'Y' WHERE purchased = 'N' OR purchased = '' OR purchased IS NULL"; $statementSetToN = $conn->prepare($sqlSetToN); $statementSetToY = $conn->prepare($sqlSetToY); /*** loop through the results/collection of checked items ***/ foreach($result as $row) { if ($row["purchased"] != "Y") { // *** fetch one row at a time pertaining to the 2nd query *** // $resultSetToY = $statementSetToY->fetch(); foreach($resultSetToY as $row) { $statementSetToY->execute(); } } else { // *** fetch one row at a time pertaining to the 2nd query *** // $resultSetToN = $statementSetToN->fetch(); foreach($resultSetToN as $row) { $statementSetToN->execute(); } } } break; }CRUD Queston.png 20.68KB 0 downloads How should it look if I want to make a query where a field value should be lower than another field? Code: [Select] ....WHERE total_points<max_points"); Hi, I need to call to this text to add a all with value "blank/empty" or "0" to the dropdownlist code below.. it should be inserted int the first position in the dropdownlist and have a value blank and call to this text from the language files: $searchAll = gettext('_LANGUAGE_SEARCH_ALL',_LANGUAGE_SEARCH_ALL,false,false); example is: ratestitle=>0 gettext('_LANGUAGE_SEARCH_ALL',_LANGUAGE_SEARCH_ALL,false,false); the words it calls is "ALL" when the user selects or leaves the "ALL" in the list the value remains empty this allows the search to search everything.. basically im stuck how to get it in the dropdown list as the first default position: can anyone help? here is my code://this is a search function which calls to the field rate_title the text from the select box is matched to the database table and the search pages shows the search option is the search is successful.. I have 5 of these types of searches but cant give a broader search option to my users as the values must be selected to search--- i need the option "ALL" to have a "EMPTY" value or no value.... if (in_array("ratestitle",$searchOptions)&& $showSearchOptions ) { if (empty($sch->filter['ratestitle']) ) $selectOption=$output['LANGUAGE_SEARCH_RATESTITLE']; else $selectOption=$sch->filter['ratestitle']; $showButton=true; $query = "SELECT DISTINCT rate_title FROM #__rates_table ORDER BY rate_title ASC"; $dropDownList ="<select class=\"inputbox\" name=\"ratestitle\">"; $ratesitles =doSelectSql($query); foreach ($ratesitles as $ratetitle) { $selected=""; $rate_title=$ratetitle->rate_title; if ($ratetitle==".$sch->filter['ratestitle'].") $selected="selected"; $dropDownList .= "<option ".$selected." value=\"".$rate_title."\">".$rate_title."</option>"; } $dropDownList.="</select>"; $output['RATESTITLE']=$dropDownList; } Hello. I am trying to display only one instance of records that have the same memberid in my db. I am using the following statement but it continues to show all of the records that have the same memberid. Any ideas what I may be doing wrong? Code: [Select] $sql = "select DISTINCT memberid, event, category, date, enddate, locality, location, address, city, state, zip, contact, phone, notes, doc1, doc2, doc3, doc4, doc5 from event where date >= '$datenow' ORDER by date ASC"; Thanks for any help! Hi. I have two select fields one called category and the other sub category. Both are in the format. <select name="category" value=" <?php $qGetCat = "SELECT * FROM club_category" ; $rGetCat = mysql_query($qGetCat); while ($Cat = mysql_fetch_assoc($rGetCat)) { ?>" /> <option value="<?php echo $Cat['categorys'];?>"><?php echo $Cat['categorys']; ?></option> <?php } ?> </select> <select name="sub_category" value=" <?php $qGetSubCat = "SELECT * FROM sub_categorys" ; $rGetSubCat = mysql_query($qGetSubCat); while ($SubCat = mysql_fetch_assoc($rGetSubCat)) { ?>" /> <option value="<?php echo $SubCat['sub_categorys'];?>"><?php echo $SubCat['sub_categorys']; ?></option> <?php } ?> </select> Now I want to make it so that when a particular category is chosen for example self defence. The sub category when clicked shows all the self defence stuff. If watersports was chosen sub category would show things like swimming. What do I need to look up to do this? At the minute there is no link the way I have coded these to fields. In the database its self there is a; category table with categoryID and category_name sub category table with sub_cat_name and categoryID I think this will work but I have never done this so its making my head hurt just thinking about it. Does anyone have any advice, tuts or scripts to do this? Thank you I want to select the user from super_administrators, administrators, teachers and students, and give the user permission based from what table he "came". But is giving the "Query failed" error... Code: [Select] <?php //Start session session_start(); //Include database connection details require_once('../config/config.php'); //Array to store validation errors $errmsg_arr = array(); //Validation error flag $errflag = false; //Connect to mysql server $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } //Select database $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } //Function to sanitize values received from the form. Prevents SQL injection function clean($str) { $str = @trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } return mysql_real_escape_string($str); } //Sanitize the POST values $email = clean($_POST['email']); $password = clean($_POST['password']); //Input Validations if($email == '') { $errmsg_arr[] = 'O campo Email nao foi preenchido.'; $errflag = true; } if($password == '') { $errmsg_arr[] = 'O campo Senha nao foi preenchido.'; $errflag = true; } //If there are input validations, redirect back to the login form if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); header("location: ../index.php"); exit(); } //Create query $qry = "SELECT * FROM super_administrators,administrators,teachers,students WHERE email = '$email' AND passwd = '".md5($_POST['password'])."'"; $result = mysql_query($qry); $member = mysql_fetch_assoc($result); $table = mysql_field_table('$result', '0'); //Check whether the query was successful or not if($result) { if(mysql_num_rows($result) == 1) { if($table == 'super_administrators') { session_regenerate_id(); $_SESSION['SESS_ID'] = $member['id']; $_SESSION['SESS_NAME'] = $member['name']; $_SESSION['SESS_EMAIL'] = $member['email']; session_write_close(); header("location: ../users/sadmin/index.php"); exit(); } if($table == 'administrators') { session_regenerate_id(); $_SESSION['SESS_ID'] = $member['id']; $_SESSION['SESS_SCHOOL_ID'] = $member['school_id']; $_SESSION['SESS_NAME'] = $member['name']; $_SESSION['SESS_EMAIL'] = $member['email']; session_write_close(); header("location: ../users/admin/index.php"); exit(); } if($table == 'teachers') { session_regenerate_id(); $_SESSION['SESS_ID'] = $member['id']; $_SESSION['SESS_SCHOOL_ID'] = $member['school_id']; $_SESSION['SESS_NAME'] = $member['name']; $_SESSION['SESS_EMAIL'] = $member['email']; session_write_close(); header("location: ../users/prof/index.php"); exit(); } if($table == 'students') { session_regenerate_id(); $_SESSION['SESS_ID'] = $member['id']; $_SESSION['SESS_SCHOOL_ID'] = $member['school_id']; $_SESSION['SESS_CLASS_ID'] = $member['class_id']; $_SESSION['SESS_NAME'] = $member['name']; $_SESSION['SESS_REGISTRATION'] = $member['registration']; $_SESSION['SESS_EMAIL'] = $member['email']; session_write_close(); header("location: ../users/aluno/index.php"); exit(); } } else { $errmsg_arr[] = 'Suas informacoes de login estao incorreta. Por favor, tente novamente.'; $errflag = true; $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); header("location: ../index.php"); exit(); } } else { die("Query failed"); } ?> Can anybody clarify the usefulness of "AS" and elaborate on how it operates. If I select a 'bananas' AS 'yeelow fruit' will it change the TITLE in the table? Or the table that is being viewed? If I dump a list of 'FRUITS' into and HTML table, will using AS rename each column for me, or is that handled by MY coing of the HTML table? Hi Guys, Can someone please help me before I kill myself! I have a table holding details of images to be displayed in a gallery. The table has columns as 'id', 'image_caption', 'file_path', and 'userid'. The 'id' column is the unique key, and the 'userid' column is obviously id of the user who uploaded the image. What I would like to do is select and display one image from each unique userid and then display each image along with the details in my gallery. It doesn't really matter which users image is selected aslong as there is only one for each unique user. I have been trying a number of ways to do this (DISTINCT / subqueries) but I just cant get anything to work. Could someone please advise me on how I could get this to work. Cheers in advance. Hello, i am trying to get my form to list usernames ascending as an option, but the select field just returns blank. Here is my code: Code: [Select] /** * editUserForm - Displays the users database table in * a nicely formatted field table. */ function editUserForm(){ $q = "SELECT * " ."FROM ".TBL_USERS." ORDER BY username ASC"; $result = $database->query($q); while ($row = mysql_fetch_assoc($result)) { echo '<option value="'.$row["username"].'">'.$row["username"].'</option>'; } } Code: [Select] <form action="/" method="post"> <div class="column"> <p> <select name="user" id="user" placeholder="Select A User To Edit" class="{validate:{required:true}}"> <option>Select A User To Edit</option> <? editUserForm(); ?> </select> </p> <div class="action_bar"> <input type="submit" class="button blue" value="Submit Post" /> <a href="#modal" class="modal button">Cancel</a> </div> </form> All help is appreciated
Hi guys, <form id='contact-form".$KitchConfigID."' name='contact-form".$KitchConfigID."' action='_pages/_kitchenconfig/adm_saveKitchConfig.php?Nav=".$NavHash."&kcid=".$KitchConfigID."' method='POST'> <div class='row'> <div class='col-sm-12'> <div class='md-form mb-0 form-sm'> <input value='".$KitchConfig."' type='text' id='configname".$KitchConfigID."' name='configname".$KitchConfigID ."' class='form-control'> <label for='configname".$KitchConfigID ."' class=''>Config Name:</label> </div> </div> </div> <div class='row'> <div class='col-sm-12'> <div class='md-form mb-0 form-sm'> <select id='designer_".$KitchConfigID."' name='designer_".$KitchConfigID."' class='mdb-select md-form' searchable='Search here..' onchange='changeInput(this.value, ".$SelField.");'>"); $designersql = "SELECT * FROM `tbl_contacts` ORDER BY `FirstName`"; $resultdesigner = $conn->query($designersql); if ($resultdesigner->num_rows > 0) { $resultdesigner->MoveFirst; echo("<option value='designer_".$KitchConfigID."'></option>"); while($rowdesigner = $resultdesigner->fetch_assoc()) { $DesignerName = $rowdesigner["FirstName"]." ".$rowdesigner["LastName"]; $DesignerID = $rowdesigner["ContactID"]; if($rowdesigner["ContactID"]==$rowkitch["Designer"]){ echo("<option value='".$DesignerID."' selected='selected'>".$DesignerName."</option>"); } else { echo("<option value='".$DesignerID."'>".$DesignerName."</option>"); } } } echo("</select> <input type='text' name='".$SelField."' value='' /> <label for='designer_".$KitchConfigID."' class=''>Designer:</label> </div> </div> </div> <div class='md-form mb-0 float-right'> <button type='submit' class='btn btn-outline-danger waves-effect btn-sm float-right'>Save <i class='fas fa-magic ml-1'></i></button> </div>
$upd_KitchConfigID = $_GET["kcid"]; if(isset($_POST["configname$upd_KitchConfigID"])) { $upd_KitchConfig = $_POST["configname$upd_KitchConfigID"]; } else { $upd_KitchConfig = 'NotSet'; $ErrMsg = $ErrMsg . 'No KitchConfig, '; } if(isset($_POST["designer$upd_KitchConfigID"])) { $upd_KitchConfigDesigner = $_POST["designer_$upd_KitchConfigID"]; } else { $upd_KitchConfigDesigner = 1; $ErrMsg = $ErrMsg . 'No Designer, '; } echo("designer_$upd_KitchConfigID: ".$_POST["designer_$upd_KitchConfigID"]."<br><br>");
I want to make a table for each paddler_id (Field) which exists into pushup Database My code for paddler_id = 1 is require "../sql.php"; $result = mysql_query("EXPLAIN pushup"); $r = mysql_query("SELECT * FROM paddlerinfo t1 LEFT JOIN pushup t2 on t2.paddler_id=t1.id LEFT JOIN practicedate t3 on t3.practice=t2.practice_id ORDER BY t1.firstname ASC "); $r1 = mysql_query("SELECT * FROM pushup where paddler_id =1 ORDER BY practice_id ASC "); echo "<table width='30%' border='1' cellpadding='0' cellspacing='0' style='font-family: monospace'>"; echo "<tr>"; echo "<td>DATE</td>"; while ($row = mysql_fetch_array($result)) { if (in_array($row["Field"], array("paddler_id", "practice_id", "p_id"))) continue; echo "<td>",($row["Field"]), "</td>"; } echo "</tr>"; while (($data = mysql_fetch_array($r1, MYSQL_ASSOC)) !== FALSE) { unset($data["p_id"],$data["paddler_id"]); echo "<tr>"; foreach ($data as $k => $v) { echo "<td>"; echo"$v"; echo "</td>"; } echo "</tr>"; } echo "</table>"; mysql_free_result($result); mysql_free_result($r); mysql_free_result($r1); mysql_close(); The problem is on line $r1 = mysql_query("SELECT * FROM pushup where paddler_id =1 ORDER BY practice_id ASC "); I want to put something which makes it paddler_id = X where x = 2,3,4,5... and x exists in database and do not print twice the x (because that database may have rows where x = same id How do i do that?? hello in the attached code, how do i add another field to the query? ie, i have all the code to create the result and would like to add further values such as $dept? what is the correct way to code query? i must stress that i am using php 4.4.7 so json_encode is out. the code is working but just need to find a way to add the $dept to the qeury? many thanks $dept = array(); $box = array(); while ($row = mysql_fetch_array($result)) { $dept[] = $row['department']; $box[] = $row['custref']; } /*$items = rtrim($_POST['items'],","); $sql = "UPDATE `boxes` SET status = 'Out' WHERE Id IN ($items)"; $result = runSQL($sql);*/ $total = count(explode(",",$items)); $result = runSQL($sql); $total = mysql_affected_rows(); /// Line 18/19 commented for demo purposes. The MySQL query is not executed in this case. When line 18 and 19 are uncommented, the MySQL query will be executed. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" ); header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" ); header("Cache-Control: no-cache, must-revalidate" ); header("Pragma: no-cache" ); header("Content-type: text/x-json"); $json = ""; $json .= "{\n"; $json .= "box: [\"". implode('","', $box) ."\"]\n"; $json .= "}\n"; echo $json; $sql = "INSERT INTO `act` (`item`) VALUES ('". implode("'),('", $box) . "')"; $result = runSQL($sql); Hi, I am new to the boards and php and mysql. I have created a database and can add entries via a form. I can query the database with another form and get the results to display in a table. All good so far as that is what I was hoping to achieve but one of the fields I want to display as a hyperlink but I am having problems with the syntax as I keep getting errors when I try to wrap the variables in <a href > tag. Code: [Select] <tr> <td><?php echo $fquery['prefix']; echo $fquery['website']; ?><?php echo $fquery['website']; ?></td> </tr> now that displays e.g. http://www.example.comwww.example.com. so I feel I am nearly there I just need advice as to how to construct a hyperlink from the fields queried. ok, this is clearly 1st grade code for some, but i'm not there yet - I'm querying posts in WordPress, and the post_content will always have an image in the beginning of the post followed by the content. i don't want to get the image, just the content that's after the image, which is wrapped in anchor tags, of course. Code: [Select] <a href="http://path/to/image.jpg"><img src="http://path/to/image.jpg" /></a> <p>Post content yadda, yadda, hoowie</p> obviously a character count won't work, so i need to get anything that follows the first "</a>", say...? is this the best way, or is there an easier way? thanks for anyone's help. GN Hi there. I'm totally new (about a week!) with php and mysql and am encountering a problem that perhaps someone can help me with?
I've looked through to see if a similar problem has appeared or been solved, but without success, so apologies if I am repeating something.
In php I am trying to update 7 fields from a form from which a user has edited/modified any of the fields in a chosen record (except id).
Here is the code:
$id=$_GET['id']; |