parameterizing a dynamic drop down list in php - php

I have been trying to get it so that I can assign a variable to the value that the user selects in my drop-down menu of countries. I have done this before with tables, but not drop down lists, so I'm not sure how. Ultimately, I am trying to have a new page return a table for the country selected once the user clicks the submit button, and know I need a varaiable assigned to what the user selects. Here is my code so far:
<html>
<head>
<title>test2</title>
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<?php include("header.php"); ?>
<article>
<!-- This describes the choice of country name selection -->
<h1>Please select your country:</h1>
<form action='processformD.php' method='GET'>
<select name='CountryName'>
<?php
$query = "SELECT * FROM alphabetizedCountryNames;";
$result=mysqli_query($con, $query) or die ("Couldn't execute query.");
// $row = mysqli_fetch_assoc($result);
?>
<?php
while($row = mysqli_fetch_array($result))
{
extract($row);
echo "<option value='$CountryName'>$CountryName\n";
}
?>
</select>
<div class="centerthatshit"><?php echo "<p><input type='submit' value='submit' /></p>\n"; ?></div>
</form>
</article>
<?php include("footer.php"); ?>
</body>
</html>
</body>
</html>

Related

How to keep $_get['id']

So I am trying to create a school portal, and right now i am trying to find a way to add students to my existing classes. I can successfully add classes, and view them, but when I try to add students to them, it all goes wrong. This is the page that shows my existing classes in a table, and on the right I have the option to add students to that class. It takes the class ID, and adds it to the url of the next page(addtoclass.php)
<?php
//including the database connection file
include_once("connection.php");
//fetching data in descending order (lastest entry first)
$result = mysqli_query($conn, "SELECT * FROM class INNER JOIN yeargroup ON class.yeargroup_id=yeargroup.id INNER JOIN section ON class.section_id=section.id INNER JOIN subject ON class.subject_id=subject.ID INNER JOIN teacher ON class.teacher_id=teacher.ID ORDER BY yeargroup_id ASC, section_id ASC"); // using mysqli_query instead
?>
<html>
<head>
<title>View class</title>
</head>
<body>
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td>ID</td>
<td>Class Name</td>
<td>Teacher </td>
<td>Yeargroup</td>
<td>Subject</td>
<td>Section</td>
<td>Manage </td>
</tr>
<?php
//while($res = mysql_fetch_array($result))
while($res = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>".$res['class_id']."</td>";
echo "<td>".$res['classname']."</td>";
echo "<td>".$res['surname']."</td>";
echo "<td>".$res['yeargroup_description']."</td>";
echo "<td>".$res['subject_description']."</td>";
echo "<td>".$res['section_description']."</td>";
echo "<td>Add students | View current students</td>";
}
?>
</table>
</body>
So now, in the next page, I use $id=$_GET['id'] to retrieve the ID from the URL, and ideally I would then add the students the admins select from the dropdown menu into the class with the ID from the url.
include "connection.php";
$id= $_GET['id'];
$query = "SELECT * FROM student";
$result= mysqli_query($conn, $query);
// $query1 = "SELECT id FROM class WHERE id='$id'";
// $result1= mysqli_query($conn,$query1);
// echo $result1;
?>
<!DOCTYPE html>
<html>
<head>
<title>SSWL Portal</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<form action="addtoclass.php" method="POST">
<div>
<label>Student</label>
<select name="student">
<option selected="true" disabled="disabled"> Select one from below...</option>
<?php
while ($rows=mysqli_fetch_assoc($result)) {?>
<option value="<?php echo $rows['ID']?>"><?php echo $rows['name'].$rows['surname']?></option>
<?php
}?>
</select> <br>
<button type="sumbit" name="btnAddstudent" class="float" value ="btnAddstudent">Add New Student</button>
</div>
</form>
Logout
</body>
<?php
if (isset($_POST["btnAddstudent"])) {
$student= $_POST["student"];
$query2= "INSERT INTO student_class (student_ID,class_ID) VALUES '($student','$id')";
if (!mysqli_query($conn,$query2))
{
echo "error";
}
else
{
echo "success";
}
}
?>
When I select the students from the dropdown menu and press the 'Add new student' button, I get the error
"Notice: Undefined index: id in C:\xampp\htdocs\sswl\admin\addtoclass.php on line 4".
Is there a better way to do what I am trying to do, or to keep the $id from the url from before I press the button?
Any help would be appreciated. Thank you.
I will also link a picture of my database below.
You have to add id in to your form action like this:
...
<form action="addtoclass.php?id=<?php echo $id; ?>" method="POST">
...
Your code is vulnerable for SQL injections. I advice you to use
prepared statements in case when you need to perform an SQL queries.
Hope it helps.
It seems query string id was not defined appropriately.
<form action="addtoclass.php?id=$id" method="POST">
Change code in while loop to:
echo "<td>Add students | View current students</td>";

Getting a Value from a dropdown populated from an SQL database

I have populated a drop down from my MySQL Database successfully. I am now wanting to be able to extracte the value from this dropdown. When ever I extract the value from the dropdown it is only the position value of the value in the list.
Here is the working drop down below:
<?php
include_once("connection.php");
function fill_name($connect)
{
$output = '';
$sql = "SELECT name, id FROM notes";
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result))
{
$output .= '<option value="'.$row["id"].'">'.$row["name"].'</option>';
}
return $output;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Patient Notes View</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</script>
</head>
<body>
<br /><br />
<div class="container">
<form action="dropdown_selection.php" method="post">
<select name="name" id="name">
<option value="">Show All Patients</option>
<?php echo fill_name($connect); ?>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
And here is the page it then refers to:
<?php
$patient_name = $_POST['name'];
echo $patient_name
?>
The output is either 1,2,3,4, but I am wanting it to output what is is selected in the dropdown.
Thnks for your help
You can either change the value of your elements, or remove them. If the element has no value its content will be sent as the value.
The content of this attribute represents the value to be submitted with the form, should this option be selected. If this attribute is omitted, the value is taken from the text content of the option element.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option
So either:
$output .= '<option value="'.$row["name"].'">'.$row["name"].'</option>';
or
$output .= '<option>'.$row["name"].'</option>';
The output is number is correct as you set option value to be ID, not NAME -> <option value="'.$row["id"].'"> therefore you get IDs

MySQLi Select list dependent on the selected previous

So I have a database with 2 tables and a page with 2 select lists.
According to the value selected on the first select, I want to show the corresponding items on the second select.
There are no errors or anything, but the second select does never show anything, so I'm probably missing something.
Can someone help me?
Connection.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dberror1 = "Could not connect to the database";
$dberror2 = "Could not find the table";
$Conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die ($dberror1);
$Select_db = mysqli_select_db($Conn, 'swimming') or die ($dberror2);
?>
Results.php
<?php
include ("Connections/connection.php");
$query_comp = mysqli_query($Conn, "Select * FROM comp");
?>
<!doctype html>
<html><head>
<meta charset="utf-8">
<title>Swimming Results</title>
<link href="file:///D|/Websites/Swimming/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="wrapper">
<!-- Div for Title -->
<div id="title">
<p>Swimming Results</p>
</div>
<form name="results" >
<!-- Div to Choose competition -->
<div id="competition">
<p>Competition</p>
<select name="sel_comp">
<option value="">---Select one competition---</option>
<?php
while ($fetch = mysqli_fetch_assoc($query_comp)){
echo "<option value='{".$fetch['id']."}'>".$fetch['comp_name']."</option>";
}
?>
</select>
</div>
<!-- Div to Chose event -->
<div id="event">
<p>Event</p>
<select name="sel_even">
<option value="">---Select one event---</option>
<?php
$chosen=$_POST["sel_comp"] ;
$query_even = mysqli_query($Conn, "Select comp.id, events.cid, events.event_name FROM events, comp WHERE events.cid = $chosen");
while ($fetch = mysqli_fetch_assoc($query_even)){
echo "<option value='{".$fetch['event_id']."}'>".$fetch['event_name']."</option>";
}
?>
</select>
</div>
<!-- Div to Show results -->
<div id="results">
<p>Resultados</p>
</div>
</form>
</div>
</body>
</html>
Your PHP code is interpreted server-side, before displaying to the user's browser. So this code can't know anything about the choices the user will do.
If you want a "dynamic sub-select", you need to add some javascript code. That javascript code will run on the user's browser and will be able to react to the user's action on the first select box.

Run different query based on a dynamic HTML dropdown list

I made some PHP code to generate this page. I successfully get all the items from a column into a HTML dropdown list (it's a dynamic list). I want to write some code so that when user selects an item from the list and hit submit, it will take user to a new page contains corresponding information on it. I have no idea what kind of code would be included in. Please help. Thanks!
For instance, if user select 50A-1, it will populate a table has all the items located at 50A-1.
Two pieces of code I wrote, first is the page gives you the dropdown list and the submit button. The second is the result page, but it only shows the whole inventory so far, it doesn't have a way to connect to the dropdown list option.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Inventory</title>
</head>
<body>
<div>
<a>SQL Connection test</a>
<form action="connect.php" method="POST">
<div class="center">
<input type="submit" value="Connect to MySQL" />
</div>
</form>
</div>
<div>
<section>
<article>
<p>
<select name="dropdown">
<?php query() ?>
</select>
<?php close() ?>
</p>
</article>
</section>
<div>
<input type="submit" value="Submit" />
</div>
</div>
</body>
</html>
Second page
<?php
include_once 'db.inc.php';
// connect
function connect() {
// Connect to the MySQL server
mysql_connect(DB_HOST,DB_USER,DB_PASS) or die ('Could not connect to server!' . mysql_error());
mysql_select_db(DB_NAME);
}
// close
function close() {
mysql_close();
}
// query
function query() {
$myData = mysql_query("SELECT DISTINCT * FROM sheet0_100 GROUP BY location");
while($record = mysql_fetch_array($myData)) {
echo '<option value="' . $record['location'] . '">' . $record['location'] . '</option>';
}
}
?>
That's the purpose of HTML forms :)
You need to create a form to encapsulate that select:
<form action="process.php" method="get">
<select name="inventory_id">
<!-- Here all options -->
</select>
<button type="submit">See items</button>
</form>
Then in process.php you need to get the selected element and query the database, for example (I assume that you're using PDO):
<?php
$inventory_id = $_GET['inventory_id'] // The name attribute of the select
// Then you prepare the query
$query = "SELECT * FROM sheet0_100 WHERE id = :inventory_id";
// Execute the query and show the data...
use Sessions
example:
on your first page
session_start();
$_SESSION['your-dropdown-list-value'] = 'Root';
on your new page
//error_reporting(E_ALL);
session_start();
if(isset($_SESSION['your-dropdown-list-value'])) {
echo "Your dropdown selection " . $_SESSION['your-dropdown-list-value'];
}

HTML option tags not loading after form submit

I have an html page that loads list of hotels in a select tag from a MySQL table using PHP. The select tag is inside a form tag. Whenever I load the page, the option tags will load, but when I submit my form, the option tags never load anymore. My form's action attribute is empty, I am checking everything on the same page, but when I put another php page as action, it loads normally. Is there a way to make it load after submit while keeping my form's action empty?
Here is my code
<?php
require_once 'db.php';
$db = DB::get_instance();
if(isset($_POST['search'])) {
$hotel = $_POST['hotel_list'];
$db->query("SELECT * FROM hotels WHERE Name='$hotel'");
$hotel = $db->result()->current();
$hid = $hotel['Hid'];
$db->query("SELECT * FROM rooms WHERE Hid='$hid'");
$rooms = $db->result();
$db->disconnect();
}
?>
<!doctype html>
<html>
<head>
<title>Display a hotel</title>
</head>
<body>
<form action="" method="post" id="dsphtl">
Name: <select name="hotel_list" form="dsphtl">
<?php
$db->query("SELECT Name FROM hotels ORDER BY Name");
foreach($db->result() as $row) {
$t = $row['Name'];
echo "<option value='$t'>$t</option>";
}
?>
</select>
<input type="submit" value="Search" name="search">
</form>
</body>
</html>
If $_POST['search'] is set, you $db->disconnect(); so it can't run the query in your form.
Take the $db->disconnect(); out of your if() statement, and put it at the end of the file.
The issue is with the disconnect, when the page reload after submit your connection to mysql lost due to
$db->disconnect();
<?php
require_once 'db.php';
$db = DB::get_instance();
if(isset($_POST['search'])) {
$hotel = $_POST['hotel_list'];
$db->query("SELECT * FROM hotels WHERE Name='$hotel'");
$hotel = $db->result()->current();
$hid = $hotel['Hid'];
$db->query("SELECT * FROM rooms WHERE Hid='$hid'");
$rooms = $db->result();
}
?>
<!doctype html>
<html>
<head>
<title>Display a hotel</title>
</head>
<body>
<form action="" method="post" id="dsphtl">
Name: <select name="hotel_list" form="dsphtl">
<?php
$db->query("SELECT Name FROM hotels ORDER BY Name");
foreach($db->result() as $row) {
$t = $row['Name'];
echo "<option value='$t'>$t</option>";
}
?>
</select>
<input type="submit" value="Search" name="search">
</form>
</body>
</html>

Categories