So, im creating a form that will submit data into an SQL database. Ive got 2 select drop downs that hold the data of "Module Code" and "Module Title". In the database a module title will only have one module code e.g Team project(module title) has module code 11COB290.
How can i get it so that when a user selects a given module name OR Module title is will automatically select the correct partner i.e select the right module code thats related to the module name the user has selected without pressing any submit buttons?
The following code is the drop down select boxes and php code i have so far:
<td align="center">
<select name='ModuleTitle' id='ModuleTitle' style='width:100%;'>
<option>Select...</option>
<?php
//3. Perform database query
$result = mysql_query("SELECT * FROM Module
ORDER BY `ModTitle` ASC;", $connection);
if(!$result){
die("Database query failed: " . mysql_error());
}
//4. Use Returned Data
while ($row = mysql_fetch_array($result)) {
$module = $row[2];
echo "<option name='{$module}'>{$module}</option><br />";
}
?>
</select>
</td>
<td align="center">
<select name='ModuleCode' id='ModuleCode' style='width:100%;'>
<option>Select...</option>
<?php
//3. Perform database query
$result = mysql_query("SELECT * FROM Module
ORDER BY `ModCode` ASC;", $connection);
if(!$result){
die("Database query failed: " . mysql_error());
}
//4. Use Returned Data
while ($row = mysql_fetch_array($result)) {
$module = $row[3];
echo "<option name='{$module}'>{$module}</option><br />";
}
?>
</select>
</td>
Unless there is a special reason to do so, why not give a single SELECT box instead of two?
<td align="center">
<select name='ModuleTitle' id='ModuleTitle' style='width:100%;'>
<option>Select...</option>
<?php
//3. Perform database query
$result = mysql_query("SELECT * FROM Module ORDER BY `ModTitle` ASC;", $connection);
if(!$result){
die("Database query failed: " . mysql_error());
}
//4. Use Returned Data
while ($row = mysql_fetch_array($result)) {
$module = $row[2] . ' (' . $row[3] . ')';
$moduleCode = $row[3];
echo "<option value='{$moduleCode}'>{$module}</option>";
}
?>
</select>
</td>
Or otherwise if you would like to keep 2 SELECTs, use AJAX calls. The idea is to define onChange event on each SELECT and in that event, send an AJAX request to a PHP script. The PHP script will request the module code or title and send it back to the AJAX handler. The AJAX handler can then automatically mark as SELECTED the corresponding option in the other SELECT. You might need sometime to research on AJAX and JavaScript if you aren't already experienced with this stuff.
Another idea might be to use the module code as the value for the title SELECT and module title as the value for the code SELECT. For example, title SELECT will be:
<SELECT name="ModuleTitle" id="ModuleTitle" style="width:100%;">
<OPTION>Select...</option>
<OPTION value="123">Title 123</OPTION>
<OPTION value="345">Title 345</OPTION>
<OPTION value="567">Title 567</OPTION>
</SELECT>
Then in the onChange event handler you might do something like this:
var selObj = document.getElementById('ModuleTitle');
var selIndex = selObj.selectedIndex;
document.getElementById('ModuleCode').value = selObj.option[selIndex].text;
By the way, there is no "name" attribute for . It should be "value" instead. Please fix in your code.
Hope it helps!
CAUTION: none of the above code is tested but I hope it works fine
Related
Okay, I'm reframing this whole question because the earlier version was a bit convoluted.
Here's the scenario:
I have a MySQL table called "churches."
I have a form with four selects. The options are drawn dynamically from the table, so that users can search on four table columns to find churches that fit the criteria (country, state/province, city, presbytery)
I also have working code to get all the table data to display.
What I haven't figured out is how to use the selected option from the form to filter the results.
My current code is below:
<form action="display0506b.php" method="post">
<select name="country">
<option value=""></option>
<?php
$query = mysqli_query($link, "SELECT DISTINCT country FROM churches");
$query_display = mysqli_query($link,"SELECT * FROM churches");
while ($row = mysqli_fetch_array($query)){
echo "<option value='" . $row['id']."'>". $row['country'] . "</option>";
}
?>
</select>
<select name="state">
<option value=""></option>
<?php
$query = mysqli_query($link, "SELECT DISTINCT state FROM churches WHERE state != ''");
$query_display = mysqli_query($link,"SELECT * FROM churches WHERE state != ''");
while ($row = mysqli_fetch_array($query)){
echo "<option value='" . $row['id']."'>". $row['state'] . "</option>";
}
?>
</select>
<input type="submit" value="Go!">
</form>
<?php
if(isset($_POST['country']))
{
$name = $_POST['country'];
$fetch = "SELECT * FROM churches WHERE id = '".$name."'";
$result = mysqli_query($link,$fetch);
echo '<div class="churchdisplay">
<h4>' .$row['churchname'].'</h4>
<p class="detail">' .$row['detail'].'</p>
<p><b>' .$row['city'].'</b>, ' .$row['state'].' ' .$row['country'].'</p>
<p>' .$row['phone'].'</p>
// etc etc
</div>';
}
else{
echo "<p>Please enter a search query</p>";
}
?>
Note that in the form above, I only have two selects for illustration, but ultimately I will have four, as mentioned; and I am only attempting the country selection at this point to keep things simple. Ultimately, I will need the ability to select any (and preferably all) of the four categories.
As you can see, this code does attempt to "grab" the selected value from the form, but it's not working. I've pondered numerous tutorials and examples, but none of them do exactly what I'm after, and as an extreme PHP novice, I'm stumped.
So the question: how do I tweak this so that I can "grab" the form selection and display the relevant results from my table?
Edit: I am using mysqli syntax, and want to just use PHP and MYSQL (no Ajax etc) if possible.
Well, it looks like I've finally found what I needed here:
display result from dropdown menu only when value from it is selected
Or, I should say, I've got it to work with one select option. Still need to see if I can figure out how to get four working together.
I'm having some issues with passing information from a form to a PHP script which then requests data from MySQL.
I get get data to return as long as I hard code the request; however, I'm trying to do it so when a user selects an option from the drop-down list to have it the runs the selected query. This is what I have in my form.
<form action="FETCH.PHP" method="POST" enctype="multipart/form-data">
<select name="mySelect">
<option value="South Yorkshire">South Yorkshire</option>
<option value="West Midlands">West Midlands</option>
</select>
<input type="submit" value="Go">
</form>
and this is what I have in my PHP script:
<?php
$con=mysqli_connect("*******","*******","*******","*******");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$selectedOption = $_POST["mySelect"];
$result = mysqli_query($con,"SELECT * FROM `SouthYorkshire` WHERE `EstProv` ='$_POST'");
echo "<div id=Results>";
while($row = mysqli_fetch_array($result))
{
echo "<div class=ClubName>";
echo $row['EstName'];
echo "<div class=Location>";
echo $row['EstAddress2'];
echo "<br>";
}
echo date("Y") . " " ."Search is Powered by PHP.";
mysqli_close($con);
?>
I know there's something wrong here but I don't know what. This is the first time I have attempted anything with MySQL and PHP.
The current script does not give any errors but doesn't bring back any results. Any ideas?
Here in lies the problem:
$result = mysqli_query($con,
"SELECT * FROM `SouthYorkshire` WHERE `EstProv` ='$_POST'");
Change that line to:
$result = mysqli_query($con,
"SELECT * FROM `SouthYorkshire` WHERE `EstProv` ='$selectedOption'");
Update
You should bind params to secure your script like this:
$result = mysqli_query($con,
sprintf("SELECT * FROM `SouthYorkshire` WHERE `EstProv` = '%s'",
preg_replace("/[^A-Za-z ]/", '', $selectedOption))); // pattern based on your html select options
OR...
Do it the Object Orientated way: http://php.net/manual/en/mysqli.prepare.php
WHERE `EstProv` ='$selectedOption'
In your SQL, you put the whole $_POST in, and for displaying the results, there is no close div tag.
I want to show options from my database for users to check, but having trouble getting user's choice.
So, I write two php files,
the first one doing things like: getting data from database, displaying in select option, then submit value by post to and the second php file.
And the second php file just display the recieved value.
Here's the first php file:
<html>
<body>
<form method="post" action="second.php">
<Select name=”select_value”>
<?
//connect to server
$con = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE) or die("Error " . mysqli_error($con));
$query = "SELECT * FROM MYTABLE" or die("Error in the consult.." . mysqli_error($con));
$result = $con->query($query);
//display result in select option
while ($row = mysqli_fetch_array($result)) {
echo "<Option value=".$row['ENTRY_ID']."> ".$row['ENTRY_NAME']."</Option><br>";
}
mysqli_close($con);
?>
</Select>
</form>
</body>
</html>
And the second php file:
<?
$option = isset($_POST['select_value']) ? $_POST['select_value'] : false;
if($option) {
echo $_POST['select_value'];
} else {
echo "not getting value of select option";
exit;
}
?>
If this works fine, I should see the selected value by the second php file, but I keep recieving my echo "not getting value of select option".
There must be something wrong between select option and my recieving file.
Can someone help?
try this double quotes
<Select name="select_value">
instead of <Select name=”select_value”>
I've been at this for hours and i have gotten a slight break through, however i am at a stand still at the moment. I have a SQL Database that store vehicle information, such as make, model and year. What i want to do is allow users to modify the query and only display specific results.
I understand how to display all the records at once but what i want to add is when the user selects say for example the make as "Toyota" i want only that specific make to appear. I did reach some where in this, by using this code:
<form method="post" action="">
<div id="search_query" >
Make
<select name="make" size="0">
<option value="honda">Honda</option>
<option value="toyota">Toyota</option>
<option value="nissan">Nissan</option>
</select>
<input type="submit" name="submit" value="submit">
</div>
</form>
<?php
$db_con = mysql_connect('localhost', 'root', '');
if (!$db_con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('my_db', $db_con);
$make = mysql_real_escape_string($_POST['make']);
$sql = sprintf("SELECT * FROM chjadb_vehicles WHERE v_make= '$make' ");
$result = mysql_query($sql);
echo "<table width= 970 border=1>
<tr>
<th width='120' scope='col'>Image</th>
<th width='170' scope='col'>Details</th>
<th width='185' scope='col'>Seller</th>
<th width='126' scope='col'>Price</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td> <img src=" .$row['v_image']. " width =200 height = 130>" . "</td>";
echo "<td>". $row['v_year'] . " " . $row['v_make'] . " ". $row['v_model'] . " ". $row['b_type']. "</td>";
echo "<td>". $row['user_id'] ."</td>";
echo "<td>". $row['v_price'] ."</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($db_con);
?>
however when i run the page initially i get this error: "Notice: Undefined index: make in C:\xampp\htdocs\carhuntja.com\buy_a_car.php on line 62"
i did some research and realized that this was happening because i had no make value set, what i wish to do here is at the start of going to that page i want all vehicles to be displayed.
The problem is that the query is being sent before the user chooses a make. To fix this, you need check that the user has actually submitted the form by enveloping your PHP code in if(isset($_POST['submit'])) ("submit" is used because that is the name of your submit button).
//place connection code here (do not query the database yet)
if(isset($_POST['submit']))
{
//all of the database retrieval code
}
else
{
$query_makes = "SELECT v_make FROM chjadb_vehicles";
$result_makes = mysqli_query($query_makes);
echo "Please choose a make."
//echo opening select tag
while($row = mysql_fetch_array($result_makes))
{
//echo each option tag
}
//echo ending select tag
}
Also, you are missing a slash in the self-contained input tag.
Finally, you should use MySQLi functions because MySQL functions are deprecated in PHP.
When the page loads for the first time you need to run this query:
SELECT * FROM chjadb_vehicles
You need to check if the user clicked the submit button and posted the make field, to do that use isset():
if (isset($_POST['make']){
$make = mysql_real_escape_string($_POST['make']);
}
I strongly suggest you use jquery and ajax
EDIT:
First time the page loads you display all vehicles.
In your javascript you bind a onSelect evvent to the dropdown and once the user selects a make, you send an ajax request to the server and display the new results from the server, so it'll look something like that:
$('#search_query select').change(function(){
//get the selected option text
var selectedVal = $(this).find('option:selected').text();
//send ajax request
$.ajax( {
url : url,
type : "POST",
data : selectedVal ,
dataType : 'json',
success : function(data) {//handle returned data}
})
});
I suggest you take a look here, for a complete VIDEO tutorial on jquery.
I've got a drop down select box that grabs each relevant value from an SQL database in a loop.
I'm creating a form so that when the "Submit" button is pressed it redirects to a PHP file that carries out the INSERT SQL statement. However because the select options are coming from a loop I'm unsure of how to grab the right value when its selected as it just grabs the last value gained from the loop.
I'm pretty sure that the way I have done it is the wrong way to go
<?php
echo"<select name='ModuleTitle' id='ModuleTitle' style='width:100%;'>";
echo"<option>Select...</option>";
//3. Perform database query
$result = mysql_query("SELECT * FROM Module
ORDER BY `ModTitle` ASC;", $connection);
if(!$result){
die("Database query failed: " . mysql_error());
}
//4. Use Returned Data
while ($row5 = mysql_fetch_array($result)) {
$module = $row5[2];
echo "<option name='{$module}'>".$row5[2]."</option><br />";
}
echo"</select>";
echo "<a href='submitREQ.php?id={$module}'><img src='images/submit.jpg' height='27'></a>";
?>
Instead of using <a href you should use <input type="image" value="submit" src="images/submit.jpg" />
To grab the value after the form is submitted you should use: $ModuleTitle = $_POST['ModuleTitle']; or $_GET if the method is get.