Prepopulate a dropdown menu with multiple options from a MySQL database - php

Newbie here... I tried to adapt my code from here
The list is populated properly but I can't get it to pre-select. What am I doing wrong? Thanks in advance!
$q = "SELECT cat_id FROM category_user WHERE cat_id=$d";
while ($row = mysqli_fetch_array($q)) {
$cat = (int)$row['cat_id'];
}
$q = "SELECT cat_id, cat FROM category";
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r)> 0) {
while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) {
echo "<option value=\"$row[0]\"";
$selected = '';
$cid=(int)$row[0];
if ($cid=$cat) {
$selected='selected="selected"';
echo $selected;
echo ">$row[1]</option>\n";
}else{
//Check for stickyness
if (isset($_POST['category'])&&($_POST['category']== $row[0]))
echo 'selected="selected"';
echo ">$row[1]</option>\n";
}
}
}
category
---------------
|cat_id | cat |
---------------
category_user
-------------------------
|cu_id | user_id | cat_id|
-------------------------

Why overcomplicate the code. You can try something like this
<?php
$result = mysqli_query($dbc, "SELECT cat_id, cat FROM category");
if ($result) {
echo "<select name='whatever_you_want'>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='{$row[0]}'";
if (intval($row[0]) == intval($cat_id)) {
echo " selected";
}
echo ">{$row[1]}</option>";
}
echo "</select>";
}
?>

if($cid=$cat){
should be
if($cid==$cat){
and
$cid=(int)$row[0];
(int) is unnecessary because string to int are compared automatically.

Figured it out. the foreach loop preselects everything for the dropdown menu. The problems were mostly getting the array from the mysql table to iterate as selected. The last piece of the puzzle were the brackets [] after $cats.
Thanks for your help, and sorry I wasn't very clear on what I was trying to accomplish. My bad.
<p><select class=\"box\" name=\"wkType[]\" multiple=\"multiple\">";
$q = "SELECT cat_id FROM category_user WHERE user_id=$d";
$r = mysqli_query ($dbc, $q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$cats[]=$row['cat_id'];
}
$q = "SELECT cat_id, cat FROM category";
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r)> 0) {
while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) {
echo "<option value=\"$row[0]\"";
foreach ($cats as $key =>$cat) {
if ($row[0]==$cat){
echo 'selected="selected"';
//Check for stickyness
if (isset($_POST['category'])&&($_POST['category']== $row[0]))
echo 'selected="selected"';
}
}
echo ">$row[1]</option>\n";
}
}else{
echo '<p>Please select a category.</p>';
}
echo "</select></p>";

Related

Populate dropdown from database and set default value

Right now I have a working solution for populating an HTML <select>/<option>-dropdown with the content through PHP/MYSQLI from my database: listoption.
The database:
DATABASE NAME:
# listoption
TABLES:
# ID INT(11) *Primary AI
# listoption_item VARCHAR(255)
Here's the other code (not the mysqli connect but everything afterwards..)
<?php
$result = $mysqli->query("select * from listoption");
echo "<select id='list' name='list'>";
while ($row = $result->fetch_assoc()) {
$listoption_item = $row['listoption_item'];
echo '<option value="'.$listoption_item.'">'.$listoption_item.'</option>';
}
echo "</select>";
?>
But the problem is now that I want to have one of these options that are populated through that query to be selected. And the option to be selected should be determed by a parameter in the URL, for example: index.php?id=1.
So now I need to somehow add a IF/ELSE and a $_GET['id']; into the code to make it identify if the ID from the database is the same as the populated item and then set it to selected.
Any idéas? Thanks!
You can do that like given below:
<?php
$result = $mysqli->query("select * from listoption");
$id = ($_GET['id'])? $_GET['id'] : '';
echo "<select id='list' name='list'>";
while ($row = $result->fetch_assoc()) {
$listoption_item = $row['listoption_item'];
$sel = ($id == $row['id'])? 'selected="selected"':'';
echo '<option value="'.$listoption_item.'" '.$sel.'>'.$listoption_item.'</option>'; // $sel will deside when to set `selected`
}
echo "</select>";
?>
You can rewrite the code as follows:
<?php
$id = $_GET['id'];
$select = "";
$result = $mysqli->query("select * from listoption");
echo "<select id='list' name='list'>";
while ($row = $result->fetch_assoc()) {
$row_id = $row['ID'];
if($row_id == $id){
$select = "selected";
}
$listoption_item = $row['listoption_item'];
echo '<option value="'.$listoption_item.'" selected="'.$select.'">'.$listoption_item.'</option>';
}
echo "</select>";
?>
Use the following code:-
<?php
$selectedId = isset($_GET['id'])?$_GET['id']:0;
$result = $mysqli->query("select * from listoption");
echo "<select id='list' name='list'>";
while ($row = $result->fetch_assoc()) {
$listoption_item = $row['listoption_item'];
echo '<option value="'.$listoption_item.' .(($selectedId>0)?:" selected ":"").'">'.$listoption_item.'</option>';
}
echo "</select>";
?>

Sort multi query array for a drop down menu

I have to relations: one with the times and one where the selected times go in after submitting a form. I'm trying to create a dropdown menu, which should be sorted. If a time slot is already occupied is should still show up in the drop down, but as disabled. E.G. 9 , 10: occupied, 11... and so on.
At the moment the occupied slots are at the bottom of the menu. How can I achieve, that they appear where they should be.
Here is my code so far:
$query = "SELECT stunde FROM zeiten WHERE buchbar = 2 and
NOT EXISTS (SELECT *
FROM raumbuchung
WHERE zeiten.stunde =
raumbuchung.zeitanfang and belegt = 'belegt');
SELECT zeitanfang, belegt from
raumbuchung where belegt = 'belegt'";
echo "Beginn der Veranstaltung: ";
echo "<select name='time' id='t1'>";
if (mysqli_multi_query($conn, $query)) {
do {
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_assoc($result)) {
if ($row[belegt]) {
echo "<option value=$row[zeitanfang] disabled>$row[zeitanfang]: $row[belegt]</option>";
}
else {
echo "<option value=$row[stunde]>$row[stunde]</option>";
}
}
}
}
while(mysqli_next_result($conn));
}
Maybe someone can help me out?
First store them in separate arrays then populate as your wish.
$query = "SELECT stunde FROM zeiten WHERE buchbar = 2 and
NOT EXISTS (SELECT *
FROM raumbuchung
WHERE zeiten.stunde =
raumbuchung.zeitanfang and belegt = 'belegt');
SELECT zeitanfang, belegt from
raumbuchung where belegt = 'belegt'";
$occupied_arr = array();
$available_arr = array();
if (mysqli_multi_query($conn, $query)) {
do {
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_assoc($result)) {
if ($row['belegt']) {
$occupied_arr[] = $row;
}
else {
$available_arr[] = $row;
}
}
}
}
while(mysqli_next_result($conn));
}
echo "Beginn der Veranstaltung: ";
echo "<select name='time' id='t1'>";
foreach ($available_arr as $key => $value) {
echo "<option value=".$value['stunde'].">".$value['stunde']."</option>";
}
foreach ($occupied_arr as $key => $value) {
echo "<option value=".$value['zeitanfang']."disabled>".$value['zeitanfang'].": ".$value['belegt']."</option>";
}
echo "</select>";

Get data from category with php mysql

I try to get data from category using mysql and php.
Sql Structure:
Category
-cat_id
-name
Date
-id
-url
-category
Php code:
<?php
$sql = "select * from category";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0)
{
while ($row = mysql_fetch_assoc($result))
{
echo '<option value="'.$row["cat_id"].'">'.$row["name"].'</option>';
}
}
$sql = "select * from date WHERE category='1'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0)
{
while ($row = mysql_fetch_assoc($result))
{
echo '.$row["url"].';
}
}
?>
when i select the category the data is not listed.
Any idea?
Try this Code . Just removed single quotations
$sql = "select * from date WHERE category='1'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0)
{
while ($row = mysql_fetch_assoc($result))
{
echo $row["url"];
}
}
May this will work:
PHP Code
<?php
$sql = "select * from category";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0)
{
while ($row = mysql_fetch_assoc($result))
{
echo '<select id="category" name="category">';
echo '<option value="'.$row["cat_id"].'">'.$row["name"].'</option>';
echo '</select>';
}
}
$sql = "select * from date WHERE category='1'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0)
{
while ($row = mysql_fetch_assoc($result))
{
echo 'url is: '.$row["url"];
}
}
?>
Try this
$sql = "select * from date WHERE category='1'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0)
{
while ($row = mysql_fetch_assoc($result))
{
echo $row["url"];
}
}
if you want result with in single quotes
$sql = "select * from date WHERE category='1'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0)
{
while ($row = mysql_fetch_assoc($result))
{
echo "'".$row["url"]."'";
}
}
Please avoid mysql_* because the mysql_* functions have been removed in PHP7. Use MySQLi instead.
PHP + Mysql :
<?php
$sql = "select * from category";
$result = mysql_query($sql);
echo "<select name='category'>";
if(mysql_num_rows($result) > 0)
{
while ($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row["cat_id"].'">'.$row["name"].'</option>';
}
}
echo "</select>";
if(!empty($_POST['category'])) {
$category_id = $_POST['category'];
$sql = "select * from date WHERE category = '".$category_id."'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result))
{
echo '.$row["url"].';
}
}
}
?>
PHP + Mysqli
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "select * from category";
$result = $conn->query($sql);
echo "<select name='category'>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<option value="'.$row["cat_id"].'">'.$row["name"].'</option>';
}
}
echo "</select>";
if(!empty($_POST['category'])) {
$category_id = $_POST['category'];
$sql = "select * from date WHERE category = '".$category_id."'";
$result = $conn->query($sql);
if($result->num_rows > 0) {
while ($row = $result->fetch_assoc())
{
echo '.$row["url"].';
}
}
}
$conn->close();
?>
Nothing changed.
I'm using this code:
<?php
$sql = "select * from category";
$result = mysql_query($sql);
echo "<select name='category'>";
if(mysql_num_rows($result) > 0)
{
while ($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row["cat_id"].'">'.$row["name"].'</option>';
}
}
echo "</select>";
if(!empty($_POST['category'])) {
$sql = "select * from date WHERE category = '1'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result))
{
echo $row["url"];
}
}
}
?>
If i delete if condition the data is listed but all the time.

PHP: How to call option value in if statement?

I have this drop down list
echo "<select name='subcat'><option value=''>Select one</option>";
echo "<option value='all'>All</option>";
foreach ($dbo->query($quer) as $noticia) {
echo "<option value='$noticia[id]'>$noticia[sub_category]</option>";
}
What i want is to have 2 options, is to show "all" or one specific sub category from database
Here is my current code:
if($_POST['subcat'] == $subcat) {
$query = "Select ... where subcat = '".$subcat."'" }
else{
$query = show all;
My problem is that when I choose the dropdown value ALL, is doesn't go to else but still in the $subcat. How do I call
<option value='$noticia[id]'>
I try:
if($_POST['subcat'] == $noticia[id]
but not working..
Break your query up, depending on the value of $_POST['subcat']
$query = "Select ... ";
if($_POST['subcat'] != 'all') {
$query .= " where subcat = '".$subcat."'";
}
$query .= "...";
if($_POST['subcat'] == 'all') {
$query = show all;
else{
$query = "Select ... where subcat = '".$subcat."'" }
}

Why does this query show only one result?

The query I have below will only show me one result even if there are multiple matching entries (completely or partially matching). How do I fix it so it will return all matching entries:
//$allowed is a variable from database.
$sql = "SELECT `users`.`full_name`, `taglines`.`name`, `users`.`user_id` FROM
`users` LEFT JOIN `taglines` ON `users`.`user_id` = `taglines`.`person_id`
WHERE ( `users`.`user_settings` = '$allowed' ) and ( `users`.`full_name`
LIKE '%$q%' ) LIMIT $startrow, 15";
$result = mysql_query($sql);
$query = mysql_query($sql) or die ("Error: ".mysql_error());
$num_rows1 = mysql_num_rows($result);
if ($result == "")
{
echo "";
}
echo "";
$rows = mysql_num_rows($result);
if($rows == 0)
{
}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{
$person = htmlspecialchars($row['full_name']);
}
}
}
print $person;
Because your overwriting $person on each iteration.
Hold it in a $person[] array if your expecting more then one. Then loop through it with a foreach loop when you intend to output.
Not related but your also querying twice, you only need 1 $result = mysql_query($sql);
Update (Simple Outputting Example):
<?php
$person=array();
while($row = mysql_fetch_array($query)){
$person[] = array('full_name'=>$row['full_name'],
'email'=>$row['email'],
'somthing_else1'=>$row['some_other_column']);
}
//Then when you want to output:
foreach($person as $value){
echo '<p>Name:'.htmlentities($value['full_name']).'</p>';
echo '<p>Eamil:'.htmlentities($value['email']).'</p>';
echo '<p>FooBar:'.htmlentities($value['somthing_else1']).'</p>';
}
?>
Or an alternative way to is to build your output within the loop using concatenation.
<?php
$person='';
while($row = mysql_fetch_array($query)){
$person .= '<p>Name:'.$row['full_name'].'</p>';
$person .= '<p>Email:'.$row['email'].'</p>';
}
echo $person;
?>
Or just echo it.
<?php
while($row = mysql_fetch_array($query)){
echo '<p>Name:'.$row['full_name'].'</p>';
echo '<p>Email:'.$row['email'].'</p>';
}
?>

Categories