<?php
$pdo = new PDO('mysql:host=localhost;dbname=xxxxxxx', "xxxxxxx", "xxxxxxx");
$sql = "SELECT id, food, kcl, fat, fullk, sockerart, kolhyd FROM bread";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$users = $stmt->fetchAll();
?>
<select name="food" id="food">
<?php foreach($users as $user): ?><br />
<option value=><?= $user['id']; ?><?= $user['food']; ?></option>
<?php endforeach; ?>
</select>
<?php
/*
* Database Connection
*/
$db_options = [
/* important! use actual prepared statements (default: emulate prepared statements) */
PDO::ATTR_EMULATE_PREPARES => false
/* throw exceptions on errors (default: stay silent) */
, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
/* fetch associative arrays (default: mixed arrays) */
, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];
$pdo = new PDO('mysql:host=' . DATABASE_HOST . ';dbname=' . DATABASE_NAME . ';charset=utf8', DATABASE_USERNAME, DATABASE_PASSWORD, $db_options);
$sql = "SELECT id, food, kcl, fat, fullk, sockerart, kolhyd FROM bread";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<select name="food" id="food">
<?php
foreach($records as $record) {
echo 'option value="' . $record['id'] . '">' . $record['food'] . '</option>';
}
?>
</select>
I hope you were kind of showing pseudo HTML / Code as you are missing some key parts. I don’t know exactly what you are trying to do, so I guessed. I would also make sure you have error reporting turned on. There might be a few errors in what I gave you that is why I’m suggesting to do so, plus you should always have error reporting turned on when coding.
The intention is to retrieve data from MYSQL with different types of bread and display these in a drop down list.
The user should be able to choose a type of bread.
I need to fetch the selected value and show the bread content (carbohydrates, fat, etc.) in different text boxes where the user should be able to make changes. The user should also be able to choose what the bread weighs. The program then calculates the current content and saves it in the database.
As a beginner in PHP, I did not get the modified script to show anything in the drop down list. Why?
There are no errors in the log.
My question is: How do I retrieve the selected value in the drop down list and can I use saved values in the list?
<header>
<!DOCTYPE html>
<html lang="sv">
<head>
<meta name="author" content="">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" type="image/ico" ">
<title> </title>
<link href="/css/style.css" rel="stylesheet">
</head>
<body>
</header>
<?php
/* session_start();
if(!isset($_SESSION["username"]))
{
header("location: include/login.php?action=login");
}
?>
<?php $nam = $_SESSION["username"] */
include ('admin/dbconnection.php');
include("lang/lang_sv.php");
?>
<style type="text/css">
body {
background-color: #FFFFF0;
}
</style>
<div style="width: height: 120px; margin-left: 20px; float: center; padding: 20px;">
<table width="55%" border="1" align="center" cellpadding="1" cellspacing="0">
<tr>
<th bgcolor="#FFFFA6" scope="col"><div align="center" style="font-size: 14px">
<p align="center"><a href="userintag_sv.php" target="iframe_a"><?php echo ca_text0015_user; ?></a></p>
</div></th>
<th bgcolor="#FFFFA6" scope="col"><div align="center" style="font-size: 14px">
<p>Menu2</p>
</div></th>
<th bgcolor="#FFFFA6" scope="col"><div align="center" style="font-size: 14px">
<p>Menu3</p>
</div></th>
<th bgcolor="#FFFFA6" scope="col"><div align="center" style="font-size: 14px">
<p>Menu4</p>
</div></th>
<th bgcolor="#FFFFA6" scope="col"><div align="center" style="font-size: 14px">
<p>Menu5</p>
</div></th>
</tr>
</table>
<p> </p>
<?php
/*
* Database Connection
*/
$db_options = [
/* important! use actual prepared statements (default: emulate prepared statements) */
PDO::ATTR_EMULATE_PREPARES => false
/* throw exceptions on errors (default: stay silent) */
, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
/* fetch associative arrays (default: mixed arrays) */
, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];
$pdo = new PDO('mysql:host=' . 'localhost' . ';dbname=' . 'xxxxxx' . ';charset=utf8', 'xxxxxx', 'xxxxxx');
$sql = "SELECT id, food, kcl, fat, fullk, sockerart, kolhyd FROM bread";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<select name="food" id="food">
<?php
foreach($records as $record) {
echo 'option value="' . $record['id'] . '">' . $record['food'] . '</option>';
}
?>
</select>
A drop-down is a SELECT clause. It has ONLY one value. The currently selected value.
Therefore, when the form is posted you retrieve from the posted data and that is the value.
Something like this:
< select name=“food”>< option value=“bread”>bread< /option>< option value=“corn”>corn< /option>< /select>
// In the PHP posted code area:
$selected_food = filter_input(INPUT_POST, “food”);
and that gives you the value selected…
Hope that is what you are asking for…
I was bored so I did a little test php in thinking what you were after?
<?php
require_once 'assets/config/config.php';
require_once "vendor/autoload.php";
/*
* Database Connection
*/
$db_options = [
/* important! use actual prepared statements (default: emulate prepared statements) */
PDO::ATTR_EMULATE_PREPARES => false
/* throw exceptions on errors (default: stay silent) */
, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
/* fetch associative arrays (default: mixed arrays) */
, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];
$pdo = new PDO('mysql:host=' . DATABASE_HOST . ';dbname=' . DATABASE_NAME . ';charset=utf8', DATABASE_USERNAME, DATABASE_PASSWORD, $db_options);
/* Retrieve additional information need after user selects bread type */
if (isset($_POST['submit'])) {
$type = $_POST['type'];
$stmt = $pdo->prepare('SELECT * FROM food WHERE bread=:type');
$stmt->execute([':type' => $type]);
$record = $stmt->fetch();
$message = $record['bread'] . ' has this many Carbohydrates ' . $record['Carbohydrate'] . '!';
}
$stmt = $pdo->query('SELECT * FROM food'); // Grab the Data from the database table:
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<!-- Post Information that user selects -->
<p> <?= ($message ?? null); ?></p>
<!-- User Selects bread type -->
<form action="" method="post">
<select id="bread" class="select-css" name="type" tabindex="1">
<?php
while ($row = $stmt->fetch()) {
echo '<option value="' . $row['bread'] . '">' . $row['bread'] . '</option>';
}
?>
</select>
<input id="submitBtn" type="submit" name="submit" value="select" tabindex="2">
</form>
</body>
</html>
Of course you would have to put in your own database connection and database table requirement, plus no security was taken to sanitize the string. This isn’t exactly what you need to do, but I think it will get you on the right track?
Here’s a quick dump out of the table
--
-- Table structure for table `food`
--
CREATE TABLE `food` (
`id` int(3) NOT NULL,
`bread` varchar(60) DEFAULT NULL,
`Carbohydrate` varchar(60) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `food`
--
INSERT INTO `food` (`id`, `bread`, `Carbohydrate`) VALUES
(1, 'White', '15g'),
(2, 'Wheat', '10g'),
(3, 'Banana Bread', '33g');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `food`
--
ALTER TABLE `food`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `food`
--
ALTER TABLE `food`
MODIFY `id` int(3) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
I even tested it.
When posting code, either use bbocode [code][/code
] tags or markdown (three back-tacks) around it. I have added bbocde tags to your posts in this thread.
Thank you so much it works but in the database has strange characters due to the Swedish letters å ä ö. I have entered UTF8 in all places.
I guess htmlentities should be used in some way.
I also have to figure out how to display the values in text boxes.
I do not request whole scripts but I am grateful for some tips.
Before you make your database connection, add this line:
mysql_set_charset("utf8");
Then, it should retrieve the data correctly.
It did not work with mysql_set_charset ("utf8") ;
I get the error message: Uncaught Error: Call to undefined function [mysql_set_charset () in /.
The page is saved in utf8. I also have UTF8 in the header and dbconnection.php. In the first script I showed, å, ä and ö worked. Do you have any tips?
I am so sorry! it is mysqli_set_charset NOT mysql_ My typing error.
Also, I was just pointing you to that function, to actually use it, you need to do it like this. Right after setting up the connection. In this case, let’s say you set it up with $conn = your.connection… Then, use this:
mysqli_set_charset($conn,“utf8”);
Hope that works for you…
No it did not work.
I now have the following code: \\ $ db_options = [
PDO :: ATTR_EMULATE_PREPARES => false
, PDO :: ATTR_ERRMODE => PDO :: ERRMODE_EXCEPTION
, PDO :: ATTR_DEFAULT_FETCH_MODE => PDO :: FETCH_ASSOC
];
$ conn = mysqli_connect ($ hostname, $ DB_USER, $ DB_PASSWORD, $ dbname);
mysqli_set_charset ($ conn, “utf8”);
$ pdo = new PDO (‘mysql: host =’. $ hostname. ‘; dbname =’. $ dbname. ‘; charset = utf8’, $ DB_USER, $ DB_PASSWORD, $ db_options); \
I have UTF8 after $pdo too.
I know it’s not possible to mix them. I was just going to show how it turned out.
For PDO you would do it something like this… Not tested…
$dbh = new PDO("mysql:$connstr", $user, $password);
$dbh->exec("set names utf8");
If I after — dbname = — write the real db name
and not $ … everything works fine.
I probably wrote it in the wrong way.
But what about security?
All of those examples expect you set up the username, password and dbname in string variables before you execute the commands. Any time you ever see a question mark, " $ ", in PHP it means it is a variable that you previously set up for use.