how to get data from database mysql in form select html? - php

i was trying to show data from database into tag> select html. here is the code :
<?php
require 'koneksi.php';
$sql_select = "SELECT nama_supplier FROM supplier";
$hasil = mysql_query($sql_select);
if(!$hasil) {
echo "data not found ".mysql_error();
}
mysql_close();
?>
<div class="par control-group">
<label class="control-label" for="supplier">Supplier</label>
<select name="supplier" class="uniformselect">
<?php
while($baris = mysql_fetch_array($hasil)){
echo "<option value='$baris'>".$baris."</option>";
}
?>
</select>
</div>
the problem is, the output doesn't show the option value from database. the output only print 'array'. here is screenshot : image . i know that it has to be something simple that i am missing but seriously i cannot figure it out. please anyone help, thanks!

You need to select a row from the $baris variable which stands as an array
echo $baris['Coulmn you want'];
If you don't the variable $baris will be equal to something like that. You need to select which column you want.
([id]->1,[name]->'user',...,['email']->a#a.com)

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.

Get variable from database table column into input field based selected option from option field

I have succesfully retrieved two columns from my table and displayed the result as options in a select tag, in my form.
The problem is I cannot display the data from a third column into an input field, which is also in the form, based on the selected option.
There is no issue with the database connection or retrieving the data for the options in the select tag.
Any help would be appreciated. The relevant code is below.
<div class="col-md-4 col-12 bottommargin-sm">
<label for="">Choose currency</label>
<select class="form-control" id="exampleFormControlSelect1">
<option value="">Choose currency...</option>
<?php
// Including DB connection file
include_once "config/config.php";
// Retrieving all columns from currency table
$result = mysqli_query($con, "SELECT * FROM currency_test");
// Loop printing options with country and currrency for all rows in currency table
while($row = mysqli_fetch_array($result)) {
print "<option>";
echo $row['country'] . " - " . $row['currency'];
print "</option>";
}
// Closing DB connection
mysqli_close($con);
?>
</select>
</div>
<div class="col-md-2 col-12 bottommargin-sm">
<label for="">Currency rate</label>
<input type="text" class="form-control" value="<?php echo $row['buy_rate'] ?>" readonly>
</div>
Additional Edit
I am now using the following code, still without any luck:
<div class="col-md-4 col-12 bottommargin-sm">
<label for="">Choose currency/label>
<select class="form-control" id="exampleFormControlSelect1">
<option value="default">Choose currency...</option>
<?php
// Including DB connection file
include_once "config/config.php";
// Retrieving all columns from currency table
$result = mysqli_query($con, "SELECT * FROM currency_test");
// Loop printing country, currrency, buy_rate and sell_rate for all rows in currency table
while($row = mysqli_fetch_array($result)) {
echo "<option value=".$row['currency']."> ".$row['country']. " - " .$row['currency']." </option>";
}
?>
</select>
</div>
<div class="col-md-2 col-12 bottommargin-sm">
<label for="">Currency rate</label>
<input type="text" class="form-control" value="<?php echo $row['buy_rate'] ?>" readonly>
</div>
<?php
// Closing DB connection
mysqli_close($con);
?>
As said before, you have a result SET in your while-loop above, but you want the input field only to contain a single value: the buy-rate of the selected currency. If I guessed right and this is what you want, this will not work like this.
If you want to test it and just retrieve only a single value in your while-loop, also your input field gets filled with the correct buy-rate.
You can do it with or without JavaScript, but you need a second statement to retrieve the buyrate you desire.
Further security suggestions: You should not use the include directives without __ DIR __ . Neither you should use "SELECT * ...". Better it is to name all the fields you want to retrieve.
You will have to have a statement for that selection. (Hint: Also in the tag you will have to have a value attribute set) Also your select needs a name if you use a submit button..
Now when you submit the form you can query the database and show the correct record.
If you dont want to use a submit button and have the value in the textfield change by selection, you will need javascript.
So what I see :
1) No name in select tag
<select class="form-control" id="exampleFormControlSelect1">
There is no name attribute. So after posting the form, the server doesn't know the name of the variable.
2) No value
print "<option>";
You don't supply a value. So your server doesn't know the value (the user selected) after posting the form.
This is the proper way for a select tag : https://www.w3schools.com/tags/tag_select.asp

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

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

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.

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