I am currently using PHP 5 with a MysSQL database with 2 tables. So far my PHP Combo Box is working however I need to access the values selected from the combo box. it goes like this:
1) I select a value from the Combo Box.
2) I click on the Submit button
3) The Submit button brings me to another webpage.
The problem that my program is facing now is during step 3 when I click the submit button there is no webpage generated. I think the problem is due to the sequencing of the Combo Box Codes and Button Codes.
My codes are as shown:
<?php
include "db_connect.php";
{
?>
<td valign=top><strong>Name:</strong></td>
<td>
<?php
echo '<select name="table_choice">';
echo "<option size =30 selected>Select</option>";
$result = mysql_query("show tables");
if(!$result) trigger_error("Query Failed: ". mysql_error($db), E_USER_ERROR);
if(mysql_num_rows($result))
{
while($table_array = mysql_fetch_array($result))
{
echo "<option>$table_array[0]</option>";
}
$array_value = $_POST['table_choice'];
if(!$_POST['submit'])
{
?>
<input type="submit" name="submit" value="Submit">
<?php
}
else
{
echo '<script type="text/javascript">
alert("Redirecting you to the site main page");
window.location="echo.php"</script>';
}
}
else
{
echo "<option>No Names Present</option>";
}
}
?>
Everything seems fine to me.
Where is the <form> tag?
Anyway, consider writing your web applications using some web framework or at least templates to separate the program logic (PHP code) from the presentation (HTML code). Else it will be a big unmaintainable mess soon (or maybe it already is).
<?php
include "db_connect.php";
{
?>
what's with the random bracket?
Never Mind got the answer. The answer is just to simply add an echo '</select>' above the $array_value = $_POST['table_choice'];. The answer is simply to end select with /select.
Thanks for the extra tips guys.
Related
I was practicing using HTML/PHP/MySQL, and was working on a small project.
I wanted to create a page that would allow the user to add records to a MySQL table. The user would enter the values via an HTML form. This data would then be posted to a php script to perform the actual INSERT INTO.
The database is for a shop, and has 2 tables, product and manufacturer. When adding a product, I must also add a code for the manufacturer. I want to populate a dropdown list, showing the names of manufacturers (taken from the manufacturers table).
I am attempting to embed this PHP code into an HTML file. Here is the code:
<form action="" method="post">
<fieldset>
<legend>Enter Product Details:</legend>
Product Name:<input type="text" name="productName"><br>
Product Price:<input type="text" name="Price"><br>
<?php
$host="localhost";
$user="root";
$pass="";
$db="computer_shop";
$conn=mysqli_connect($host,$user,$pass,$db) or die ("Couldn't connect");
$sql="SELECT * FROM manufacturer";
$result=mysqli_query($conn,$sql) or die ("Could not execute query!");
if(!$result){
echo"Error with results";
}
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$code=$row["Code"];
$name=$row["Name"];
echo"<select name='select'>";
echo"<option value=" .$code.">".$name."</option>" ;
<echo"</select>";
}
echo "<br>";
} else {
echo "0 results";
}
mysqli_close($conn);
?>
<input type="submit" value="Submit">
</fieldset>
</form>
When I attempt this, it doesn't go well. When I load the page, the initial part of the form (with input boxes for name and price are fine), but the drop down list is a mess, and I see the code: "0) { while($row = mysqli_fetch_assoc($result)) { $code=$row["Code"]; $name=$row["Name"]; echo" along with a drop down list showing only $name, and then the submit button. So the HTML file is displaying part of the actual PHP code.
My question is, how do I fix this so that the drop down list will display the values from the mysql database? I have been looking through various sites, trying different things, but I keep getting a similar problem. Should I flip things, and embed the HTML inside a PHP file instead?
In general this code is not a good practice. Make sure that this code is in a .php file and your web server supports php.
Other than that, I think that the following script will solve your problem.
if (mysqli_num_rows($result) > 0) {
//open the select tag before the loop
echo"<select name='select'>";
//populate the select
while($row = mysqli_fetch_assoc($result)) {
$code=$row["Code"];
$name=$row["Name"];
echo"<option value=" .$code.">".$name."</option>" ;
}
//close the select tag after the loop
echo"</select>";
echo "<br>";
} else {
echo "0 results";
}
Hello i am new to php and i have tried to find a piece of code that i can use to complete the task i need, i currently have a page with a form set out to view the criteria of a course. also i have a dropdown menu which currently holds all the course codes for the modules i have stored in a database. my problem is when i select a course code i wish to populate the fields in my form to show all the information about the course selected. The code i am trying to get to work is as follows:
<?php
session_start();
?>
<? include ("dbcon.php") ?>
<?php
if(!isset($_GET['coursecode'])){
$Var ='%';
}
else
{
if($_GET['coursecode'] == "ALL"){
$Var = '%';
} else {
$Var = $_GET['coursecode'];
}
}
echo "<form action=\"newq4.php\" method=\"GET\">
<table border=0 cellpadding=5 align=left><tr><td><b>Coursecode</b><br>";
$res=mysql_query("SELECT * FROM module GROUP BY mId");
if(mysql_num_rows($res)==0){
echo "there is no data in table..";
} else
{
echo "<select name=\"coursecode\" id=\"coursecode\"><option value=\"ALL\"> ALL </option>";
for($i=0;$i<mysql_num_rows($res);$i++)
{
$row=mysql_fetch_assoc($res);
echo"<option value=$row[coursecode]";
if($Var==$row[coursecode])
echo " selected";
echo ">$row[coursecode]</option>";
}
echo "</select>";
}
echo "</td><td align=\"left\"><input type=\"submit\" value=\"SELECT\" />
</td></tr></table></form><br>";
$query = "SELECT * FROM module WHERE coursecode LIKE '$Var' ";
$result = mysql_query($query) or die("Error: " . mysql_error());
if(mysql_num_rows($result) == 0){
echo("No modules match your currently selected coursecode. Please try another coursecode!");
} ELSE {
Coursecode: echo $row['coursecode'];
Module: echo $row['mName'];
echo $row['mCredits'];
echo $row['TotalContactHours'];
echo $row['mdescription'];
echo $row['Syllabus'];
}
?>
however i can only seem to get the last entry from my database any help to fix this problem or a better way of coding this so it works would be grateful
Thanks
The main error is in your final query, you're not actually fetching anything from the query, so you're just displaying the LAST row you fetched in the first query.
Some tips:
1) Don't use a for() loop to fetch results from a query result. While loops are far more concise:
$result = mysql_query(...) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
...
}
2) Add another one of these while loops to your final query, since it's just being executed, but not fetched.
For me i would use some javascript(NOTE: i prefer jQuery)
An easy technique would be to do this(going on the assumption that when creating the drop downs, your record also contains the description):
Apart from creating your dropdown options like this <option value="...">data</option>, you could add some additional attributes like so:
echo '<option value="'.$row['coursecode'].'" data-desc="'.$row['description'].'">.....</option>
Now you have all your drop down options, next is the javascript part
Let's assume you have included jQuery onto your page; and let's also assume that the description of any selected course is to be displayed in a <div> called description like so:
<div id="course-description"> </div>
<!--style it how you wish -->
With your javascript you could then do this:
$(function(){
$("#id-of-course-drop-down").change(function(){
var desc = $(this).children("option").filter("selected").attr("data-des");
//now you have your description text
$("#course-description").html(desc);
//display the description of the course
}
});
Hope this helps you, even a little
Have fun!
NOTE: At least this is more optimal than having to use AJAX to fecch the description on selection of the option :)
needing some advice.
I am wanting to include 4 drop down lists on a website, which all contain data from different fields in a mysql table.
I then want to be able to press a submit button and display the required data on a webpage.
I am having trouble with knowing what programming language to use and also finding it difficult to find any tutorials. Any help would be greatly appreciated.
Thanks
You mean a HTML dropdown list or just a select dropdown in a form?
If you mean a select dropdown in a form you could do something like this:
<?PHP
$query = mysql_query("SELECT value FROM table ORDER BY value ASC") or die(mysql_error());
$result = mysql_num_rows($result);
// If no results have been found or when table is empty?
if ($result == 0) {
echo 'No results have been found.';
} else {
// Display form
echo '<form name="form" method="post" action="your_result.php">';
echo '<select name="list" id="lists">';
// Fetch results from database and list in the select box
while ($fetch = mysql_fetch_assoc($query)) {
echo '<option id="'.$fetch['value'].'">'.$fetch['value'].'</option>';
}
echo '</select>';
echo '</form>';
}
?>
And then in your_result.php you should fetch the data from your MySQL database based on value from the (when you fetch use mysql_real_escape_string):
<?PHP $_POST['list']; ?>
You could also do everything in just one file, but thats up to you. Try to use google, there are dozens of tutorials out there.
not sure how feasable this is, but I have just rolled my own user search form, which simply queries my database and returns all the results with any given username, or similar using the LIKE 'some_username%' statement.
My search works great, and im really chuffed with myself as I am a php and mysql novice.
I used a mysql_fetch_assoc($result) statement, and then used a while loop to echo out each row from the database into an html table.
What I would then like to be able to do, is select a record from the table, and open a new page, which is populated with all the fields for that record, which I can then use to edit and update the user settings.
I thought perhaps one way to do it, is to perhaps echo out a form instead? that way I can have a button next to each row, to post the fields into some php code on my new page? I thought this may be a bit clunky though, and not sure how I would go about echoeing out a different form for each row.
Don;t know if anyone had any ideas on the best way to do this? If you need any code examples of what im working with, I can post them here.
Thanks very much!!
Eds
not a form but a hyperlink.
I wonder why you aren't familiar with this way of opening new pages as it is used everywhere.
just create a hyperlink
name
here is a sketch example of such an application, editing only one field, but you can add any number as well:
a main script:
<?
mysql_connect();
mysql_select_db("new");
$table = "test";
if($_SERVER['REQUEST_METHOD']=='POST') { //form handler part:
$name = mysql_real_escape_string($_POST['name']);
if ($id = intval($_POST['id'])) {
$query="UPDATE $table SET name='$name' WHERE id=$id";
} else {
$query="INSERT INTO $table SET name='$name'";
}
mysql_query($query) or trigger_error(mysql_error()." in ".$query);
header("Location: http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
exit;
}
if (!isset($_GET['id'])) { //listing part:
$LIST=array();
$query="SELECT * FROM $table";
$res=mysql_query($query);
while($row=mysql_fetch_assoc($res)) $LIST[]=$row;
include 'list.php';
} else { // form displaying part:
if ($id=intval($_GET['id'])) {
$query="SELECT * FROM $table WHERE id=$id";
$res=mysql_query($query);
$row=mysql_fetch_assoc($res);
foreach ($row as $k => $v) $row[$k]=htmlspecialchars($v);
} else {
$row['name']='';
$row['id']=0;
}
include 'form.php';
}
?>
and two simple templates responsible for output,
one for the displaying the form, form.php
<? include TPL_TOP ?>
<form method="POST">
<input type="text" name="name" value="<?=$row['name']?>"><br>
<input type="hidden" name="id" value="<?=$row['id']?>">
<input type="submit"><br>
Return to the list
</form>
<? include TPL_BOTTOM ?>
and one to display the list, list.php
<? include TPL_TOP ?>
Add item
<? foreach ($LIST as $row): ?>
<li><?=$row['name']?>
<? endforeach ?>
<? include TPL_BOTTOM ?>
always start php like this <?php, usually php manual configuration do not support short tag like this <?.
for hyperlink just use view record
It is just query string and get id on next page like this
$id = $_GET['id'];
Hope u will understand..
I am using PHP 5 to create a query page for a MySQL database with 2 tables "students" and "teachers". I have created a combo box which can allow users to view and select the 2 tables from the combo box via a "submit" button after selecting from the combo box.
However the problem with the script is that I want to verify if the "submit" button works which I created a "echo.php" to echo out the value of the combo box and submit button. Overall the idea is to do a query like these steps:
1) User selects value from combo box "teacher" or "student".
2) User clicks submit button.
3) After clicking submit button, user is redirected to "echo.php"
4) "echo.php" should output/echo out either "teacher" or "student".
The codes for script:
<?php
include "db_connect.php";
{
?>
<td valign=top><strong>Name:</strong></td>
<td>
<?php
echo "<form name = \"queryEquipTypeForm\" method = \"post\" action
=\"select_table.php\">";
echo '<select name=\"table\">';
echo "<option size =30 selected>Select</option>";
$result = mysql_query("show tables");
if(!$result) trigger_error("Query Failed: ". mysql_error($db), E_USER_ERROR);
if(mysql_num_rows($result))
{
while($table_array = mysql_fetch_array($result))
{
echo "<option>$table_array[0]</option>";
}
echo '</select>';
echo '</form>';
if(!$_POST['submit'])
{
?>
<form method="post" action="select_table.php">
<input type="submit" name="submit" value="Submit">
</form>
<?php
}
else
{
echo '<script type="text/javascript">
alert("Redirecting you to echo.php page");
window.location="echo.php"</script>';
}
}
else
{
echo "<option>No Names Present</option>";
}
}
?>
</td>
The codes for "echo.php" :
<?php
include "select_table.php";
echo "data is : ".$_POST['table'];
?>
The output of echo.php would be exactly the same as "select_table.php" with the cobo box and the "data is: " without the "teachers" or "student" word as its being redirected to echo.php.
I'm not quite sure what exactly what you want to do, but as michaeltwofish already pointed out, redirecting to another page using javascript will make you lose the post data. Also you seem to echo two <form> elements when the select_table.php is called without post data, one with only a submit button, while your first form is missing the button.
Normally, you would want your php script to either output the form with the combobox where the user can select the table, or, if there was post data (meaning that the user selected a value), the results of the selection, kinda like the following:
<?php
if(isset($_POST['table'])) {
print "Selected element: " . $_POST['table'];
} else {
echo '<form method="post" action="select_table.php">';
echo '<select name="table">';
// here should be your SQL query and the combobox options generation
echo '</select>';
echo '<input type="submit" />';
echo '</form>';
}
?>
When the form is submitted, you redirect to echo.php, but that means you lose the POST data. You need to think carefully about the flow of your application, because what you have seems a bit confused.