select options not displaying using functions - php

I am trying to displays value of selects options dynamically in PHP. Basically user creates those options awhich are stored in database and then I am trying to fetch this at different place. for this purpose i wrote the below function:
function fetch_acad_yr($conn) {
$query = "SELECT a.fk_acadyear_id as acadyearid,b.acad_year as acadyear FROM tbl_admparam a inner join list_acad_years b on a.fk_acadyear_id = b.pk_acad_year_id";
$stmt = $conn->prepare($query);
if ($stmt->execute()) {
foreach ($stmt as $row) {
?>
<option value="<?php echo $row['acadyearid'] ?>"><?php echo $row['acadyear'] ?></option>
<?php
}
}
}
then in html i called this function
<select class="form-control" id="acad_period" name="acad_period" required>
<option value="">Please select...</option>
<?php fetch_acad_yr($conn); ?>
</select>
But the options doent show any values it simply come blank and is not dispalying the values stored in database. I tried running the query separately and the query is returning the desired result

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$con = new mysqli($servername, $username, $password,$dbname);
if ($con->connect_error)
{
die("Connection failed: " . $con->connect_error);
}
?>
<select name="acad_period" required="">
<option value="0">Select</option>
<?php
$s= "SELECT a.fk_acadyear_id as acadyearid,b.acad_year as acadyear FROM tbl_admparam a inner join list_acad_years b on a.fk_acadyear_id = b.pk_acad_year_id";
$ex= $con->query($s);
if (!$ex)
{
echo("Error description: " . mysqli_error($con));
}
else
{
while ($f= $ex->fetch_assoc())
{
?>
<option value="<?php echo $f['acadyearid'] ?>"><?php echo $f['acadyear'] ?></option>
<?php
# code...
}
}
?>
</select>

Make sure you have the right connection and the data coming in the query result.
Basic php mysql code I used was the below and it worked. You make change it to pdo or propel and get the result. But the usage is same with while or for loop.
$conn = mysql_connect($host, $username, $pass);
mysql_select_db($dbname, $conn);
echo "<pre>";
echo "<select>";
fetch_acad_yr($conn);
echo "<\select>";
function fetch_acad_yr($conn) {
$query = "SELECT a.fk_acadyear_id as acadyearid,b.acad_year as acadyear FROM tbl_admparam a inner join list_acad_years b on a.fk_acadyear_id = b.pk_acad_year_id";
$res = mysql_query($query);
while($row = mysql_fetch_assoc($res)){
?>
<option value="<?php echo $row['acadyearid'] ?>"><?php echo $row['acadyear'] ?></option>
<?php
}
}
?>
Works for me.

Related

Using a variable from one PHP script as an argument for a PHP function i another PHP script

I am trying to set the value to be displayed in a SELECT list using php scripts.
What I have done is create an input html page (MatchSelect.php) which shows two select boxes and a submit button.
On pressing the submit button a new new php file is called (MatchSelectResult.php) which is as follows;
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Seniors Inter-Club Match Management</title>
<link rel="stylesheet" href="MainBody.css">
<link href="dropDown.css?v=1.1" rel="stylesheet" >
<?PHP require '../../configure.php';
include "Main_PHP_Code.php" ;
?>
</head>
<body>
<?PHP include "MatchPopulate.php"; ?>
<div class="container">
<?PHP include "menu.txt" ?>
<div class="content">
<div>
<h1>Team Selection</h1>
<form name="matchSelect" method="POST" action="MatchUpdate.php">
<p>
<select id = "Venue" name= "Venue" >
<option disabled selected value> -- select an option -- </option>
<option value="Away">Away</option>
<option value="Home">Home</option>
</select>
match against
<select id ="Opponents" name ="Opponents">
<?php
Global $OpponentName;
$oop = $OpponentName;
opponent_load('$oop');
?>
</select>
etc.
the function opponent_load() is contained within the "Main_PHP_Code.php" code and is as follows;
function opponent_load($oppon){
Global $OpponentName;
$db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
$database = "matchmanagementdb";
$db_found = mysqli_select_db($db_handle, $database);
if ($db_found) {
$SQL = "SELECT * FROM opponentsdb";
$result = mysqli_query($db_handle, $SQL);
while ( $db_field = mysqli_fetch_assoc($result) ) {
$uName = $db_field['Opponents'];
if ($uName == $oppon)
{
$selected = 'selected="selected"';
}
else
{
$selected = '';
}
echo "<option value='$uName' $selected> $uName </option>";
}
}
else {
print "Database NOT Found ";
}
mysqli_close($db_handle);
}
The "MatchPopulate.php" code in the HEAD section is used to search the mySQL database using the two values from MatchSelect.php page. If the data is found, then the global variable $OpponentName is defined. The code is thus;
<?php
Global $OpponentName;
//require '../../configure.php';
$uOpponentName = $_POST['Opponents'];
$uVenue = $_POST['Venue'];
//$db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
$database = "matchmanagementdb";
$conn = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// check to see if Match (Opponents + Venue)already in the database, if so, retrieve data or add match to database
$SQL = "SELECT * FROM teamselect WHERE Opponents = '$uOpponentName' AND Venue = '$uVenue'";
$result = $conn->query($SQL);
//if $result->num_rows >0 then retrieve data ELSE add match to database
if (!$result){
print "Error selecting record: " . $sql . "<br>" . $conn->error;
} else {
if ($result->num_rows >0) {
while($row = $result->fetch_assoc()) {
$OpponentName = $row['Opponents'];
}
} else {
$sql = "INSERT INTO teamselect (Opponents, Venue) VALUES ('$uOpponentName', '$uVenue')";
if ($conn->query($sql) === TRUE) {
} else {
print "Error adding record: " . $sql . "<br>" . $conn->error;
}
}
}
$conn->close();
?>
The code stops when it tries to populate the Opponents Select box on MatchSelectResult.php. Any help to solve this would be appreciated.
I have solved the problem by opening a session and using $_SESSION["Opponents"] to pass the variable around the scripts.
Also changed opponent_load('$oop') to opponent_load($oop).

DropDown to select data from MS SQL server

I'm trying to make a PHP web application display the data from specific Countries from a dropdown but I can't figure it out how to use the WHERE [Column] = [Value1, Value2, Value3] on a PHP dropdown.
I'm using the "Adventure Works 2014 Full Database Backup" for test purpose.
<html>
</body>
<!-- form for tower selection -->
<form action="test20.php" method="POST">
Please select the tower you are about to work on. </br></br>
<select name="TowerSelect"><option> Choose </option>
<?php
$serverName = 'SERVERNAME';
$uid = 'USERNAME';
$pwd = 'PASSWORD';
$databaseName = 'AdWorks';
$connectionInfo = array( 'UID'=>$uid,
'PWD'=>$pwd,
'Database'=>$databaseName);
$conn = sqlsrv_connect($serverName,$connectionInfo);
if($conn){
echo '';
}else{
echo 'Connection failure<br />';
die(print_r(sqlsrv_errors(),TRUE));
}
$sql = "SELECT BusinessEntityID, FirstName FROM dbo.vKelvin WHERE CountryRegionName = 'United States'";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($data=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
echo "<option value=";
echo $data['BusinessEntityID'];
echo ">";
echo $data['BusinessEntityID'];
echo "</option>";
}
?>
<input type="submit" value="Select Tower">
</select></br></br>
</form>
</body></html>
<?php
if(empty($_POST['TowerSelect'])){
$_SESSION['tower'] = '';
} else {
$_SESSION['tower'] = $_POST['TowerSelect'];
echo "<tr>";
echo $_SESSION['tower'];
echo " selected. </p>";
echo('<td>'.$row['BusinessEntityID'].'</td><td>'.$row['FirstName'].'</td></tr>');
}
I believe I have this fixed. There were a number of problems with the code. You were referencing a $row but there was no SQL query that would have resulted in a $row, you were trying to post data after the closing HTML tag, you were trying to create rows for a table without declaring the table, and a few other things. Some of this was probably a result of quickly creating the test case. No problem. Try this...
<?php
$serverName = 'SERVERNAME';
$uid = 'USERNAME';
$pwd = 'PASSWORD';
$databaseName = 'AdWorks';
$connectionInfo = array( 'UID'=>$uid,'PWD'=>$pwd,'Database'=>$databaseName);
$conn = sqlsrv_connect($serverName,$connectionInfo);
if($conn){echo '';}else{echo 'Connection failure<br />';die(print_r(sqlsrv_errors(),TRUE));}
?><html><body>
<!-- form for tower selection -->
<form action="test20.php" method="POST">
Please select the tower you are about to work on. </br></br>
<select name="TowerSelect"><option> Choose </option>
<?php
$sql = "SELECT BusinessEntityID, FirstName FROM dbo.vKelvin WHERE CountryRegionName = 'United States'";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($data=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
echo '<option value="'.$data['BusinessEntityID'].'">';
echo $data['BusinessEntityID'];
echo "</option>";
}
?><input type="submit" value="Select Tower">
</select></br></br>
</form>
<table cols="3" cellpadding="0" cellspacing="0" border="0">
<?php
if(empty($_POST['TowerSelect'])){
$_SESSION['tower'] = '';
} else {
$sql = "SELECT BusinessEntityID, FirstName FROM dbo.vKelvin WHERE BusinessEntityID = '".$_POST['TowerSelect']."'";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($row=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
$_SESSION['tower'] = $_POST['TowerSelect'];
echo '<tr><td>'.$_SESSION['tower'].' selected.</td>';
echo '<td>'.$row['BusinessEntityID'].'</td>';
echo '<td>'.$row['FirstName'].'</td></tr>';
}
}
?></table></body></html>
Note: Though not important to answer your question, it is a best practice to use PDO and bound paramters when making database calls to protect yourself against SQL injection and other nasties. I recommend you look into it to protect your database. Cheers!
Ok, I got the solution, my select was wrong
$sql = "SELECT DISTINCT CountryRegionName FROM dbo.vKelvin ORDER BY CountryRegionName";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($data=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
echo '<option value="'.$data['CountryRegionName'].'">';
echo $data['CountryRegionName'];
echo "</option>";
if(empty($_POST['TowerSelect'])){
$_SESSION['tower'] = '';
} else {
$sql = "SELECT BusinessEntityID, FirstName FROM dbo.vKelvin WHERE BusinessEntityID = '".$_POST['TowerSelect']."'";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($row=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
$_SESSION['tower'] = $_POST['TowerSelect'];
echo '<tr><td>'.$_SESSION['tower'].' selected.</td>';
echo '<td>'.$row['BusinessEntityID'].'</td>';
echo '<td>'.$row['FirstName'].'</td></tr>';
}
}

Populating DropDown List with PHP from MYSQL Database

I'm trying to bring data from MYSQL Database called ebms_db. The table is events and the fields are Event_ID and Event_Name.
The code I'm using currently to show the Event_Name only in the dropdown list is:
<select name="mySelect">
<?php
include 'db.php';
$sql = "SELECT Event_Name FROM events";
$result = mysql_query($sql);
echo "<select name='Event_Name'>";
while ($r = mysql_fetch_array($result)) {
echo '<option value="'.$row["Event_Name"].'">'.$row["Event_Name"].'</option>';
}
echo "</select>";
?>
<input type = "submit" name="Search" value="Search">
</select>
Db.Php looks like this...
$servername = "localhost";
$username = "test";
$password = "test";
$dbname = "ebms_db";
$conn = new mysqli($servername, "test", "test", $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
echo "Error";
}
What am I doing wrong?
The output shows a combo box with
- '.$row["Events_Name"].'
inside it.
while ($row = mysql_fetch_array($result)) {
^^^^ here
echo '<option value="'.$row["Event_Name"].'">'.$row["Event_Name"].'</option>';
}
<?php
include 'db.php';
// you just fetching here (Event_Name) take all the values from the database or
$sql = "SELECT * FROM events";
$result = mysql_query($sql);
echo "<select name='Event_Name'>";
while ($row = mysql_fetch_array($result)) {
echo '<option value="'.$row["Event_Name"].'">'.$row["Event_Name"].'</option>';
}
echo "</select>";
?>
<input type = "submit" name="Search" value="Search">
Why are you taking two selects? I just removed one select just beginning above the php tags.
MYSQL is deprecated, you should really use something else, if and/or when they remove it your website will be defunct.

Trying to load data dynamically from the database in a from using PDO

Im trying to load data from the database dynamically. Like when user click on select button in a form, the data will be loaded dynamically from the database. But the problem is I have to use PDO. Im not getting the output, don't know what's wrong. Here is my code-
<tr><td><font size="+1">Region :</font></td>
<td><Select name="region" class="regionfields" id="wineRegion">
<option id="0">-- Select Region --</option>
<?php
$hostname = 'localhost';
$username = 'ovic';
$password = 'root';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=winestore", $username, $password);
echo 'Connected to database<br />';
$sql = "SELECT region_name FROM region";
$stmt = $dbh->query($sql);
$obj = $stmt->fetch(PDO::FETCH_OBJ);
foreach($obj->region_name AS $W)
{?>
<option id="<?php echo $W; ?>"><?php echo $W; ?></option>
<?php
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
</Select></td></tr>
You may need to use $stmt->fetchAll() which returns an array of objects. The fetch() method returns only a single object.
$regions = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach ($regions as $region) {
?>
<option id="<?php echo $region->region_name; ?>">
<?php echo $region->region_name; ?></option>
<?php
}
If that fails, trying doing a print_r on the result of fetchAll() to see if you are getting anything back.

Using Dreamweaver, how can I populate a drop down list via PHP?

I am trying to populate a drop-down list via PHP embedded in HTML.
Here is what I have so far:
<select name="ChapterList" id="ChapterList" style="width:120px;">
<?php
$username = "xxxxxxxxxxx";
$password = "xxxxxxxxx";
$database = "xxxxxxxxxxxxxx";
$host = "xxxxxxxx.mydomainwebhost.com";
#mysql_connect($host, $username, $password) or die("Unable to connect to database");
#mysql_select_db($database) or die("Unable to select database");
$query = "SELECT * FROM Chapters ORDER BY Id";
$ListOptions = mysql_query($query);
while($row = mysql_fetch_array($ListOptions))
{
echo "<option value='".$row['Id']."'>".$row['ChapterName']."</option>"
}
?>
</select>
I know I am recieving the expected results because if I echo $row['ChapterName']; , the current values I have in the database are listed in the proper order, so why is it when I echo "<option value='".$row['Id']."'>".$row['ChapterName']."</option>" my list receives nothing at all?
You are missing a semi-colon at the end of your echo statement
while($row = mysql_fetch_array($ListOptions)) {
echo "<option value='".$row['Id']."'>".$row['ChapterName']."</option>";
}
?>
Note: Start using mysqli_() functions as mysql_() are no more maintained by PHP team..
try using this
<?php
$form='';
$link = odbc_connect ('databasename', 'username', 'password');
if (!$link)
{
die('Could not connect: ' . odbc_error());
}
echo 'Connected successfully .<br>';
//Query the database
$sql = "SELECT * FROM Chapters ORDER BY Id ";
$result = odbc_exec($link,$sql);
$selectbox='<select id=combox name=Chapters >';
while($bin =odbc_fetch_array($result))
{
$selectbox.= "<option value=\"$bin[Chapters]\">$bin[FChapters]</option>";
}
odbc_close($link);
$selectbox.='</select>';
echo "Select Name".$selectbox;
?>
this code is working perfectly for me
Ok... so I solved my own question in a way.
What I discovered was that my php was being commented out via <--! -->. I merely changed the file extension to .php as opposed to .html. The drop-down list worked immediately and was populated with the proper values.
But this raises another question... how can I get inline PHP to work? My site is hosted with MyDomain. Is there a setting I am missing somewhere?
try to use this
<select>
while($row = mysql_fetch_array($ListOptions))
{
$id=$row['Id'];
$cname=$row['ChapterName'];
echo "<option value='$id'>$cname</option>";
}
?></select>
I have correct them just look at once,
<?php
$username = "xxxxxxxxxxx";
$password = "xxxxxxxxx";
$database = "xxxxxxxxxxxxxx";
$host = "xxxxxxxx.mydomainwebhost.com";
$dbc=#mysqli_connect($host, $username, $password,$database) or die("Unable to connect to database");
?>
<select name="ChapterList" id="ChapterList" style="width:120px;">
<?php
$query = "SELECT * FROM Chapters ORDER BY Id";
$ListOptions = mysqli_query($dbc,$query);
while($row = mysqli_fetch_array($ListOptions,MYSQLI_ASSOC))
{
echo "<option value='".$row['Id']."'>".$row['ChapterName']."</option>";
}
?>
</select>

Categories