Inserting PHP in an HTML form to populate a selection - php

I have a HTML form that has a selection drop down. I would like to populate the drop down from my MySQL DB. The HTML form already has some java scripts to handle datepicker, and current date on one of the fields in the form.
I can code the form for the selection manually, but would like it to come from MySQL. the php I am using I put in it's own file name.php to make sure it worked correctly. I added some echo statements in the php to build the form, and the selection, and then populate the selection, and close it. this worked just fine as a standalone php.
When I append the php in the form under the selection definition, it does not populate the selection at all, it is left blank/empty. If I add some echo statments to output info in the format of a selection option, the first echo never shows up, and the subsequent echos show up, but any variable show up as the variable name.
<form id="form1" name="form1" method="post" action="/db_log.php">
Field:<select name="id">
<?php
require_once dirname(__FILE__) . '/db_connect.php';
$db = new DB_CONNECT();
$query="SELECT id, name FROM file order by name";
$result=mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$name =$row['name'];
echo "<option value=\"$id\"> $name </option>";
}
?>
</select><br />
</form>
the above yealds an empty select dropdown.
But this works great as a PHP file.
<?php
echo "<form id=\"form1\" name=\"form1\" method=\"post\" action=\"/db_log.php\">";
echo "Select:<select name=\"id\">";
require_once dirname(__FILE__) . '/db_connect.php';
$db = new DB_CONNECT();
$result=mysql_query("SELECT id, name FROM file order by name");
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$name =$row['name'];
echo "<option value=\"$id\"> $name </option>";
}
echo "</select><br />";
echo "</form>";
?>
If I add a echo to the HTML form one like a test echo before any other echo, it is ignored.
<form id="form1" name="form1" method="post" action="/db_log.php">
Field:<select name="id">
<?php
echo "<option value=\"1\"> Test-name </option>";
require_once dirname(__FILE__) . '/db_connect.php';
$db = new DB_CONNECT();
$query="SELECT id, name FROM file order by name";
$result=mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$name =$row['name'];
echo "<option value=\"$id\"> $name </option>";
}
?>
</select><br />
</form>
the only thing that shows up from this is the option to select $name

Based on this question and the previous questions and the comments you've gotten and made I'm going to guess that you're trying to run php from a .html file. You need to save your code (including the html) in a .php file for it to work.

A have a combo box that feeds from my mysql database.
I goes like this:
<tr>
<td>Emergency service</td>
<td><?php
$nombreEmergencia;
$idEmergencia;
$sql4 = "SELECT `idEmergencias`, `nombre` FROM `emergencias` WHERE 1";
$iterador = $conn->consulta($sql4);
echo '<select name="idEmergencia" id="idEmergencia" style="width:228px">
<option value="-1" selected>(please select:)</option>';
while($iterador->hayElemento()){
$nombreEmergencia = $iterador->getElemento("nombre");
$idEmergencia = $iterador->getElemento("idEmergencias");
echo '<option value="'.$idEmergencia.'">'.utf8_encode($nombreEmergencia).'</option>';
}
echo '</select>'; ?></td>
</tr>
as you can see you have to use an "iterator" variable with a function that checks the database for more elements and brings 'em.
That auxiliary function looks like this:
<?php
class Iterador{
private $ultimoDato;
private $id;
public function __construct($id){
$this->id = $id;
}
public function hayElemento(){
$dato = mysql_fetch_array($this->id);
$this->ultimoDato = $dato;
return !empty($dato);
}
public function getElemento($columnas){
return $this->ultimoDato[$columnas];
}
public function inicializar(){
$dato = mysql_fetch_array($this->id);
$this->ultimoDato = $dato;
}
public function hay(){
return !empty($this->ultimoDato);
}
public function siguiente(){
$dato=mysql_fetch_array($this->id);
$this->ultimoDato=$dato;
}
}
?>
hope this helps!!

Related

Saving a value from select option to database

So i am trying to insert some data in my database, unfortunatly it doesn't work as i hoped.
This is my index.php file here i made a little piece of php code to get the select options from my database(this works fine). But now i want people to select from the options in my database and store the selected option in another db table.
<?php
$query = "SELECT event_naam FROM events";
$result2 = mysqli_query($dbconn, $query);
$options = "";
while($row2 = mysqli_fetch_array($result2))
{
$options = $options."<option>$row2[0]</option>";
}
?>
<form class="inschrijven" method="POST" action="includes/inscscript.php">
<select name="iselect">
<?php echo $options;?>
</select><br><br>
<span>Uw Naam: </span><input type="text" name="inaam" placeholder="Naam"><br>
<span>Leeftijd: </span><input type="number" name="leeftijd"><br>
<span>Aantal Personen:</span><input type="number" name="personen"><br>
<input type="submit" name="inschrijven" value="Inschrijven!">
</form>
I have tried this, but it doesn't do anything it also doesn't give an error.
require_once 'connectie.php'; //Connection to Database File
$sql = "INSERT INTO inschrijven (inschrijf_event, inschrijf_naam, inschrijf_leeftijd, inschrijf_personen) VALUES
('".$_POST['iselect']."','".$_POST['inaam']."','".$_POST['leeftijd']."','".$_POST['personen']."')";
if ($dbconn->query($sql) === TRUE) {
header( "Location: ../index.php" );
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $dbconn->error."');</script>";
}
$dbconn->close();
This is my inscscript.php file
I tried searching for similair qeustions but couldn't find anything like this.
$query = "SELECT event_naam FROM events";
$result=mysqli_query($con,$query)
{
// Return the number of rows in result set
while($rowcount=mysqli_num_rows($result)){
echo "<option value='".$rowcount['event_naam']."'>".$rowcount['event_naam']."</option>
}
Include this php file to your html between select opend and closing tags

mysql php jquery hide show select

I know a little bit of PHP programming, but none of JQuery.
I have build a <select> dropdown menu with data from MySql db.
But now I want a button or something next to the <select> option, like a + sign or something that will give me a extra <select> option. And that this can come as many time as you want.
Ps. I'm sorry for my English.
Here is a picture of how I want this to be.
and then next you will get this.
And here is the code what I already have made.
<?php
$conn = new mysqli('localhost', 'username', 'password', 'database')
or die ('Cannot connect to db');
$result = $conn->query("select id, name from table");
echo "<html>";
echo "<body>";
echo "<select name='id'>";
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$id = $row['id'];
$name = $row['name'];
echo '<option value="'.$id.'">'.$name.'</option>';
}
echo "</select>";
echo "</body>";
echo "</html>";
?>
You can use check box instead of dropdown for multiple selection
while ($row = $result->fetch_assoc()) {
unset($id, $name);//use if you want
$id = $row['id'];
$name = $row['name'];
echo '<input name="city[]" type="checkbox" value="'.$name.'" />'.$name;
}

Print selected value from dynamic dropdown php mysql

I have the below code where I can get dynamic value into drop down list from mysql db but i can't print selected value when i click on submit button.
can anyone help me urgntly ?
<?php
include("includes/config.inc.php");
$query = "SELECT * FROM category";
$result = mysql_query ($query);
echo "<select class='turnintodropdown' name='CategoryID' ><option value=''>All</option>";
while($r = mysql_fetch_array($result)) {
echo "<option value=".$r['CategoryID'].">".$r['CategoryName']."</option>";
}
echo "</select>";
if (isset($_POST['submit'])) {
$selected_val = $_POST['CategoryID']; // Storing Selected Value In Variable
echo "You have selected :" .$selected_val; // Displaying Selected Value
}
?>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
If you want to preselect the selected value of the then you can use the following code. Also check your form method attrivute to see if it set to post (note that mysql_* functions are deprecated, it's better to use PDO using prepared statements).
while($r = mysql_fetch_array($result)) {
if (!empty($_POST['CategoryID']) && $_POST['CategoryID'] == $r['CategoryID']) {
$selected = 'selected="selected"';
} else {
$selected = '';
}
echo "<option ".$selected." value=".$r['CategoryID'].">".$r['CategoryName']."</option>";
}
from above:
echo "you have selected :" . $selected_val;
from what you are echoing, based on what I'm exp[laining], it echos the ID, not the name of the category.

$_POST['variable'] not working

I am having an issue getting the $userid from $_POST. I have done this lots of times before, so I am not sure what I am doing wrong all of a sudden.
Form that is submitting to user_confirm.php
<?php
//confirm user function
function confirmUsers() {
//make connection global
global $con;
//set user variables
$userquery = mysqli_query($con, "SELECT * FROM users WHERE userlevel = 0");
//echo list
echo '<center><form name="userConfirm" action="functions/user_confirm.php" method="post">';
echo '<select name="confirmUser">';
while ($row = mysqli_fetch_array($userquery)) {
echo "<option value='" . $row['userid'] ."'>" . $row['username'] ."</option>";
//in viewing element, the userid is displaying properly
}
echo '<input type="submit" value="Confirm User">';
echo '</select>';
echo '</form></center>';
}
?>
user_confirm.php
<?php
//include db connect
include ("db_con.php");
//set variable names
$userid = $_POST['userid'];
//start session
session_start();
echo $userid;
?>
As you can see, I am simply just trying to echo the variable passed from the form. It is not working and I am totally confused as to why, any ideas?
in case it was needed here is db_con.php
<?php
$con=mysqli_connect("localhost","user","pw","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
You dont have a form field called userid, perhaps you mean the confirmUser field:
$userid = $_POST['confirmUser'];
You are not passing the userid var to user_confirm.php, try renaming your select to userid
The coding looks right to me and should work.
I'm not sure if this will help but try to load the session_start(); first.
The next thing would be to do a print_r($_POST) and see what shows.
Also view the source of the finished html and see how it prints out.
Also I like to use
echo <<
END;
With this you can just type in the html plus the strings with no ' or " unless the html needs it.
I missed the confirmUser myself.. =(

Passing dropdown data which is gatherd from a mysql table

I need a script that loads data form mysql and show on a drop down list. From there, I need to pass the selected data to another page.
I have done the first step. I am now able to load data from mysql table and to show them on a drop down menu. The exact is given bellow.
<?php
include("config.php");
$result= mysql_query("SELECT folder_name FROM folders");
echo '<select name="directory">'; // Open your drop down box
while ($row = mysql_fetch_array($result)) {
//echo "<option>" . $row['folder_name'] . "</option>";
echo '<option value="'.$row['folder_name'].'">'.$row['folder_name'].'</option>';
}
echo '</select>';// Close your drop down box
?>
Now I need help to pass the selected data to another page. Any suggestion please?
Let me consider the form is posted to page2.php from page1.php
page1.php
<form method="post" action="page2.php">
//your dropdown code here
<?php
include("config.php");
$result= mysql_query("SELECT folder_name FROM folders");
$str = '';
$str .= '<select name="directory">'; // Open your drop down box
while ($row = mysql_fetch_array($result)) {
$str .= '<option value="'.$row['folder_name'].'">'.$row['folder_name'].'</option>';
}
$str .= '</select>';// Close your drop down box
echo $str;
?>
<input type="submit" value="submit" />
</form>
in page2.php you can access the dropdown selected value as
$selVal = '';
if(isset($_POST['directory']))
{
$selVal = $_POST['directory'];
}
create a javascript function to handle the redirect with the folder name data:
function changePage(folder){
window.location.href= 'http://www.yourdomain.com/page2.php?folder=' + folder;
}
onchange option, trigger changePage javascript function with folder name as input:
include("config.php");
$result= mysql_query("SELECT folder_name FROM folders");
echo '<select name="directory">'; // Open your drop down box
while ($row = mysql_fetch_array($result)) {
echo '<option value="'.$row['folder_name'].'" onchange="changePage(\''.$row['folder_name'].'\')">'.$row['folder_name'].'</option>';
}
echo '</select>';// Close your drop down box
page2.php
$folder_name = strip_tags($_GET['folder']);

Categories