I have just started using PDO but I am slowly getting the hang of it. I want to know how to make a drop down menu or list box populate the data into fields on a page. I have started the code by looking up PDO guides etc, but I am having trouble finding a solution for this. I am also sorry for the untidy code but again I am new to the whole programming scene.
Thanks in advance. Here is my code so far:
Here is the connection string:
<?php
session_start();
if(!isset($_SESSION["user_id"])){
header("location:../Pages/login.html");
}
//databse connection Sting
$connection = new PDO("sqlsrv:server=servername;Database=databasename", "username", "password");
//insertion function
$smt = $connection->prepare('select exam_id From exam');
?>
This also included my session cookie, but that works great. Here is the population of the drop down box I have so far.
<select name="lst_exam" id="lst_exam">
<?php
$smt->execute();
while ($row = $smt->fetch()){
echo "<option>" . $row["exam_id"] . "</option>";
}
$connection = null;
if(isset($_POST["lst_exam"]));
?>
</select>
The text boxes I am trying to populate are txt_exam_id, txt_location, txt_date_taken, txt_exam_taken, txt_grade_recieved
The answer is simple: do not populate dropdown menus through pdo code
That's totally different matters which should never be intrmixed in the code.
Separate your code into 2 parts:
PDO code
populating whatever menus from a conventional array code.
write and debug these parts separately.
$smt = $connection->prepare('select exam_id From exam');
$smt->execute();
$data = $smt->fetchAll();
now you have your exams stored in $data array.
<select name="lst_exam" id="lst_exam">
<?php foreach ($data as $row): ?>
<option><?=$row["exam_id"]?></option>
<?php endforeach ?>
</select>
//USING PDO
$ID=trim($_GET['id']);
$result = $DB_con->prepare("select userID, firstName, lastName, gender, telNo, userEmail, userName, contactAddress, case when userStatus = 'Y' then 'TRUE' ELSE 'FALSE' end as userStatus, case when state = 1 then 'ACTIVE' else 'IN-ACTIVE' end as state, department.name as department from users JOIN department on department.id = users.department where userID=:get_header LIMIT 1");
$result->execute(array(":get_header"=>$ID));
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
$id=$row['userID'];
?>
$sql_g = "Select id, name from gender";
$gend = $DB_con->prepare($sql_g);
//Execute the statement.
$gend->execute();
//Retrieve the rows using fetchAll.
$gend_lists = $gend->fetchAll(PDO::FETCH_ASSOC);
//HTML AND PHP
<div class="col-sm-3">
<div class="form-group">
<label class="control-label">Gender</label>
<?php $value = $row["gender"]; ?>
<select name="gender_test" class="form-control">
<?php foreach($gend_lists as $id => $option) { ?>
<option value="<?php echo $id["id"] ?>"<?php
if($id["id"] == $value) {
echo " selected";
} ?>><?php echo $option["name"] ?></option>
<?php } ?>
</select>
</div><!-- form-group -->
</div><!-- col-sm-6 -->
Related
The function of this web application is to: select a customer from the dropdown list (the dropdown list values are auto popup from the database), it will print the selected customer name and its postcode on the result page.
When I choose the customer name from the dropdown list and click the submit button, the result page only prints the $customerv value (the 1st echo), but the $result value (2nd echo) was not printed. The customer name is unique in the database.
index.php:
<?php
require_once('config.php');
?>
<!DOCTYPE HTML>
<html>
<form action="result.php" method="post">
Customer:<br>
<select Customer id="customer" name="Customer">
<option value="">--- Select Customer ---</option>
<?php
$sql = "SELECT b.BPName from BP b where b.BPCode like 'C%' Order by b.BPName";
$customer = mysqli_query($conn, $sql);
while ($cat = mysqli_fetch_array(
$customer,
MYSQLI_ASSOC
)) :;
?>
<option value="<?php echo $cat['BPName']; ?>">
<?php echo $cat['BPName']; ?>
</option>
<?php
endwhile;
?>
</select>
<input type="submit" value="Submit">
</form>
</html>
config.php:
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$databse = "xxx";
$conn = new mysqli($servername, $username, $password, $databse);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
result.php:
<table>
<?php
require_once('config.php');
$customerv = $_POST['Customer'];
echo $customerv;
$sql = "SELECT shiptozipcode FROM BP WHERE BPName ='$customerv'";
$result = $conn->query($sql);
echo $result;
?>
</table>
The query result itself isn't something that's "printable" to the page. It's not just a single value, it's a complex object. You need to fetch the record(s) from the result. For example:
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
echo $row["shiptozipcode"];
}
If you're sure there will be only one row (it's still a good idea to add some error checking anyway) then you don't need the loop:
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo $row["shiptozipcode"];
But either way, you need to extract the data from the result set. (You could also use fetch_object() instead of fetch_assoc() if you prefer object syntax over array syntax.)
As an aside, be aware that your query is wide open to SQL injection. Now would be a good time to learn how to correct that.
I need some help in populating a drop down down list from a mysql table. I'm new to php and I am having a hard time. Here's my code and I know it's wrong, I just don't know where.
My current output is just a drop down box with nothing inside it.
My expected output is that it would show the driver's name from the mysql table.
<?php
$Hehe = $mydb->getALL('SELECT drivername FROM driver;'); //select from all users
?>
<select name=mydriver value=''>Driver Name</option> // list box select command
<?php
foreach($Hehe as $hehe){//Array or records stored in $row
?>
<option name = "mydriver"><?phpecho $Hehe['drivername']?></option>
</select>
<?php
}
?>
the getALL function:
function getAll($query) {
$result = $this->conn->prepare($query);
$ret = $result->execute();
if (!$ret) {
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$reponse = $result->fetchAll();
return $reponse;
}
You're using wrong array to get the drivername. It should be $hehe['drivername'], not $Hehe['drivername']. Like I said, use some meaningful variable names in your code, it would be easy for you track down the error. Also </select> should be outside of foreach loop.
<?php
$Hehe = $mydb->getALL('SELECT drivername FROM driver;'); //select from all users
?>
<select name="mydriver">Driver Name</option> // list box select command
<?php
foreach($Hehe as $hehe){//Array or records stored in $row
?>
<option value="<?php echo $hehe['drivername']; ?>"><?php echo $hehe['drivername']; ?></option>
<?php
}
?>
</select>
Sidenote: Always turn on error reporting, add these two statements ini_set('display_errors', 1); error_reporting(E_ALL);at the very top of your PHP scripts to debug any syntax related issues.
i am trying below code to display list of enum values in select dropdown box.
but its displaying only dropdown box, but values are not displaying....
tablename = tbl_users, column name = userStatus
<select>
<?
$stmt = $user_home->runQuery('SHOW COLUMNS FROM '.tbl_users.' WHERE field="'.userStatus.'"');
while($data = $stmt->fetch()) {
foreach(explode("','",substr($row[1],6,-2)) as $option) {
print("<option>$option</option>");
}
}
?>
<select>
Note : I really tried lot before posting question here & i am new to php coding, still learning....
To display list of enum values in select dropdown:
<select name="select">
<?php
$sql = 'SHOW COLUMNS FROM table_name WHERE field="field_name"';
$row = $dbh->query($sql)->fetch(PDO::FETCH_ASSOC);
foreach(explode("','",substr($row['Type'],6,-2)) as $option) {
print("<option value='$option'>$option</option>");
}
?>
</select>
For display enum value as dropdown you can do something like this.
<?php $status = array('Y'=>'Approve','N'=>'unapprove'); ?>
<select>
<?php foreach($status as $key=>$state) { ?>
<option value="<?php echo $key;?>"><?php echo $state;?></option>
<?php } ?>
</select>
i am using Php/Mysql , i have the client table and trying to display data in a drop down list. Unfortunately, only one client is displayed in drop down which i have the total of 3 clients. Why only one ? For example : Michael King, Michael Jordan , Michael John when i select all the data from table and make an output to display in dropdown, Michael John is only in the dropdown.
Here my Mysql code :
//All data is selected from client_tb
<?php
$sql = "SELECT * FROM client_tb";
$result = $conn->query($sql);
while($row=mysqli_fetch_array($result))
{
$id = $row['id'];
$lname = $row['lname'];
$fname = $row['fname'];
}
?>
//my dropdown which will show the clients from client_tb but only one will appear.
<option value ="<?=$lname?><?=$fname?>"><?=$lname?> , <?=$fname?> </option> </select><br><br>
You can also achieve dropdown outside the while loop. Try this:
$sql = "SELECT * FROM client_tb";
$result = $conn->query($sql);
$options =array();
while($row=mysqli_fetch_array($result))
{
$options[] =$row;
}
Your dropdown:
<select name="">
<?php
foreach($options as $option):
echo '<option value ="'.$option['lname'].''.$option['fname'].'">'.
$option['lname'].','.$option['fname'].'</option>';
endforeach;
?>
</select>
You could also add your db query into a function , then call it.
function myFunction() {
$sql = "SELECT * FROM client_tb";
$result = $conn->query($sql);
while($row=mysqli_fetch_array($result))
{
$myvalues[] =$row;
}
return $myvalues;
}
Now the dropdown,
Note the options are inside the loop
<select name="">
<?php foreach($myvalues as $myvalue) {
echo '<option value="'.$myvalue['lname'].''.$myvalue['fname'].'">'.
$myvalue['lname'].','.$myvalue['fname'].'</option>';
}
?>
</select>
I am currently struggling with creating a drop down box that when populated will delete whichever record is currently highlighted.
I have been able to create a form that allows me to add new records to the database, but since then have really struggled to get the correct records to show on the drop down box as I only have a vague understanding of PHP.
<?php
$db=sqlite_open("/wwwroot/Work/bookDB.db");
if (isset($_POST['submit']))
{
$Author = $_POST['Author'];
$Title = $_POST['Title'];
$Synopsis = $_POST['Synopsis'];
$ISBN = $_POST['ISBN'];
$Publisher = $_POST['Publisher'];
sqlite_query ($db, "INSERT INTO Books (Author, Title, Synopsis, ISBN, Publisher)
VALUES ('$Author', '$Title', '$Synopsis', '$ISBN', '$Publisher')");
header("Location: /Work/Book/Book.php");
}
else
{
}
?>
this is my submit query that may give some understanding of how the database is set up, I am looking to have a drop down box that will be populated by a list of the authors. So far I have tried using $row to no avail, and I don't seem to be able to use $column either, like I have stated earlier my PHP skills are awful so any help would really be appreciated.
html:
<form name = "delete form" action="Delete.php" method="POST">
<div class = "book">
<select name = "Title">
<option value = ""> Select </option>
</div>
php:
<form action = "<?php echo $_SERVER['PHP_SELF'];?>" method="get">
<select name = 'rowno' onchange = "javascript:document.forms[0].submit();">
<option> Select a Book </option>
<?php
$db = sqlite_open("/wwwroot/work/bookDB.db");
$query = sqlite_query($db,"SELECT ID, Title from Books");
$result = sqlite_fetch_all($query, SQLITE_BOTH);
$rowno = 0;
foreach($result as $entry)
{
echo "<option value = $rowno >$entry[ID] $entry[Title]</option>";
$rowno++;
}
?>
</select>
</form>
</div>