Populating Dropdown box from mysql using php - php

Student looking for help.
Trying to populate a dropdown menu from a mysql database, no data being showed in dropdown. Using getCategory function to get data from tables categories. Database is connecting and the particular table is being accessed through another function. I'm lost on this one, been looking and googling for the answer for last number of nights, still no luck. Maybe I've been looking at it too long that my brains fried?
Function Code
public function getCategory()
{
echo $query = "SELECT * FROM `categories`";
$results = mysqli_query($this->_con, $query) or die(mysqli_error());
$categories = array();
foreach ($results as $result){
$categories[$result['id']] = $result['category_name'];
}
mysqli_close($this->_con);
return $categories;
echo "<pre>"; print_r($categories); echo "</pre>";
}
Dropdown Code
<select class="form-control" name="category" id="category">
<option value="">Choose your category</option>
<?php foreach ($categories as $key=>$category){ ?>
<option value="<?php echo $key; ?>"><?php echo $category; ?></option>
<?php } ?>
</select>
Table called categories
Columns are id & category_name

please try the below code in your code in your function
$nums=mysql_num_rows($results);
for($i=0;$i<$nums;$i++)
{
$id=mysql_result($results,$i,'id');
$category=mysql_result($results,$i,'category_name');
$categories[$id] = $category;
}
$categories =getCategory() ;

I am not sure what you are struggling with, your code is missing a function call to getCategory (should be called getCategories because you are getting plural of objects, not one. Just a sidenote).
Following code is tested and works (save as index.php in your documentRoot to test), please be aware that I cannot declare a function as public when not in a class context, also I could not use $this->_con without a class with _con var, so I used $con instead. You need to adapt it to your context and needs:
index.php:
<?php
$category = filter_input(INPUT_POST,'category');
if($category!=FALSE && $category!=NULL){
$selectedCategory = $category;
}
function getCategory() {
$con = mysqli_connect("localhost","root","","categories") or die("Error " . mysqli_error($con));
echo $query = "SELECT * FROM `categories`";
$results = mysqli_query($con, $query) or die(mysqli_error());
$categories = array();
foreach ($results as $result){
$categories[$result['id']] = $result['category_name'];
}
mysqli_close($con);
return $categories;
}
?>
<html>
<head>
<title>Categories Test</title>
</head>
<body>
<?php
if(isset($selectedCategory)){
echo "last selected category ID: ".$selectedCategory;
}
?>
<form action="index.php" method="POST">
<select class="form-control" name="category" id="category">
<option value="">Choose your category</option>
<?php
$categories = getCategory();
foreach ($categories as $key=>$category): ?>
<option value="<?php echo $key; ?>"><?php echo $category; ?></option>
<?php endforeach; ?>
</select>
<input type="submit" value="send" />
</form>
</body>

Here is the example i did it in this way. Hope! it will helps you.
public function GetStates()
{
$tempgetstates = mysql_query("SELECT * FROM `states`") or die(mysql_error());
echo '<select name="state" class="sel_reg_form" required />';
echo '<option value="">...Select...</option>';
while($getstates = mysql_fetch_object($tempgetstates))
{
echo '<option value="'.$getstates->state_code.'">'.$getstates->state.'</option>';
}
echo '</select>';
}

Related

PDO query stop loop - Php

so i trying to use some query at pdo , but only the first select show results , the second select dont show the results , only show " Selecione "
look my code below
<?php
$con1 = new PDO('mysql:host=localhost;dbname=db','root','passdb');
$con1->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sqlimpressora = $con1->query("SELECT * FROM impressoras");
?>
<html>
<body>
<form>
<select name="impressora" class="form-control">
<option value="selecione">Selecione...</option>
<?php while($prod = $sqlimpressora->fetch(PDO::FETCH_BOTH)) { ?>
<option value="<?php echo $prod['nome'] ?>"><?php echo $prod['nome'] ?></option>
<?php } ?>
</select>
<select name="impressora" class="form-control">
<option value="selecione">Selecione...</option>
<?php while($prod2 = $sqlimpressora->fetch(PDO::FETCH_BOTH)) { ?>
<option value="<?php echo $prod2['nome'] ?>"><?php echo $prod2['nome'] ?></option>
<?php } ?>
</select>
</form>
</body>
</html>
Do not use ->fetch twice, use ->fetchAll and loop over the result.
$sqlimpressora = $con1->query("SELECT * FROM impressoras");
$result = $sqlimpressora->fetchAll();
foreach($result as $prod) {
// <select > .....
}
Each call to $sqlimpressora->fetch() will move the cursor to the next record in the result set. So when your first while loop finished it moved the cursor to the end of the result set and thus another fetch() call fetched nothing.
One possible solution is to fetch the records into an array and use foreach to iterate through it:
$rows = $sqlimpressora->fetchAll();
foreach ($rows as $prod) {}
foreach ($rows as $prod) {}

Convert PHP MySQL to PHP PDO

I am trying to convert this PHP MySQL code from:
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["primary_cat"])) {
$query ="SELECT DISTINCT `secondary_cat` FROM student5 WHERE primary_cat = '" . $_POST["primary_cat"] . "'";
$results = $db_handle->runQuery($query);
?>
<option value="">Select State</option>
<?php
foreach($results as $state) {
?>
<option value="<?php echo $state["secondary_cat"]; ?>"><?php echo $state["secondary_cat"]; ?></option>
<?php
}
}
to PHP PDO as follows. I'm not sure what I am doing wrong. This is my code below.
$table = 'student5';
include('config.php');
if(!empty($_POST['primary_cat'])) {
$sqlQuerySecondaryCat = $dbh->query("SELECT DISTINCT secondary_cat FROM $table WHERE primary_cat = :primary_cat");
$sqlQuerySecondaryCat->execute(array(':primary_cat' => $_POST['primary_cat']));
?>
<option value="">Select State</option>
<?php
foreach($sqlQuerySecondaryCat as $secondaryCatRow) {
?>
<option value="<?php echo $secondaryCatRow["secondary_cat"]; ?>"><?php echo $secondaryCatRow["secondary_cat"]; ?></option>
<?php
}
}
I am getting the following error in my error_log PHP Warning: Invalid argument supplied for foreach()
First of all you need to use prepare, not query.
$sqlQuerySecondaryCat->prepare("SELECT .......
Secondly, you haven't done anything with the data stored in the object $sqlQuerySecondaryCat - you need to use fetch or fetchAll for the data.
$data = $sqlQuerySecondaryCat->fetchAll(PDO::FETCH_ASSOC);
foreach($data as $secondaryCatRow){
.... do something
Full code:
$table = 'student5';
include('config.php');
if(!empty($_POST['primary_cat'])) {
$sqlQuerySecondaryCat = $dbh->prepare("SELECT DISTINCT secondary_cat FROM $table WHERE primary_cat = :primary_cat");
$sqlQuerySecondaryCat->execute(array(':primary_cat' => $_POST['primary_cat']));
$rows = $sqlQuerySecondaryCat->fetchAll(PDO::FETCH_ASSOC); ?>
<option value="">Select State</option>
<?php foreach($rows as $secondaryCatRow) { ?>
<option value="<?php echo $secondaryCatRow["secondary_cat"]; ?>"><?php echo $secondaryCatRow["secondary_cat"]; ?></option>
<?php }
}

how to set the selected value tag <select> html from database in php?

I'm trying to create a drop down menu that will select a value that is stored in the database. here's the code :
require 'koneksi.php';
$sql_select = "SELECT * FROM supplier";
$hasil = mysql_query($sql_select);
if(!$hasil) {
echo "data supplier not found ".mysql_error();
}
$id = $_GET["id"];
$hasil2 = mysql_query("SELECT * FROM brg_supplier WHERE id_brg=".$id);
$data = mysql_fetch_array($hasil2);
if($hasil2) {
$supplier = $data['nama_supplier'];
}
<select name="supplier">
<option value="">---pilih supplier---</option>
<?php
while($baris = mysql_fetch_array($hasil)){
?>
<option value="<?php $baris['nama_supplier'] ?>" <?php if ($supplier==$baris['nama_supplier']) echo 'selected="selected"'; ?> > <?php echo $baris['nama_supplier']; ?> </option>;
<?php }?>
</select>
the problem is my code creates a dropdown with nothing selected. here's the screenshot : link
i've tried all the solutions in the stackoverflow. but the dropdown value still nothing selected. i know that it has to be something simple that i am missing but seriously i cannot figure it out. please anyone help, thanks!
I think the problem lies in this line:
<option value="<?php $baris['nama_supplier'] ?>" <?php if ($supplier==$baris['nama_supplier']) echo 'selected="selected"'; ?> > <?php echo $baris['nama_supplier']; ?> </option>;
You're missing an echo and it looks funny :/
Try instead:
<option <?php $val=$baris['nama_supplier']; echo "value='$val'"; if($supplier==$val) echo "selected='selected'>";echo $val;?> </option>;
Try this way..
$sel="select f.*,c.category from final f, category c where f.category_id=c.id and f.id='$id'";
$data=mysql_query($sel);
$res=mysql_fetch_assoc($data);
<select name="cat">
<?php
$sql = mysql_query("SELECT * FROM category");
while ($row = mysql_fetch_array($sql)){
if($row['id'] == $res['category_id']){
echo '<option value="'.$row['id'].'" selected="selected">'.$row['category'].'</option>';
}else{
echo '<option value="'.$row['id'].'">'.$row['category'].'</option>';
}
}
?>
</select>
Try this out
require 'koneksi.php';
$sql_select = "SELECT * FROM supplier";
$hasil = mysql_query($sql_select);
if(!$hasil) {
echo "data supplier not found ".mysql_error();
}
$id = $_GET["id"];
$hasil2 = mysql_query("SELECT * FROM brg_supplier WHERE id_brg=".$id);
$data = mysql_fetch_array($hasil2);
if(mysql_num_rows($hasil2) > 0) {
$supplier = $data['nama_supplier'];
}
<select name="supplier">
<option value="">---pilih supplier---</option>
<?php
while($baris = mysql_fetch_array($hasil)){
?>
<option value="<?php echo $baris['nama_supplier'] ?>" <?php if ($supplier==$baris['nama_supplier']) {echo 'selected="selected"';} ?> > <?php echo $baris['nama_supplier']; ?> </option>;
<?php }?>
</select>
<option value="<?php $baris['nama_supplier'] ?>
should be
<option value="<?php echo $baris['nama_supplier'] ?>
I spent some time trying to find the best solution for this, and came up with a tiny little jQuery code.
First of all you should be using PDO or mysqli instead of mysql, since it's deprecated. Let's assume you've fixed that.
Inside the <form> tag, add an <input type="hidden"/> so that it can storage your database value, for example:
HTML
<form>
<input id="valueFromDatabase" type="hidden" value="<?php echo $stringFromDB ?>"/>
</form>
Note: in this case, $stringFromDB is a variable that holds your query's return from DB.
So now we have the value of our database inside our HTML code. Now we just need to check if any of the options inside the <select> tag is equal to this value. We'll be doing it with jQuery:
jQuery
$( document ).ready(function() {
$('option').each(function(){
if (this.value == $('#valueFromDatabase').val()){
this.setAttribute('selected', 'selected');
}
});
});
What's happening here? We are telling to jQuery to analyze all the <option> tags in the HTML and compare its value with our value from database; if its equal, we add the selected attribute to the equivalent <option>.
You can it working here (used a calendar example).
Hope that helps!

i am trying to display productname from newproduct mysql table into combobox. The following code is executing but its displaying a blank

**<html>
<body>
<form name="call">
<select name="category">
<option>Select a category</option>
<?php
mysql_connect("localhost","root","");
mysql_select_db("shenvel");
$category = "SELECT productname FROM newproduct";
//retrieving product name alone from newproduct
$query_result = mysql_query($category);
while($result = mysql_fetch_assoc($query_result))
{
?>
<option value = "<?php echo $result['productname']?>"><?php echo $result['productname']?></option>
//the above code displays the combo box with one empty space as output.
**
change fetch records using mysql_fetch_array()
while($result = mysql_fetch_array($query_result))
{
*********
}
And try it..
Try this
<select name="category">
<option>Select a category</option>
<?php
mysql_connect("localhost","root","");
mysql_select_db("shenvel");
$category = "SELECT productname FROM newproduct";
$query_result = mysql_query($category);
while($result = mysql_fetch_array($query_result))
{
?>
<option value = "<?php echo $result['productname']; ?>"><?php echo $result['productname']; ?></option>
<?php
}
?>
</select>
try this:
<html>
<body>
<form name="call">
<select name="category">
<option>Select a category</option>
<?php
mysql_connect("localhost","root","");
mysql_select_db("shenvel");
$category = "SELECT productname FROM newproduct";
//retrieving product name alone from newproduct
$query_result = mysql_query($category);
while($result = mysql_fetch_array($query_result))
{
?>
<option value = "<?php echo $result['productname']?>"><?php echo $result['productname']?></option>
Your while loop is being fully executed in the first <?php ... ?> snippet. The syntax you used for your while loop will not execute across multiple php code snippets.
Try echoing out your option HTML code and thus having only one php code snippet.
<html>
<body>
<form name="call">
<select name="category">
<option>Select a category</option>
<?php
mysql_connect("localhost","root","");
mysql_select_db("shenvel");
$category = "SELECT productname FROM newproduct";
//retrieving product name alone from newproduct
$query_result = mysql_query($category);
while ($result = mysql_fetch_assoc($query_result)) {
echo '<option value = "', $result['productname'], '">', $result['productname'], '</option>';
}
?>

sql queries results from parents

need some help completing my code what it does is searches in the tables of my DB for all the sections pointing to the parent_sections=2 and then prints the results in a select tag i would like some help with the sql query to check if the parent_sections=2 has child's and if so to print them with a optgroup style anyway please check the images below they explain what i need.
PHP & SQL CODE:
<?php
include('../application_top.php');
function get_title_sections($id){
$sections_query = tep_db_query("select title_sections_detail from sections_detail where id_sections = '" . (int)$id . "' and id_lang='0' order by title_sections_detail");
$result='';
while ($sections = tep_db_fetch_array($sections_query)) {
$result=$sections['title_sections_detail'];
}
return $result;
}
?>
<form>
<select name="sections">
<option selected="selected" value="">Please choose an option</option>
<?php
$sections_sql=tep_db_query("select p.id_sections, d.title_sections_detail as title from sections p, sections_detail d where p.id_sections=d.id_sections and d.id_lang='0' and p.status_sections='1' and p.parent_sections='2' order by d.title_sections_detail asc");
while ($sections = tep_db_fetch_array($sections_sql)) {
$id_sec=$sections['id_sections'];
$title_sec=get_title_sections($id_sec);
?>
<option value="<?php echo $id_sec ?>" ><?php echo $title_sec ?></option>
<?php }?>
</select>
</form>
SQL table sections:
SQL table sections_detail:
RESULT:
RESULT I NEED:
Here is my solution:
<?php
include('../application_top.php');
function load_sections($id_parent) {
$sections_sql = tep_db_query("select p.id_sections, d.title_sections_detail as title
from sections p, sections_detail d
where p.id_sections=d.id_sections
and d.id_lang='0'
and p.status_sections='1'
and p.parent_sections='".$id_parent."'
order by d.title_sections_detail asc");
$sect = array();
while ($sections = tep_db_fetch_array($sections_sql)) {
$sections['childs'] = load_sections($sections['id_sections']);
$sect[] = $sections;
}
return($sect);
}
function print_section($sect) {
if (count($sect['childs'])) {
echo "<optgroup label=\"".htmlentities($sect['title'])."\">\n";
foreach ($sect['childs'] as $subsect) {
print_section($subsect);
}
echo "</optgroup>\n";
} else {
echo "<option value='".$sect['id_sections']."'>".htmlentities($sect['title'])."</option>\n";
}
}
?>
<!DOCTYPE html>
<html>
<body>
<form>
<select name="sections">
<option selected="selected" value="">Please choose an option</option>
<?php foreach (load_sections(2) as $sect) print_section($sect); ?>
</select>
</form>
</body>
</html>
Be aware that nesting opgroups is not allowed; only one optgroup level is allowed, as you can also read here.

Categories