populating a value field of a combo-box from a MySQL query - php

This question is relating to a problem that a previous questions answer yielded! (as is the way)
I have set up a simple script to access a MySQL database and populate a dropdown combobox with usernames, but it wont accept the values from my php, it creates the names however so its some form of syntax error but not one that causes a crash.
<?php
# parameters for connection to MySQL database
$hostname="";
$database="";
$ausername="";
$apassword="";
mysql_connect ("$hostname","$ausername","$apassword");
mysql_select_db ("$database");
$query = mysql_query("SELECT DISTINCT username FROM dbusers") or die(mysql_error());
?>
<div id="select_users" style="position:absolute;width:466px;height:108px;">
<form name="select_user" method="POST" action="./page5.php" id="Form1">
<div id="select_a_user" style="position:absolute;left:0px;top:20px;width:100px;height:20px;z-index:11;text- align:left;">
<span style="color:#000000;font-family:Arial;font-size:15px;">Select User</span></div>
<select name="users[]" multiple = "multiple" id="users" style="position:absolute;left:93px;top:15px;width:200px;height:75px;z-index:12;">
<option value="test"> Select a user</option>
<?php
while($row = mysql_fetch_assoc($query)){
$username = $row["username"];
?>
<option value= <?php $username ?> > <?php echo $username ?> </option>
<?php
}?>
</select>
<input type="submit" id="Button1" name="" value="Submit" style="position:absolute;left:93px;top:100px;width:96px;height:25px;z-index:13;">
</form>
</div>
the section
<option value= <?php $username ?> > <?php echo $username ?> </option>"
is what is causing the issue i think as its not assigning the variable value
Im using the following script to debug and display what is supposed to be inside the array after POST
<?php
if(isset($_POST['users']))
{
$ausers = $_POST['users'];
if(!isset($ausers))
{
echo("<p>You didn't select any users!</p>\n");
}
else
{
$nusers = count($ausers);
echo("<p>You selected $nusers user: ");
for($i=0; $i < $nusers; $i++)
{
echo($ausers[$i] . " ");
}
echo("</p>");
}
}
?>
It will output the number of data files in the array but wont display their content, which after force echo'ing the variables has lead me to believe that the values of the array are all empty.
The end result of this selection is to store each entry of the array as a variable for another MySQL query if that any help with the correct code to achieve the result.
Thanks!

<option value= <?php $username ?>
^----you forgot 'echo' here
No echo, no output, and your generated html becomes
<option value=>foo</option>

I am not sure what the issue is here, sometimes when dealing with a database though it will create a multidimensional array. If this is the case you aren't actually looking at any values. To help you check try doing a var_dump on the variable to see everything about the data. It will even tell you if it is truly empty it should look like this:
echo var_dump($varName);
That should help you with debugging and maybe help you post some better information.

Related

insert while loop select option

this is my form. in heere i want to input data select option in while loop
<form method="post" action="process/input_penilaian_produk.php">
<div class="input">
<p>Produk</p>
<?php
$q="SELECT * FROM `produk`";
$qe=mysqli_query($koneksi,$q);
while ($de=mysqli_fetch_array($qe)) {
$id_produk=$de['id_produk'];
$nama_produk=$de['nama_produk'];
echo "
<select name=\"id_produk\">
<option value=\"".$id_produk."\">".$nama_produk."</option>
</select>
";
}
?>
<?php
$q="SELECT * FROM `kriteria`";
$qe=mysqli_query($koneksi, $q);
while ($de=mysqli_fetch_array($qe)) {
$id_kriteria=$de['id'];
$nama_kriteria=$de['nama_kriteria'];
echo "
<p>".$nama_kriteria."</p>
<select name=\"id_penilaian\">
";
$q1="SELECT * FROM `penilaian_kriteria` WHERE `id_kriteria`=\"".$de['id']."\"";
$qe1=mysqli_query($koneksi, $q1);
while ($de1=mysqli_fetch_array($qe1)) {
$id_penilaian=$de['id_penilaian'];
$id_kriteria=$de1['id_kriteria'];
$penilaian=$de1['penilaian'];
$bobot=$de['bobot'];
echo "
<option value=\"".$id_penilaian."\">".$penilaian."</option>
";
}
echo "
</select>
";
}
?>
<input class="btn_input" type="submit" value="input">
</div>
</form>
here's my code to insert.
this is the code to insert the data. what makes me confusing is, how can i insert same is into different table data
<?php
include("koneksi.php");
$id_produk=$_POST['id_produk'];
$id_penilaian=$_POST['id_penilaian'];
$q="INSERT INTO `penilaian_produk` VALUES('','$id_produk','$id_produk','','','','')";
$qe=mysqli_query($koneksi, $q);
if ($qe) {
header('location:../produk.php');
} else{
echo "gagal";
}
?>
i've been try this code and it works, no error. but when i check phpmysql, the data is empty. i don't know what to do to solve this problem
how can i insert loop while $id_penilaian into database?
how can i insert differnt id_penilaian into database in the same query?
please help me to solve this problem. Thank you
For the line,
$q="INSERT INTO penilaian_produk VALUES('','$id_produk','$id_produk','','','','')";
check into the database, that what kind of constraints you have applied on each column and also check the corresponding column datatypes, that you have used during table creation.
Might be this will be the problem here.

Populate Table from more than one drop-down list

I'm trying to populate a Table after a user picks options from a drop down list when this options are picked the table should be populated based on selected options. I'm not sure how can I get this done and I've searched for tutorias etc but nothing helped me. So I'll be glad if someone can help somehow for example with small test codes etc.
I'm using PHP and the options for the drop-down list come from a MySQL-Database so in summary a person will choose a user from Users-drop down list after that a another option from different drop down list and then there's also going to be a date filter after 1, 2 or all 3 are selected a table will be produced based on the selected values.
So far I've no code done because I have no idea how to do it but I guess I need to put all 3 dropdown lists in a form and after submission I should produce the table, but how can I have more than one <select> ..... </select> in a <form> and submit them all simultaneously.
What I've done so far (I know it's unsafe and that mysql_* doesn't exist anymore in PHP7) but please don't criticize it.
UPDATE
//Database query for User drop-down(DD) population.
$sqlDD = " SELECT DISTINCT `user` FROM `users` " ;
$resultDD = mysql_query($sqlDD);
//Database query for Status drop-down(DD) population.
$sqlDDStatus = " SELECT `status` FROM `status` WHERE `id` = 1 OR
`id` = 123 OR `id` = 182 OR `id` = 12 ";
$resultDDStatus = mysql_query($sqlDDStatus);
<form id="form1" name="form1" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<select name="userSelect">
<?php
while($rowDD = mysql_fetch_array($resultDD)):
echo "<option value='" . htmlspecialchars($rowDD['user']) ."'>" . htmlspecialchars($rowDD['user']) ."</option>"; ?>
<?php endwhile; ?>
</select>
<!-- Second DD-list in the same form -->
<select name="Status" style="max-width: 250px;" >
<?php
while($rowDDS = mysql_fetch_array($resultDDStatus)):
echo "<option value='" . htmlspecialchars($rowDDS['status']) ."'>" . htmlspecialchars($rowDDS['status']) ."</option>"; ?>
<?php endwhile; ?>
</select>
<input type="submit" name="submit" value='Find'/>
</form>
//Get the submited data
<?php if(isset($_POST['submit'])): ?>
<?php echo 'This is submitted ' . $_POST['submit']; ?>
<?php endif; ?>
I've added echo 'This is submitted ' . $_POST['submit'];
because i wanted to see what is submitted but all it get's echoed out is only
"Find".
Any ideas how can i get the data submitted from both 's in the form and populate a table based on it ?
UPDATE 2
After getting an answer from other users I saw that my forms handles the data correctly but my question now is how can I use the data from the Submitted DDL Form and populate a table with them? So far I've tried the following:
<?php if(isset($_POST['submit'])): ?>
<?php $result = mysql_query( "SELECT * FROM `users` WHERE `user` =
$_POST['userSelect'] AND (`id` = 1 OR `id` = 18)" );
?>
<?php endif; ?>
and then in the table
<table>
<?php while ($row = mysql_fetch_assoc($result)) :; ?>
<tr>
<td><?php echo $row['user']; ?></td>
<?php endwhile; ?>
</table>
But I just don't get any response when I try it. How can I fix my problem and get the wanted output?
EDIT
I think that i've found my mistake after some research im not able to test the code now but i'm almost positive that you can't use $_POST['userSelect'] in the Database query so i just need to assign $_POST['userSelect'] to some variable before i use it in the query. So far i've gotten useful 1 little useful tip...... so disappointed from stackoverflow .......
This is a basis HTML/PHP page for getting data from the backend to the frontend, this should get you started. Try to print the data (in the while loop on the HTML page).
<html>
<head>
<title></title>
</head>
<body>
<form action="dropdown.php" method="POST">
<select name='options'>
<option>option 1</option>
<option>option 2</option>>
<option>option 3</option>>
</select>
<input type="submit" value="Submit">
</form>
</body>
</html>
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}else{
if (!empty($_POST)){
if(!empty($_POST['options'])){
$option = $_POST['options'];
$query = "SELECT * FROM table WHERE option='$option'";
$res = $mysqli->query($query);
while($data = $res->fetch_assoc()){
//print data to HTML page
print_f('%s, $s\n', $data['firstname'], $data['lastname']);
}
}
}
}
?>
Your form is probably working, the reason you only get "Find" is because you are printing the value of the submit button.
To get an overview of your form data, try:
echo '<pre>';
print_r($_POST);
echo '</pre>';
You will get the other values of your form by using the name attribute of your <select> with $_POST:
echo $_POST['userSelect'];
echo $_POST['Status'];
By the way, you are using a deprecated extension (written here for example), it is recommended to use MySQLi or PDO (especially PDO is recommended). If you are working with PHP 7, mysql_connect won't work as it has been removed.
And I'm not sure the use of htmlspecialchars() is relevant on each database data you use.
PHP.net - print_r() (See also var_dump())
PHP.net - $_POST

Once I add session in edit form, I could not get selected values in dropdown

Once I add session in edit form, I could not get selected values in dropdown menu. I am using bootstrap framework. When I remove session from the same beginning it works.
edit.php file
<?php
session_start();
$car=$_POST['car']
?>
<form method="post" action="">
<div class=from-group>
<label for="exampleInputEmail1>Car</label>
<select class="form-group" name="car" id="car" value="<?php echo $car; selected?>">
<option value=<?php echo $car?> selected>
<?php cars()?>
</option>
</div>
</form>
I have created "cars" function in which I get values of all cars from database.
function cars(){
$link = new mysqli("", "", "", "");
$link = set_charset("utf8);
$sql = mysqli_query($link, "SELECT * FROM db_cars ORDER BY CarId")
echo '<option value=""> Choose car </option>'
while ($record = mysqli_fetch_array($sql)) {
echo '<option value = "'.$record['CarId']'"> . $record['CarName'].' </option>
}
}
Any help or advice is appreciated.
The select element has no name attribute, so it cannot be a successful control (i.e. submit any data).
The form has no submit button, so there is no obvious way for you to trigger the form submission. (You have to submit the form in a new HTTP request to the server to run the PHP and get the data from the user).
First, add the semicolons after every line when you use PHP. That can make a lot of troubles.
Second, some attributes have just one ("), like the label in the HTML.
Third, you are adding "something" called selected after echoing $car.
In the function cars() you are echoing without a semicolon (;) and just after doing a while() loop.
Check out all, you are missing very important and essential things
Also, I gonna guess this is not a "copy-paste" from your code, but if it's, you also are missing </select>

PHP Form - Highlight multiple selection for SQL query

I'm trying to keep multiple options selected in a dropdown form after being submitted but I can't get it to work. The options don't stay selected. I've seen answers for this using foreach() (Highlighting multiple selections on a form after submitting), however my data comes from a SQL query so I believe I need to use while() to loop through the rows. Any thoughts?
$id7 = $_REQUEST['id7'];// Interest Level
<?php
$getParameter_sql4 = 'SELECT Funds.[Interest Level] FROM Funds GROUP BY Funds.[Interest Level] ORDER BY Funds.[Interest Level]';
$getParameter4 = sqlsrv_query($conn,$getParameter_sql4);
?>
<form action="/Reports/FundStatistics.php" method="get">
<select name="id7[]" multiple size="4">
<?php while ($row4 = sqlsrv_fetch_array($getParameter4, SQLSRV_FETCH_ASSOC)) { ?>
<option <?php if (in_array($row4['Interest Level'],$id7)) { echo 'selected="selected"';}?> value="'<?php echo $row4['Interest Level']; ?>'"><?php echo $row4['Interest Level']; ?></option><?php }?>
</select>
<input type="submit" VALUE="Update" /></form>

How do I retrieve a selected value from a dynamically selection box

I would like to know how to retrieve a selected value from a dynamically selection box. If I get the selected value then I will store it into another variable that is located in another php file. This variable will help me in a sql query in postgresql.
//First php file
<form name="boton_alta_soniador" action="dar_alta_soniador.php" method="POST" autocomplete="off">
<div class="text-field">
Nombre de la asociacion
<? $strconn="dbname=postgres port=5432 host=127.0.0.1 user=xxx password=xxx";
$conn=pg_Connect($strconn);
$consulta="Select n_asociacion from asociacion";
$result=pg_query($conn,$consulta);
while($results [] =pg_fetch_object($result));
array_pop($results);?>
<select name="asociacion_seleccion" id="i_clave_asociacion">
<?php foreach ( $results as $option ) : ?>
<option value="<?php echo $option->i_clave_asociacion; ?>"><?php echo $option->n_asociacion; ?></option>
<?php endforeach; ?>
</select>
</div>
</form>
This is just the dynamically selection box. Then I want to store the selected value in this variable:
$ingresaAsociacion = pg_escape_string($_POST['asociacion_seleccion']);
So I can query the following statement:
$conocerIDasociacion = "SELECT N_ASOCIACION FROM ASOCIACION WHERE I_CLAVE_ASOCIACION='$ingresaAsociacion'";
I didn't want to use jQuery because the whole system is almost entirely made in PHP and HTML.
Please, any help is welcome and I'm all ears to everyone.
Cheers!
Looks like you're missing a Submit button.
You do not have to use AJAX at all, nor jQuery. You can submit your form and process the selection value as you see fit.
The selected value in the select Tag will be sent to dar_alta_soniador.php, and that file will process that data, using the exact code you wrote:
$_POST['asociacion_seleccion']
So, in dar_alta_soniador.php you will write that code:
$ingresaAsociacion = pg_escape_string($_POST['asociacion_seleccion']);
And then perform the query. You do not even have to worry about sending the data around in a session variable, POST does it for you already.
So everything should be OK in your code, or I may have misunderstood your question. Do you have an error message or get some inappropriate behavior?
Maybe the submit button is missing? I use a code like this:
For the select tag:
<div class="controls">
<select name="list_name">
<option>List</option>
<?php
foreach ($nucleos as $inner_array) {
$out = "<option>" . $inner_array['name'] . "</option>";
echo $out;
}
?>
</select>
</div>
And for the Submit button:
<div class="control-group">
<div class="controls">
<button type="submit" class="btn">Confirm</button>
<br/>
</div>
</div>
</form>
I am using bootstrap here for style, HTML and CSS. Nothing more.
Best wishes,
I found another solution:
<? $strconn="dbname=postgres port=5432 host=127.0.0.1 user=xxxx password=xxxx";
$conn=pg_Connect($strconn);
$consulta="Select n_asociacion from asociacion";
$result=pg_query($conn,$consulta);?>
<select name="asociacion_seleccion" id="i_clave_asociacion">
<?php
while($row=pg_fetch_assoc($result))
{echo "<option>{$row['n_asociacion']}</option>";}?>
</select>
The point is, whenever the user selects an option from the dyamically selection box, the value of the selection box is known if we call the value with pg_escape_string($_POST['NAME OF YOUR SELECTION BOX']);.
Thanks to all for your collaboration,my problem was resolved.

Categories