Select option from dropdown menu with PHP and mySql [duplicate] - php

This question already has answers here:
Create PHP array from MySQL column
(12 answers)
Closed 22 days ago.
I tried to create a simple select dropdown menu from MySQL database. However, it does not work on my code.
Here is my code:
<?php
mysql_select_db($database_conn, $conn);
$query_RsCourse = "SELECT * FROM tbl_course ORDER BY courseid DESC";
$RsCourse = mysql_query($query_RsCourse, $conn) or die(mysql_error());
$totalRows_RsCourse = mysql_num_rows($RsCourse);
$count=0;
while ( $row = mysql_fetch_array($RsCourse, MYSQL_ASSOC)) {
$courseid=$row["courseid"];
$count++;
}
?>
<tr>
<td bgcolor="#CCCCCC"> Course Name</td>
<td bgcolor="#dfdfdf"> <select name="courseid">
<option value="" SELECTED>Selected Course</option>
<option value="<?php echo $courseid; ?>"><?php echo $row_RsCourse['$courseid']; ?></option>
</select>
</td>
</tr>
Any advice will be appreciated!

<?php
echo '<tr>
<td bgcolor="#CCCCCC"> Course Name</td>
<td bgcolor="#dfdfdf"> ';
mysql_select_db($database_conn, $conn);
$query_RsCourse = "SELECT * FROM tbl_course ORDER BY courseid DESC";
$RsCourse = mysql_query($query_RsCourse, $conn) or die(mysql_error());
$totalRows_RsCourse = mysql_num_rows($RsCourse);
if($totalRows_RsCourse)
{
echo '<select name="courseid"><option value="" SELECTED>Selected Course</option>';
$count=0;
while ($row = mysql_fetch_array($RsCourse, MYSQL_ASSOC))
{
$count++;
echo '<option value="'.$row['courseid'].'">'.$row['courseid'].'</option>';
}
echo '</select>';
}
else
{
echo 'No courses to show yet.'; // no rows in tbl_course
}
echo '</td>
</tr>';
?>
That was a mess, but hope you can go on from these new codes. Enjoy.
PS: this part >'.$row['courseid'].'</option> u can change to new one according to your table structure which one is not shown here.
<?php
echo '<tr>
<td bgcolor="#CCCCCC"> Course Name</td>
<td bgcolor="#dfdfdf"> ';
mysql_select_db($database_conn, $conn);
$query_RsCourse = "SELECT * FROM tbl_course ORDER BY courseid DESC";
$RsCourse = mysql_query($query_RsCourse, $conn) or die(mysql_error());
$totalRows_RsCourse = mysql_num_rows($RsCourse);
echo '<select name="courseid"><option value="" SELECTED>Selected Course</option>';
$count=0;
while ($row = mysql_fetch_array($RsCourse, MYSQL_ASSOC))
{
$count++;
echo '<option value="'.$row['courseid'].'">'.$row['courseid'].'</option>';
}
echo '</select></td>
</tr>';
?>

You can store everything in a buffer and print at once in the select below:
<?php
mysql_select_db($database_conn, $conn);
$query_RsCourse = "SELECT * FROM tbl_course ORDER BY courseid DESC";
$RsCourse = mysql_query($query_RsCourse, $conn) or die(mysql_error());
$coursesHtml = "";
while ( $row = mysql_fetch_array($RsCourse, MYSQL_ASSOC)) {
$coursesHtml .= "<option value='{$row["courseid"]}'>{$row["coursename"]}</option>";
}
?>
<tr>
<td bgcolor="#CCCCCC">Course Name</td>
<td bgcolor="#dfdfdf">
<select name="courseid">
<option value="" SELECTED>Selected Course</option>
<?= $coursesHtml ?>
</select>
</td>
</tr>
PS: Avoid use , style your html well with css using padding-left: 5px; or other features;
PS2: You should not show your page/form with tables structure, use divs with flexbox.

Related

I would like to avoid repeating codes

Hello I'm trying to build a web app for a friend of mine to help her in her business. The application is meant to help her monitor the number of Stock Keeping Unit in the storage of her little bakeshop.(or monitor how much sacks of flour, tray of eggs, cups of butter are left in her inventory). So to do this I've made a form for her. look:
<tr> <form method="POST" action="makeprod.php">
<td>Prodname</td>
<td> <input type="text" name="prodname"></td>
</tr>
<tr>
<td>Quantity</td>
<td> <input type="int" name="quantity"></td>
</tr>
<tr>
<td>Recipe 1: </td>
<td>
<?php
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('inventory system');
$sql = "SELECT itemname FROM inventory";
$result = mysql_query($sql);
echo "<select name='recipe1'>";
while ($row = mysql_fetch_array($result)){
echo "<option value = ' ". $row ['itemname'] ."'>".$row['itemname']."</option>";
}
echo "</select>";
?>
</td>
<td>Qty</td>
<td> <input type="int" name="rec1qty"></td>
</tr>
<tr>
<td>Recipe 2: </td>
<td>
<?php
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('inventory system');
$sql = "SELECT itemname FROM inventory";
$result = mysql_query($sql);
echo "<select name='recipe2'>";
while ($row = mysql_fetch_array($result)){
echo "<option value = ' ". $row ['itemname'] ."' >".$row['itemname']."</option>";
}
echo "</select>";
?>
</td>
<td>Qty</td>
<td> <input type="int" name="rec2qty"></td>
</tr>
<tr>
<td>Recipe 3: </td>
<td>
<?php
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('inventory system');
$sql = "SELECT itemname FROM inventory";
$result = mysql_query($sql);
echo "<select name='recipe3'>";
while ($row = mysql_fetch_array($result)){
echo "<option value = ' ". $row ['itemname'] ."'>".$row['itemname']."</option>";
}
echo "</select>";
?>
</td>
<td>Qty</td>
<td> <input type="int" name="rec3qty"></td>
</tr>
<tr>
<td>Recipe 4: </td>
<td>
<?php
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('inventory system');
$sql = "SELECT itemname FROM inventory";
$result = mysql_query($sql);
echo "<select name='recipe4'>";
while ($row = mysql_fetch_array($result)){
echo "<option value = ' ". $row ['itemname'] ."' >".$row['itemname']."</option>";
}
echo "</select>";
?>
</td>
<td>Qty</td>
<td> <input type="int" name="rec4qty"></td>
</tr>
<tr>
<td>Recipe 5: </td>
<td>
<?php
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('inventory system');
$sql = "SELECT itemname FROM inventory";
$result = mysql_query($sql);
echo "<select name='recipe5'>";
while ($row = mysql_fetch_array($result)){
echo "<option value = ' ". $row ['itemname'] ."' >".$row['itemname']."</option>"; ['itemname']."</option>";
}
echo "</select>";
?>
</td>
<td>Qty</td>
<td> <input type="int" name="rec5qty"></td>
</tr>
<tr>
<td><input id="button" type="submit" name="submit" value="submit"></td>
</tr>
</form>
</table>
What I'm trying to do in this form is to prompt her to record a product/pastry she's making, quantity and indicate the recipes/inventories that will cost her to make that product in that quantity so it will reduce those recipes from a database table I named 'inventory'(but this is for another story).
My issue is that I could not determine how many ingredients she'll need to make a single product and repeating a select option for the recipe 5 or 10 times seems to make my code look too dirty and it doesn't seem like efficient. What I want is a code that will help me display only the number of select options she needs in the form. So if a product she's making only has about 6 different ingredients then only 6 select option should be displayed. If 3, then only 3.
It would help if I don't have to repeat this code from above to make my code atleast a bit cleaner:
<td>Recipe 1: </td>
<td>
<?php
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('inventory system');
$sql = "SELECT itemname FROM inventory";
$result = mysql_query($sql);
echo "<select name='recipe1'>";
while ($row = mysql_fetch_array($result)){
echo "<option value = ' ". $row ['itemname'] ."' >".$row['itemname']."</option>";
}
echo "</select>";
?>
I'm fairly new to PHP and doesn't know Javascript yet so I would prefer solution in HTML/PHP format but JS would also suffice. Thank you.
As per your title of question you have repeating code of sql connection in your code. Do avoid it by adding single connection file. Do create connection.php and add below code in it.
<?php
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('inventory system');
?>
and include this file in your this working page as
include "connection.php";

get multiple ID while POST multiple selection option value to next form

how can I get multiple ID while POST multiple selection option value to next form? I only get the first selection ID from array. Can you guys can suggest any ideas to me?
here is my code when select the value.
<tr>
<label>Auditor: </label>
<select class="form-control" name="auditor[]" multiple="multiple" >
<?php
$result = $db->query("SELECT * FROM auditor");
while($row = mysqli_fetch_array($result))
{
echo '<option value="'.$row["auditor_name"].'">'.$row["auditor_name"].'</option>';
}
echo "</select>";
?>
</tr>
here is another code while POST to the next page.
$myselected = $_POST["auditor"];
if(count($myselected)>1){
$auditor = implode ("','",$myselected);
}else{
$auditor =$myselected;
}
$query10 = "SELECT * FROM auditor WHERE auditor_name IN ('$auditor') ";
$result10 = $db->query($query10);
$row10 = $result10->fetch_array();
?>
<form action="audit_action/audit_action.php" role="form" method="post" name="auditformdetails" onsubmit="return(validate());">
<table width='100%' border='0' class="table">
<tr>
<td colspan=6>Audit details</td>
<td colspan=6>Outlet details</td>
</tr>
<tr>
<td><b>Auditor:</b></td>
<td colspan='5'>
**<?php
echo'<input type="hidden" name="auditor_id" value="'.$row10["id"].'">';
foreach ($myselected as $auditor){
echo $auditor."<br>\n";
}
?>**
</td>
You can not compare string with mysql IN Clause. So, you have to connect each of your value with or condition in query as i written below.
$myselected = $_POST["auditor"];
$sql_cond = "";
if(count($myselected)>1){
foreach($myselected as $selected){
if($sql_cond != "")
$sql_cond.=" or auditor_name = ".$selected;
else
$sql_cond.=" auditor_name = ".$selected;
}
}else{
$auditor =$myselected;
}
$query10 = "SELECT * FROM auditor WHERE ".$sql_cond;

pull the data from mysqli to dropdown list php

I have been trying to pull the data from database mysqli in the drop down menu. Here is my code for postad.html. I want to pull categories data from categories table with a row name CatName. I also have CatId that shows ctegory id. Thank you in advance.Please help:
<html>
<head>
<title>Post AD</title>
</head>
<body>
<form method="POST" action="postad.php">
<table>
<tr>
<td>AdName:</td>
<td><input type="text" name="adname"></td>
</tr>
<tr>
<td>AdCategory</td>
<td>
//dropdown list
<select name="Categories">
<?php include = connect.php
$sql = "SELECT CatName FROM categories order by CatName";
$result = $db->query($sql);
while($row = $result->fetch_array()) {
echo "<option value='". $row['CatName']."'>."</option>';
}
?>
</select>
</td>
</tr>
<tr>
<td>Contact Number</td>
<td><input type="text" name="contactnumber"></td>
</tr>
<tr>
<td>Image</td>
<td><input type="text" name="image"></td>
</tr>
<tr>
<td>Description</td>
<td><input type="text" name="description"></td>
</tr>
<tr>
<td>Expiration Date</td>
<td><input type="text" name="expirationdate"></td>
</tr>
<tr>
<td id="btn"><input type="submit" value='submit' name="submit"></td>
</tr>
</table>
</form>
</body>
</html>
Looks like you have an error with your menu code. Should be this
echo "<option value=". $row['CatName'] ."></option>';
Opposed to
echo "<option value='". $row['CatName']."'>."</option>';
The result from the table is going to be a string regardless so there is no need to worry about value=''. The real problem was how you muffled up your quotes.
EDIT: Just noticed include = connect.php should be include 'connect.php';
<?php
$mysql_host = '';
$mysql_user = '';
$mysql_pass = '';
$mysql_dbase = '';
$mysql_table = '';
$pdo = new PDO('mysql:host=' . $mysql_host . ';dbname=' . $mysql_dbase, $mysql_user, $mysql_pass);
$sth = $pdo->prepare('SELECT * FROM `' . $mysql_table . '` ORDER BY `id` CatName');
$sth->execute();
$result = $sth->fetchAll();
foreach ($result as $row) {?>
<option value=<?php echo $row['CatName']; ?>></option>;
<?}?>
echo "<option value='". $row['CatName']."'>."</option>';
contains error and also there is no inner html for options
You can use this way for simplicity.
$CatName=$row["CatName"];
echo '<option value="'.$CatName.'">'.$CatName.'</option>';
Ok. Now I have created a new php file called getcategories.php. and this page works well. Here is the code for it:
$sql = "SELECT CatName FROM categories order by CatName";
$result = $db->query($sql);
$options="";
//echo "<select value='categories'>";
while($row = $result->fetch_assoc()) {
$categoryname=$row["CatName"];
// echo '<option value="'.$categoryname.'">'.$categoryname.'</option>';
// echo "</select>";
//echo "$categoryname\n";
$options .= '<option value="'.$categoryname.'">'.$categoryname.'</option>';
}
?>
How should I pull the data of options to the dropdown of html file

Why is that My PHP records not being INSERTED

Good Day!
Guys can you help me to check why my is it that i cannot insert records using chekbox option on table..
Please Help..
Here's My Code...
--ADDING Subject Load for Teacher HTML Form-- (studsub.php)
<form action="setsubject.php" method="post">
<?php
include('../connect.php');
$id=$_GET['id'];
$result = mysql_query("SELECT * FROM student WHERE id='$id'");
while($row = mysql_fetch_array($result))
{
//$course=$row['course'];
//$year=$row['yearlevel'];
//$section=$row['section'];
$idnumber=$row['idnumber'];
echo '<br/>';
echo $row['lname'].", ".$row['fname'];
?>
<input type="hidden" name="studidnum" value="<?php echo $rows['idnumber']?>">
<?php }
?>
<br/><br/>
<label for="filter">Filter</label> <input type="text" name="filter" value="" id="filter" />
<table cellpadding="1" cellspacing="1" id="resultTable">
<thead>
<tr>
<th style="border-left: 1px solid #C1DAD7"><label>Assign</label></th>
<th style="border-left: 1px solid #C1DAD7"> Subject ID </th>
<th>Title</th>
<th>Units</th>
</tr>
</thead>
<tbody>
<?php
include('../connect.php');
$result = mysql_query("SELECT * FROM tbl_cur_sub where status='1' ");
while($row = mysql_fetch_array($result))
{
echo '<tr class="record">';
echo ' <td>' . '<input type="checkbox" name="subject[]" value="'.$rows['code'].'" />' . '</td> ' ;
echo '<td style="border-left: 1px solid #C1DAD7">'.$row['code'].'</td>';
echo '<td><div align="left">'.$row['subject'].'</div></td>';
echo '<td><div align="left">'.$row['units'].'</div></td>';
echo '</tr>';
}
?>
</tbody>
</table>
<br/>
Course<br>
<select name="course" class="ed">
<?php
include('../connect.php');
$results = mysql_query("SELECT * FROM course");
while($rows = mysql_fetch_array($results))
{
echo '<option>'.$rows['coursecode'].'</option>';
}
?>
</select>
<select name="yearlevel" class="ed">
<?php
include('../connect.php');
$results = mysql_query("SELECT * FROM tbl_yrlevel");
while($rows = mysql_fetch_array($results))
{
echo '<option>'.$rows['yearlevel'].'</option>';
}
?>
</select>
<select name="section" class="ed">
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
</select>
<br>
<br>
<input type="submit" value="Assign" id="button1">
</form>
--The Submission Page -- (setsubject.php)
<?php
include('../connect.php');
//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
$course = clean($_POST['course']);
$section = clean($_POST['section']);
$yearlevel = clean($_POST['yearlevel']);
$studidnum=$_POST['studidnum'];
$subject=$_POST['subject'];
$N = count($subject);
for($i=0; $i < $N; $i++)
{
mysql_query("INSERT INTO studentsubject (student, subject, section, course, level) VALUES ('$studidnum', '$subject[$i]','$section','$course', '$level')");
}
header("location: student.php");
mysql_close($con);
?>
--My Database--
TABLE: studentsubject
FIELDS: student, subject, section, course, level
Thanks IN advance for the Help..
TRY
mysql_query("SELECT * FROM tbl_cur_sub where status=1 ");
change the mysql statement...you need to differ the variable and string in the query
$result = mysql_query("SELECT * FROM student WHERE id='".$id."'");

search with multiple category and criteria

My table has 4 columns. "isbn, author, title, price".
I want to search one of them combining all 4 fields.
Like: if author "kayle" write 4 books with same price ($50) but with different title, for that in search page, if i select author:kayle and hit search, then it shows all books with all different or may be same prices and titles. Now i want to select author:kayle and price:$50 at the same time, and hit enter. For that it will show only $50 prices books wrote by kayle and it will appear in the table with 4 rows.
I try to combine it but stuck with the second step searching query. Here is my code if any one understand what i want to do, please share it. Here is my code:
<form method="post" action="search_form.php">
<input type="hidden" name="submitted" value="true"/>
<table border="1">
<tr>
<td style="padding:3px 10px; font-weight:bold;">ISBN</td>
<td style="padding:3px;">
<input type="hidden" name="category_isbn" id="category_isbn" value="isbn"/>
: <select name='criteria_isbn' id="criteria_isbn" onchange="ajaxFunction()">
<option selected="selected">- Select -</option>
<?php
$order = "SELECT isbn FROM books" or die (mysql_error());
$result = mysql_query($order);
while($data = mysql_fetch_array($result))
{
echo ("<option> $data[isbn] </option>");
}
?>
</select>
</td>
<td style="padding:3px 10px; font-weight:bold;">Author</td>
<td style="padding:3px;">
<input type="hidden" name="category_author" id="category_author" value="author"/>
: <select name='criteria_author' id="criteria_author" onchange="ajaxFunction()">
<option selected="selected">- Select -</option>
<?php
$order = "SELECT author FROM books" or die (mysql_error());
$result = mysql_query($order);
while($data = mysql_fetch_array($result))
{
echo ("<option> $data[author] </option>");
}
?>
</select>
</td>
<td style="padding:3px 10px; font-weight:bold;">Title</td>
<td style="padding:3px;">
<input type="hidden" name="category_title" id="category_title" value="title"/>
: <select name='criteria_title' id="criteria_title" onchange="ajaxFunction()">
<option selected="selected">- Select -</option>
<?php
$order = "SELECT title FROM books" or die (mysql_error());
$result = mysql_query($order);
while($data = mysql_fetch_array($result))
{
echo ("<option> $data[title] </option>");
}
?>
</select>
</td>
<td><input type="submit" /></td>
</tr>
</table>
</form>
<?php
if(isset($_POST['submitted']))
{
$category_isbn = $_POST['category_isbn'];
$criteria_isbn = $_POST['criteria_isbn'];
$query = "SELECT * FROM books WHERE $category_isbn LIKE '%".$criteria_isbn."%'";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($result);
if(isset($_POST['criteria_isbn']))
{
$category_author = $_POST['category_author'];
$criteria_author = $_POST['criteria_author'];
$query = "SELECT * FROM books WHERE $category_author LIKE '%".$criteria_author."%'";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($result);
if(isset($_POST['criteria_author']))
{
$category_title = $_POST['category_title'];
$criteria_title = $_POST['criteria_title'];
$query = "SELECT * FROM books WHERE $category_title LIKE '%".$criteria_title."%'";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($result);
echo "$num_rows results found";
echo "<table border= 1>";
echo "<tr> <th>ISBN</th> <th>AUTHOR</th> <th>TITLE</th> <th>PRICE</th> </tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr><td>";
echo $row['isbn'];
echo "</td><td>";
echo $row['author'];
echo "</td><td>";
echo $row['title'];
echo "</td><td>";
echo $row['price'];
echo "</td></tr>";
}
echo "</table>";
}
}
}
?>
Thanks in advance.
try this
for first search
select* from table where author="kayle";
for second search
select * from table where author="kayle" and price="50";

Categories