So, i have this foreach loop that runs a sql query. Every row is printed in a option. I have two forum posts. One that 'deletes' the row and one that 'uses' the row. But when I post the form the content inside the option remains empty. Here is my code:
Post file
<?php
try {
$DB = new PDO ('mysql:host=localhost;dbname=pre_messages', $DBuser, $DBpassword);
$sql = "SELECT * FROM message";
?>
<html>
<form action="action.php" method="post">
<select><?php
foreach ($DB->query($sql) as $row)
{
?>
<option name="content" value="<?php echo $row['Title']; ?>"><?php echo $row['Title']; ?></option>
<?php } ?>
</select>
<br /><input type="submit" value="use" name="use">
<input type="submit" value="delete" name="delete">
</form>
</html>
Action.php
<?php
require_once 'hidden/session.php';
$delete = $_POST['delete'];
$use = $_POST['use'];
$content = $_POST['content'];
try {
$DB = new PDO ('mysql:host=localhost;dbname=pre_messages', $DBuser, $DBpassword);
$delete = "DELETE FROM message WHERE title='$content'";
if (isset($delete)){
$DB->exec($delete);
}
}
catch (PDOException $e)
{
echo $e->getMessage();
}
In order to post content you have to give name to your control. You have specified name property for option but there is no name property specified in select. Which is why the value of that control is not getting posted. Hence, when you try to access it as $content = $_POST['content']; , it gives you empty value.
Try this:
<html>
<form action="action.php" method="post">
<select id="content" name="content">
<?php foreach ($DB->query($sql) as $row) { ?>
<option value="<?php echo $row['Title']; ?>"><?php echo $row['Title']; ?></option>
<?php } ?>
</select>
<br />
<input type="submit" value="use" name="use">
<input type="submit" value="delete" name="delete">
</form>
</html>
Hope it helps!!