My question is: I want to show all SQL answers from a specific table inside the <select> using php.
I have tried to get it working, but without much success as it only shows one result.
<?php
error_reporting(E_ALL);
include 'connect.php';
include 'header.php';
set_time_limit(10);
$cat = $bdd->query('SELECT cat_id,cat_name,cat_description FROM categories');
$categories_list = $cat->fetch();
While ($categories_list = $cat->fetch()) {
$cat_name = $categories_list['cat_name'];
}
$cat->closeCursor();
echo '<form method="post" action="accès/create_topic_post.php">';
echo '<label for="sujet">Sujet :';
echo '<input type="text" name="sujet" id="sujet" required autofocus>';
echo '</label>';
echo '<label for="cat">Catégories :';
echo '<select name="topic_name">';
echo "<option value=\"".$cat_name."\" >$cat_name </option>";
echo '</select>';
echo '<input type="submit" value="Envoyer">';
echo '</form>';
?>
That's totally not the way to do it. Have a separation between PHP and HTML. And make sure you have the option echoed out inside the loop. Something like this:
<form method="post" action="accès/create_topic_post.php">
<label for="sujet">Sujet :
<input type="text" name="sujet" id="sujet" required autofocus>
</label>
<label for="cat">Catégories :
<select name="topic_name">
<?php
// Loop it here.
while ($categories_list = $cat->fetch()) {
$cat_name = $categories_list['cat_name'];
echo "<option value=\"".$cat_name."\" >$cat_name </option>";
}
?>
</select>
</label><!-- You forgot this -->
<input type="submit" value="Envoyer" />
</form>
There are two approach to achieve your desired output.
Approach One:
Store cat_name in a new array and use it in your HTML or anywhere, where you want to use.
<?php
$cat_name = array();
while($categories_list = $cat->fetch()) {
$cat_name[] = $categories_list['cat_name'];
}
?>
<select name="topic_name">
<?php
foreach ($cat_name as $key => $value) {
?>
<option value="<?=$value?>" ><?=$value?> </option>
}
?>
</select>
Approach 2:
<?php
while ($categories_list = $cat->fetch()) {
?>
<option value="<?=$categories_list['cat_name']?>" ><?=$categories_list['cat_name']?> </option>
<?php
}
?>
Whats wrong with your code:
$cat_name = $categories_list['cat_name']; this will only store the last value of your query, you must need to store the value in an array or use <option> inside the while() loop.
You keep replacing cat_name every time you read data from the SQL server. You need to store it in an array
<?php
error_reporting(E_ALL);
include 'connect.php';
include 'header.php';
set_time_limit(10);
$cat = $bdd->query('SELECT cat_id,cat_name,cat_description FROM categories');
//$categories_list = $cat->fetch(); This line discards a row of data
$cat_names = array(); //array for category names
While ($categories_list = $cat->fetch()) {
//Add newest 'cat_name' to the array
$cat_names[] = $categories_list['cat_name'];
}
$cat->closeCursor();
echo '<form method="post" action="accès/create_topic_post.php">';
echo '<label for="sujet">Sujet :';
echo '<input type="text" name="sujet" id="sujet" required autofocus>';
echo '</label>';
echo '<label for="cat">Catégories :';
echo '<select name="topic_name">';
//Loop and read back each category name
foreach ($cat_names as $cat_name){
echo "<option value=\"".$cat_name."\" >$cat_name </option>";
}
echo '</select>';
echo '<input type="submit" value="Envoyer">';
echo '</form>';
?>
You don't have to loop over results manually, as PDO has a function that can do it for you already, called fetchAll(). You have to use it instead of fetch() if you want to get an array of rows.
However, beside it, you need to learn PHP and programming in general. Because your current code makes little sense. To output an array, you have to use a loop:
$cat = $bdd->query('SELECT cat_name FROM categories');
$categories_list = $cat->fetchAll(PDO::FETCH_COLUMN); // here it is
echo '<form method="post" action="accès/create_topic_post.php">';
echo '<label for="sujet">Sujet :';
echo '<input type="text" name="sujet" id="sujet" required autofocus>';
echo '</label>';
echo '<label for="cat">Catégories :';
echo '<select name="topic_name">';
foreach ($categories_list as $cat_name)
{
echo "<option value='$cat_name'>$cat_name</option>";
}
echo '</select>';
echo '<input type="submit" value="Envoyer">';
echo '</form>';
Move the fetch loop to the output section of your code.
So instead of this:
echo "<option value=\"".$cat_name."\" >$cat_name </option>";
move the loop so it will look like this:
While ($categories_list = $cat->fetch()) {
$cat_name = $categories_list['cat_name'];
echo "<option value=\"".$cat_name."\" >$cat_name </option>";
}
Use while loop while you're outputting the category in select option.
Like this,
While ($categories_list = $cat->fetch()) {
echo "<option value=\"".$categories_list['cat_name']."\" >$categories_list['cat_name'] </option>";
}
Related
I need to use nested foreach for dependent checkboxes.
<input type="checkbox" name="all[]" value="<?php echo $row_bus_details['busid'];?>" >
<?php
$book_side_result = mysqli_query($db,"select * from advt_sides");
while($book_side_row=mysqli_fetch_array($book_side_result))
{
?>
<input type="checkbox" name="bookingside[]" value="<?php echo $book_side_row['advt_side_id']; ?>" id="<?php echo $book_side_row['advt_side']; ?><?php echo $row_bus_details['busid'];?>" > <?php echo $book_side_row['advt_side']; ?><br/>
<?php } ?>
I need to loop the selected values of second checkbox if the first checkbox is selected.
I wrote the code like
$i = 0;
$busid = isset($_POST['all']) ? $_POST['all'] : array();
foreach ((array)$busid as $item) {
if(!empty($_POST['bookingside'])) {
foreach($_POST['bookingside'] as $side) {
$sql_book_side=mysqli_query($db,"INSERT INTO `advt_book_side`(bus_id,sides_id) VALUES ('$item','$side')");
$i++;
}
}
}
The result I need is just like the image below
You need to save data in serialize array from in data base like:
$sql_book_side=mysqli_query($db,"INSERT INTO advt_book_side(bus_id,sides_id) VALUES ('$item',serialize(array('left'=>1,'right'=>1,'back'=>0)))");
Print check box with check uncheck using below code
$book_side_result = mysqli_query($db,"select * from advt_sides");
while($book_side_row=mysqli_fetch_array($book_side_result))
{
$array = unserialize($book_side_row['sides_id']);
foreach($array[0] as $side){
?>
<input type="checkbox" name="bookingside[]" value="<?php echo ($side)? $side:0; ?>">
<?php }
} ?>
<select id="rightsid" name="rightsid">
<?php
while($row=mysql_fetch_array($list)) {
$admno=$row["adm_no"];
$name=$row["name"];
?>
<option id="<?php echo $admno;?>" name="<?php echo $admno;?>"><?php echo $admno;?> <?php echo $name;?></option>
<?php
}
?>
<input type="submit" value="Show Rights">
</select>
This is my code. When I take the value of select to next page, it is taking both name and admno but I want to take only admno but here in dropdown list. I want to display both but want to carry only one. How to do this?
Within option value, write $admo. Try this:
<?php
while ($row=mysql_fetch_array($list)) {
$admno = $row["adm_no"];
$name = $row["name"];
echo '<option id = "'.$admno.'" name = "'.$admno.'" value = "'.$admno.'" >' . $admno . $name . '</option>';
}
?>
Use value in option as below
<select id="rightsid" name="rightsid">
<?php
while($row=mysql_fetch_array($list)) {
$admno=$row["adm_no"];
$name=$row["name"];
?>
<option value="<?php echo $admno;?>" id="<?php echo $admno;?>" name="<?php echo $admno;?>"><?php echo $admno;?> <?php echo $name;?></option>
<?php
}
?>
</select>
<option id="<?php echo $admno;?>" value="<?php echo $admno;?>"><?php echo $name;?></option>
I want two <option> output form database by while loop and also need to receive it form $_POST[''] function but i am getting only one <option> output. double <option> not appears form these codes. what wrong i am doing here?
$q6 = mysql_query("SELECT * FROM menu");
echo '<form action="" method="post">'.'Need To Change <select name="tobechanged">';
while ($row = mysql_fetch_array($q6)) {
$menu_name = $row['menu_name'];
echo '<option value="'.$menu_name.'">'.$menu_name.'</option>';
}
while ($row = mysql_fetch_array($q6)) {
$menu_name2 = $row['menu_name'];
echo '<option value="'.$menu_name2.'">'.$menu_name2.'</option>';
}
echo '</select><br>
<input type="submit" name="pchange_submit" value="Change it">
</form>';
if (isset($_POST['pchange_submit'])) {
echo $_POST['tobechanged'];
}
$q6 = mysql_query("SELECT * FROM menu");
echo '<form action="" method="post">'.'Need To Change <select name="tobechanged">';
while ($row = mysql_fetch_array($q6)) {
$menu_name = $row['menu_name'];
echo '<option value="'.$menu_name.'">'.$menu_name.'</option>';
}
echo '</select><br>
<input type="submit" name="pchange_submit" value="Change it">
</form>';
if (isset($_POST['pchange_submit'])) {
echo $_POST['tobechanged'];
}
I am trying to use the $_GET value to load on the same page as my form instead of opening a new page. For example, the form is on my page "products.php" and I want the form to filter database results by type of product. So on submit, it should redirect to "products.php?type=tee".
If I manually type it in the address bar it works like a charm, but I can't get the form submit to load it.
Here's my code (Update: Here's the whole file, using require_once into a basic html5 template):
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
//Populate Items to Show
function populateItems($result){
while ($row = $result->fetch_assoc()){
if ($row['available']){
echo '<li><img src="', $row['image'], '" />';
echo '<ul>';
echo '<li><h1>', $row['product'], '</h1></li>';
echo '<li><h2>', $row['description'], '</h2></li>';
echo '<li><h3>$', $row['price'], '</h3></li>';
echo '</ul>';
echo '</li>';
}
}
$result->free();
}
//Create Item List
echo '<ul class="item">';
//Create Filter
echo '<li id="filter">';
if ($result = $conn->query("SELECT DISTINCT type FROM products")){
echo 'Filter Results By: <form method="GET" action="', $_SERVER['PHP_SELF'], '">';
echo '<select>';
echo '<option>Show All</option>';
while ($type = $result->fetch_assoc()){
echo '<option name="type" value="', $type['type'], '">', $type['type'], 's</option>';
}
echo '</select>';
echo '<input type="submit" value="Go" />';
echo '</form>';
}
echo '</li>';
//Find if Filter Exists
if (isset($_GET['type']) && $_GET['type'] != "" ){
$gettype = $_GET['type'];
$filtertype = $conn->query("SELECT * FROM products WHERE type='$gettype'");
$count = $filtertype->num_rows;
if ($count <= 0){
populateItems($conn->query("SELECT * FROM products"));
}else{
populateItems($conn->query("SELECT * FROM products WHERE type='$gettype'"));
}
}else{
populateItems($conn->query("SELECT * FROM products"));
}
//End Item List
echo '</ul>';
?>
I've searched all over and haven't found anything that quite answers my question... Any help would be appreciated!
You have your <option name="type" named when it should be the <select>.
<option> does not have named attributes.
Therefore, you need to remove name="type" from your <option> and change your <select> to <select name="type">
Change
<form method="post" action="">
To
<form method="get" action="">
You have to change the Method if you want to use GET! Like this:
...<form method="get" action="">...
Im a newbie to this forum and have just started coding in php. Need some help. I have the following code
<?php error_reporting(-1);
require_once('/mysql/sql_connect.php');
$q = "SELECT pty.pty_profile_name AS profile FROM pty, users WHERE users.username = 'testaccount' ";
$r = #mysqli_query ($dbc, $q);
$results_array = array();
while($row = mysqli_fetch_assoc($r)) {
array_push($results_array, $row);
echo "<pre>"; print_r($results_array); echo "</pre>"; }
?>
<p>
<form method="post" action="foreach2.php">
<label for="Property Select" class="title">Select Property</label>
<select name="pty_select" >
<?php foreach($results_array as $key => $value){ ?>
<option value="<?php echo $key; ?>"><?php echo $value['profile']; ?></option>
<?php } ?>
</select>
<input type="submit" name="Submit" />
</form>
<?php
if (isset($_POST['Submit'])) {
echo "<pre>"; echo ($_POST['pty_select']); echo "</pre>"; } ?>
The output I get is correct, but it displays the key, eg, 0 or 1 or 2, based on what I select in the form. I need the value output. Eg 0 = Emerton, it outputs "0" instead of Emerton.
If I echo $value['profile'] instead of pty_select, I get the last result of the query all the time. Which in this example would be 2, which is Ambarvale as I believe it just chooses the last row output of the query.
I hope I've made sense. Thanks in advance.
It will obviously echo the key, as you assigned the value of options as $key
if you need the options in the $_POST['pty_select'] use this:
<select name="pty_select" >
<?php foreach($results_array as $key => $value){ ?>
<option value="<?php echo $value['profile'];?>"><?php echo $value['profile']; ?></option>
<?php } ?>
</select>
You mean you need the value what you have used to display it.
Then,
Change to :
<option value="<?php echo $value['profile']; ?>">
<?php echo $value['profile']; ?>
</option>
And now let's go to ideal world :)
Build data pairs database_id => name for options:
$q = "SELECT pty.id, pty.pty_profile_name AS profile FROM pty, users
WHERE users.username = 'testaccount'";
$r = mysqli_query($dbc, $q);
$values = array();
while($r = mysqli_fetch_row($r)) {
$values[$r[0]] = $r[1];
}
Never use # when working with database, why do you want to suppress errors instead of preventing/handling them?
Now you have real database IDs and respective values (in general, using unique IDs are better... if nothing else they have greater entropy - more efficient search). And sice displaying select box is really common in webs, lets:
function selectbox( $values = array(), $attributes = array(), $selected_value = null)
{
// Header
echo '<select';
foreach( $attributes as $key => $val){
echo ' ' . htmlspecialchars($key) . '="' . htmlspecialchars( $val) . '"';
}
echo '>';
// Values
foreach( $values as $key => $val){
echo '<option value="' . htmlspecialchars( $key) .'"';
if( $key === $selected_value){
echo ' selected="selected"';
}
echo '>' . htmlspecialchars( $val) . '</option>';
}
echo '</select>';
}
And now usage :)
<form method="post" action="foreach2.php">
<label for="Property Select" class="title">Select Property</label>
<?php selectbox( $values, array( 'name' => 'pty_select')); ?>
<input type="submit" name="Submit" />
</form>
And what to do with it then?
$id = (int)(isset( $_POST['pty_select']) ? $_POST['pty_select'] : 0);
$name = null;
if( $id && isset( $values[$id])){
$name = $values[$id];
}
Give
<option value="<?php echo $value['profile']; ?>"><?php echo $value['profile']; ?></option>
instead of
<option value="<?php echo $key; ?>"><?php echo $value['profile']; ?></option>
if (isset($_POST['Submit'])) {
echo "<pre>"; echo ($_POST['pty_select']); echo "</pre>"; } ?>
Change it to something like
if(isset($_POST['Submit'])) {
echo $results_array[$_POST['pty_select']]['profile'];
}
Or alternatively use profile option value.