I've created a php form to insert values into a database.
One of my form options is a dynamic list populated with fields from another table.
I first created the form without the dynamic option, and all data inserted just fine (and still does).
Now I'm attempting to include the code below, and while it displays the option values properly, the value fails to insert. Any advice?
<?php
/*
* LIST ALL CATEGORIES
****************************************/
include('../dbconnection.php');
$query = 'SELECT category_id, category_name FROM ingredient_categories';
$result = mysql_query($query);
echo '<select>';
while ($ingredientCategoryOption = mysql_fetch_array($result)) {
echo '<option value="'.$ingredientCategoryOption[category_id].'">'.$ingredientCategoryOption[category_name].'</option>';
}
echo '</select>';
?>
I had created something similar yesterday. The $polls array is passed to the view in CodeIgniter in the $this->load->view('poll.php', $data['polls']), while you do it in the page itself. However, you can have the general idea.
<FORM id="formPoll" class="question" name="createpoll" action="<?php echo base_url()?>index.php/poll/selectOption/" method="POST">
<select name="poll_list">
<?php
foreach($polls as $poll){
echo "<option name='poll_table'>$poll->name</option>";
}
?>
</select>
<div id="input">
Poll name: <input type="text" name="name"></input>
Title: <input type="text" name="title"></input>
</div>
<div id="options">
Option: <input type="text" name="option"></input>
</div>
<input type="submit"></input>
</FORM>
Some ideas:
Check if $results is not empty before using it
Give your <select> form a name, as I showed above
Check if $ingredientCategoryOption is not null or is something returned.
Check your database connection
Related
I have succesfully retrieved two columns from my table and displayed the result as options in a select tag, in my form.
The problem is I cannot display the data from a third column into an input field, which is also in the form, based on the selected option.
There is no issue with the database connection or retrieving the data for the options in the select tag.
Any help would be appreciated. The relevant code is below.
<div class="col-md-4 col-12 bottommargin-sm">
<label for="">Choose currency</label>
<select class="form-control" id="exampleFormControlSelect1">
<option value="">Choose currency...</option>
<?php
// Including DB connection file
include_once "config/config.php";
// Retrieving all columns from currency table
$result = mysqli_query($con, "SELECT * FROM currency_test");
// Loop printing options with country and currrency for all rows in currency table
while($row = mysqli_fetch_array($result)) {
print "<option>";
echo $row['country'] . " - " . $row['currency'];
print "</option>";
}
// Closing DB connection
mysqli_close($con);
?>
</select>
</div>
<div class="col-md-2 col-12 bottommargin-sm">
<label for="">Currency rate</label>
<input type="text" class="form-control" value="<?php echo $row['buy_rate'] ?>" readonly>
</div>
Additional Edit
I am now using the following code, still without any luck:
<div class="col-md-4 col-12 bottommargin-sm">
<label for="">Choose currency/label>
<select class="form-control" id="exampleFormControlSelect1">
<option value="default">Choose currency...</option>
<?php
// Including DB connection file
include_once "config/config.php";
// Retrieving all columns from currency table
$result = mysqli_query($con, "SELECT * FROM currency_test");
// Loop printing country, currrency, buy_rate and sell_rate for all rows in currency table
while($row = mysqli_fetch_array($result)) {
echo "<option value=".$row['currency']."> ".$row['country']. " - " .$row['currency']." </option>";
}
?>
</select>
</div>
<div class="col-md-2 col-12 bottommargin-sm">
<label for="">Currency rate</label>
<input type="text" class="form-control" value="<?php echo $row['buy_rate'] ?>" readonly>
</div>
<?php
// Closing DB connection
mysqli_close($con);
?>
As said before, you have a result SET in your while-loop above, but you want the input field only to contain a single value: the buy-rate of the selected currency. If I guessed right and this is what you want, this will not work like this.
If you want to test it and just retrieve only a single value in your while-loop, also your input field gets filled with the correct buy-rate.
You can do it with or without JavaScript, but you need a second statement to retrieve the buyrate you desire.
Further security suggestions: You should not use the include directives without __ DIR __ . Neither you should use "SELECT * ...". Better it is to name all the fields you want to retrieve.
You will have to have a statement for that selection. (Hint: Also in the tag you will have to have a value attribute set) Also your select needs a name if you use a submit button..
Now when you submit the form you can query the database and show the correct record.
If you dont want to use a submit button and have the value in the textfield change by selection, you will need javascript.
So what I see :
1) No name in select tag
<select class="form-control" id="exampleFormControlSelect1">
There is no name attribute. So after posting the form, the server doesn't know the name of the variable.
2) No value
print "<option>";
You don't supply a value. So your server doesn't know the value (the user selected) after posting the form.
This is the proper way for a select tag : https://www.w3schools.com/tags/tag_select.asp
I am practicing with developing a little bit but I stumbled upon a small issue which I just cannot get my head around. The goal is simple: users fill out a form and are then redirected to either the results page or the form. From the results page, users can navigate to a page where they can edit any records that match the time period and the name they enter.
Example: User 1 adds a car named 'Banshee', is redirected to the results page, sees the 'Banshee' car but then decides he wants the color to be different. The user navigates to the update page and is able to either type in 'Banshee' or select 'Banshee' from a dropdown list. The first option works but the latter is the solution I'm looking for.
Currently I have the following form (this is just the part that matters):
<form method="post" name="input" action="edittest.php" >
<?php
include("/var/www/html/includes/sqlconnecttest.php");
$db=mysqli_select_db($connect,$database)
or die("Could not connect to the database");
$query = "SELECT * FROM cars WHERE datetime > DATE_SUB(CURDATE(), INTERVAL 5 DAY);";
$sql = mysqli_query($connect,$query);
?>
<p>
<label>Name</label>
<select name="name" form="input" required>
<?php
echo "<option value=\"\" disabled=\"disabled\" selected=\"selected\" style=\"display\:none\"></option>";
while ($row = mysqli_fetch_array($sql)){
echo "<option value=\"name\">" . $row['name'] . "</option>";
}
?>
</select>
</p>
The connection is done through the following PHP code:
<?php
include("/var/www/html/includes/sqlconnecttest.php");
$db = new mysqli("$host","$user","$pass","$database");
$name=$_POST['name'];
$stmt = $db->prepare("UPDATE cars
SET color=?, airco=?, tires=?, rims=?, price=?, engine=?, remarks=?
WHERE name='$name' AND datetime > DATE_SUB(CURDATE(), INTERVAL 5 DAY);");
$stmt->bind_param('ssssiss', $ccolor, $cairco, $ctires, $crims, $cprice, $cengine, $cremarks);
$color=$_POST['color'];
$airco=$_POST['airco'];
$tires=$_POST['tires'];
$rims=$_POST['rims'];
$price=$_POST['price'];
$engine=$_POST['engine'];
$remarks=$_POST['remarks'];
$ccolor=htmlspecialchars($color,ENT_QUOTES);
$cairco=htmlspecialchars($airco,ENT_QUOTES);
$ctires=htmlspecialchars($tires,ENT_QUOTES);
$crims=htmlspecialchars($rims,ENT_QUOTES);
$cprice=htmlspecialchars($price,ENT_QUOTES);
$cengine=htmlspecialchars($engine,ENT_QUOTES);
$cremarks=htmlspecialchars($remarks,ENT_QUOTES);
if ($stmt->execute()) {
header("Location: redtest.php");
}
?>
The issue is as follows: when I use the above posted HTML form with the while-loop populating the options, the update page doesn't do anything. No errors, no updates it just performs the action (open edittest.php).
However, when I replace the above posted dropdown menu with this simple textfield, it works fine. Whatever I type in the textfield, it uses it in the update query.
<p>
<label>Name</label>
<input type="text" maxlength="50" name="name" required />
</p>
I've got the feeling that the PHP code breaks the connection between the select-field and the rest of the form.
I see two issues with your select. First you have what appears to be a default value that you're then hiding with display:none. You're also setting the same value for every option. I believe this is what you're trying to do.
<select name="name" form="input" required>
<option value=""></option>
<?php
while ($row = mysqli_fetch_array($sql)){
echo "<option value=\"". $row['name'] ."\">" . $row['name'] . "</option>";
}
?>
</select>
I am trying to utilize the datalist element. Everything is working with 1 little hitch. The selectable list is showing 2 columns, both the street_id and street columns. I need the street_id that will be submitted but dont want the street_id to show in the datalist.
<?php
require 'connect_mysqli.php';
$sql = "SELECT * FROM streets";
$result = mysqli_query($con, $sql) or die ("Error " . mysqli_error($con));
?>
<form action="test.php" name="test" method = "post">
<datalist id="street" name="streets">
<?php while($row = mysqli_fetch_array($result)) { ?>
<option value="<?php echo $row['street_id']; ?>"><?php echo $row['street']; ?></option>
<?php
}
?>
</datalist>
<input type="text" name="street_val" id="test" autocomplete="off" list="street">
<input type="submit" value="Submit">
</form>
<?php
mysqli_close($con);
//test the output value
echo $_POST['street_val'];//
?>
You have coded a select list - which has separate values for display and returned values. In the datalist, you only need value="" for options and then it will only return that value. Also better to keep the server code and display code separate: i.e. populate or build the array in the PHP with your query, then in the HTML only display it.
So I have searched for how to insert items from a MySQL database into a form. From what I understand, for each field, I need to add value="<?php echo htmlentities($Variable); ?>" is there a way to insert the fields all at once? Like in a PHP script? Each field already has a name identifier, that's how the insert.php insert the values into the database, like this:
//SQL Query to insert data
$sql="INSERT INTO case_info (Volunteer,CaseShortTitle,CaseNumber,HearingDate...)
VALUES ('$_POST[Volunteer]','$_POST[CaseShortTitle]','$_POST[CaseNumber]','$_POST[HearingDate]'...)
and the form fields look like this:
<div><input type="text" id="p1f5c" name="CaseShortTitle" class="fieldcontent"><div class="fielderror"></div></div>
Then the Submit button goes to this insert.php file
Is there a way to use GET to populate the fields in this manner?
Thank you!
It's generally bad practice to input data into your database directly from the $_POST variables, you should consider sanitizing them first.
If I understand what you are asking, you can do something like this;
<form action="" id="myForm" title="myForm">
<?php
$query = "SELECT * FROM case_info LIMIT 1";
$result = myqsl_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
?>
<input type="text" id="volunteer" value="<?php echo $row['Volunteer']; ?>"
<input type="text" id="CaseShortTitle" value="<?php echo $row['CaseShortTitle']; ?>"
<?php
} //Close while{} loop
?>
</form>
Can anybody help me on this. For showing the rezults from an MySql database i have to select school, class, subject, and exam. But listing all the classes or all the exams is not very practical so i want to do another function that when i choose some schools in the first select box it shows me in the second select box only the classes of the selected schools.
My code is:
<div id="allselects">
<form action="viewing.php" method="post" name="filt">
<div class="multsarrange">
<h1 class="choosetext" >Chose Schools</h1>
<select class="multipleselect" name="schools[]" size="8" multiple="multiple" id="shkll">
<?php
$sql = "SELECT * FROM schools ";
$scc=mysql_query($sql);
while ($db_f = mysql_fetch_assoc($scc)) {
$schcd=$db_f['schoolcode'];
$schc=$db_f['schoolname'];
echo "<option value=$schcd >$schc</option>";
}
?>
</select>
</div>
<div class="multsarrange" id="clasaajax">
<h1 class="choosetext" >Chose an Classes</h1>
<select class="multipleselect" name="classes[]" size="8" multiple="multiple" ">
<?php
$c = "SELECT * FROM classes ";
$cl=mysql_query($c);
while ($db_f = mysql_fetch_assoc($cl)) {
$clsc=$db_f['schoolID'];
$claid=$db_f['classID'];
$clay=$db_f['year'];
$clanm=$db_f['className'];
$name=schoolidton($clsc)." ".$clay." ".$clanm;
echo "<option value=$claid >$name</option>";
}
?>
</select>
</div>
<div class="multsarrange">
<h1 class="choosetext" >Chose Subjects</h1>
<select class="multipleselect" name="subjects[]" size="8" multiple="multiple">
<?php
$sb = "SELECT * FROM subjects ";
$sbi=mysql_query($sb);
while ($db_f = mysql_fetch_assoc($sbi)) {
$sbnm=$db_f['subjectName'];
$sbid=$db_f['subjectID'];
echo "<option value=$sbid >$sbnm</option>";
}
?>
</select>
</div>
<div class="multsarrange">
<h1 class="choosetext" >Chose Exams</h1>
<select class="multipleselect" name="exams[]" size="8" multiple="multiple">
<?php
$e = "SELECT * FROM exams ";
$ex=mysql_query($e);
while ($db_f = mysql_fetch_assoc($ex)) {
$id=$db_f['examID'];
$sub=$db_f['subjectID'];
$desc=$db_f['description'];
$year=$db_f['year'];
$data=$db_f['data'];
$exnam=subidton($sub)." - ".$year." - ".$desc." - ".$data;
echo "<option value=$id >$exnam</option>";
}
?>
</select>
</div>
<div id="longsubmit">
</br></br>
<input name="submit" type="submit" value="View" />
</div>
</form>
</div>
What you need to do is the following :
Setup an event listener on the select to listen for the change event - see here
Process the change event by sending the selected value to the PHP script - see here
Using PHP get the selected value and query the database as required (you already do that bit)
Send the associated HTML output or JSON or XML if you just creating a new select list - this is a simple echo
Write the output to the screen using JavaScript - this is either creating a new element based on the reply from the PHP function or inserting the HTML response
There are lots of things within this process - each with multiple options - i suggest you attempt to tackle each one and come back with specific questions if you get stuck
use ajax on abc.php get values or ids of school and make the tags you need and return back the results to the relevant id of html
function get_options(table,id_field,name_field,where_field,field_value,select_id,edit_id){
$('#'+select_id).html('<option>Loading...</option>');
$.ajax({
type: "POST", url: "abc.php", data: "&table="+table+"&id_field="+id_field+"&name_field="+name_field+"&where_field="+where_field+"&field_value="+field_value+ "&edit_id=" + edit_id +"&get_option=1",
complete: function(data){
//alert(data.responseText);
$('#'+select_id).html(data.responseText);
}
});
}
You have to use AJAX inorder to achieve this.
check this
http://www.plus2net.com/php_tutorial/ajax_drop_down_list.php