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";
}
Related
I'm new to php.
I have this page:
<?php
function renderForm($id, $StaffFullName, $StaffJobPosition, $error)
{
?>
<!doctype html>
<html>
<head><title></title></head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div>'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p>ID: <?php echo $id; ?></p>
Name: * <input type="text" name="StaffFullName" value="<?php echo $StaffFullName; ?>"/><br/>
Job Position: * <select name="JobPosition">
<?php
$query = "SELECT * FROM LUT_JOBPOS";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)){
if ($StaffJobPosition == $row['JobposID'])
{
echo "<option value='{$row['JobposID']}' selected='selected'>{$row['JobposTitle']}</option>";
}
else {
echo "<option value='{$row['JobposID']}'>{$row['JobposTitle']}</option>";
}
}
$result->close();
?>
</select><br/>
<input type="submit" name="submit" value="Update">
<input type="button" onClick="parent.location='view.php'" value="Back">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
require_once('../../authenticate.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// do some funky stuff
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checking that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$query = "SELECT * FROM STAFF WHERE StaffID=$id";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$result->close();
// check that the 'id' matches up with a row in the database
if($row)
{
// get data
$StaffFullName = $row['StaffFullName'];
$StaffJobPosition = $row['StaffJobPosition'];
// show form
renderForm($id, $StaffFullName, $StaffJobPosition, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
So, what happens here is this:
When you open the page like edit.php?id=1, it fetches the data of the associated record from STAFF table and shows them on page for the user to edit them.
This part of the code works fine.
I also want the user to be able to select "Job Position" possible values from a drop down box. The drop down box should get its data from another table in database, LUT_JOBPOS.
This is the part of the code that doesn't work.
I was using mysql_query commands before on this page and it worked perfectly. However I was told to switch on mysqli_query instead.
Since I did the conversion I can't find how to run these two queries on the same script.
I messed a little bit with the require_once command and depending on where I call it I can run one query or another, but never both of them.
Looking at the logs of my web host the only thing I can see that may be relevant to my issue is:
"mod_fcgid: stderr: PHP Notice: Undefined variable: connection in /var/www/vhosts/myhostdomain.com/httpdocs/prod15/admin/staff/edit.php on line 24"
The connection variable comes from authenticate.php and it holds the connection parameters to the database. I'm sure it's set otherwise the first query (that gets the user data) wouldn't work.
I read somewhere that you can't run two sqli queries on the same script.
Then how I'm supposed to use a LUT table (lookup table)?
PS: I know that for showing the data I can use a UNION and that's what I do.
But when I edit the data I want the user to be able to select only from the possible values that exist on the LUT table (drop down select box)
Any help?
You have a lot of issues in your code. You really need to review it before use it in some real application, but for your specific problem, here is my guess.
You are calling the line $result = mysqli_query($connection, $query); in the line 24 and only after taht you call require_once('../../authenticate.php');.
As you said, the $connection var is defined in the authenticate.php, so in the line 24 is undefined.
Try to use require in the first line of your php script.
I have a drop down list that is populated with a column “product_name” from a database “products”.
Each of these products has a finish level, “good”, “better”, “best” with a different price associated with that level. (i.e. product 1 has 3 different prices in 3 separate columns)
I would like to have radio buttons labeled “good”, “better”, “best” underneath the drop down that take the selected “product name” and look up the price in the database table associated with the selected radio button finish level and place that value into a text box underneath the radio buttons that the user can see, but obviously not edit.
I would want it to refresh in real time if the user changes the selection of the drop down menu.
This is all on a form that is submitted at the end to a php page that does some math to make an invoice.
There is way too much background knowledge needed, to answer this in a single question.
You should start off by getting to know javascript.
There is a good tutorial here: http://www.w3schools.com/js/
When you have a good feeling for that, learn about AJAX here: http://www.w3schools.com/ajax/default.asp
You should probably look for the onChange events on the controls affected (radio buttons and dropdown) and fire an AJAX call when one of the values changes, which will give you the result you would like to put in the third input field.
Hope this helps you :)
This works:
<?php
//***************************************
// This is downloaded from www.plus2net.com //
/// You can distribute this code with the link to www.plus2net.com ///
// Please don't remove the link to www.plus2net.com ///
// This is for your learning only not for commercial use. ///////
//The author is not responsible for any type of loss or problem or damage on using this script.//
/// You can use it at your own risk. /////
//*****************************************
$dbservertype='mysql';
$servername='localhost';
// username and password to log onto db server
$dbusername='';
$dbpassword='';
// name of database
$dbname='dd';
////////////////////////////////////////
////// DONOT EDIT BELOW /////////
///////////////////////////////////////
connecttodb($servername,$dbname,$dbusername,$dbpassword);
function connecttodb($servername,$dbname,$dbuser,$dbpassword)
{
global $link;
$link=mysql_connect ("$servername","$dbuser","$dbpassword");
if(!$link){die("Could not connect to MySQL");}
mysql_select_db("$dbname",$link) or die ("could not open db".mysql_error());
}
//////// End of connecting to database ////////
?>
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>Multiple drop down list box from plus2net</title>
<SCRIPT language=JavaScript>
function reload(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
self.location='dd.php?cat=' + val ;
}
</script>
</head>
<body>
<?
/*
If register_global is off in your server then after reloading of the page to get the value of cat from query string we have to take special care.
To read more on register_global visit.
http://www.plus2net.com/php_tutorial/register-globals.php
*/
#$cat=$_GET['cat']; // Use this line or below line if register_global is off
if(strlen($cat) > 0 and !is_numeric($cat)){ // to check if $cat is numeric data or not.
echo "Data Error";
exit;
}
//#$cat=$HTTP_GET_VARS['cat']; // Use this line or above line if register_global is off
///////// Getting the data from Mysql table for first list box//////////
$quer2=mysql_query("SELECT DISTINCT category,cat_id FROM category order by category");
///////////// End of query for first list box////////////
/////// for second drop down list we will check if category is selected else we will display all the subcategory/////
if(isset($cat) and strlen($cat) > 0)
{
$quer=mysql_query("SELECT DISTINCT subcategory FROM subcategory where cat_id=$cat order by subcategory");
}
else
{
$quer=mysql_query("SELECT DISTINCT subcategory FROM subcategory order by subcategory");
}
////////// end of query for second subcategory drop down list box ///////////////////////////
echo "<form method=post name=f1 action='dd-check.php'>";
/// Add your form processing page address to action in above line. Example action=dd-check.php////
////////// Starting of first drop downlist /////////
echo "<select name='cat' onchange=\"reload(this.form)\"><option value=''>Select one</option>";
while($noticia2 = mysql_fetch_array($quer2))
{
if($noticia2['cat_id']==#$cat)
{
echo "<option selected value='$noticia2[cat_id]'>$noticia2[category]</option>"."<BR>";
}
else
{
echo "<option value='$noticia2[cat_id]'>$noticia2[category]</option>";
}
}
echo "</select>";
////////////////// This will end the first drop down list ///////////
////////// Starting of second drop downlist /////////
echo "<select name='subcat'><option value=''>Select one</option>";
while($noticia = mysql_fetch_array($quer))
{
echo "<option value='$noticia[subcategory]'>$noticia[subcategory]</option>";
}
echo "</select>";
////////////////// This will end the second drop down list ///////////
//// Add your other form fields as needed here/////
echo "<input type=submit value=Submit>";
echo "</form>";
?>
<center><a href='http://www.plus2net.com'>PHP SQL HTML free tutorials and scripts</a>
</center>
</body>
</html>
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.
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.