I have some Problems with the following code. The hidden field is not posted to the next page. I have tried to put it next to the option field, but that creates some different problems like duplicating the dropdownmenue.
can anyone help me please?
<?php
$dbhost = 'localhost';
$dbuser = '-----';
$dbpass = '-----';
$db = '-----';
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($db);
$query = "SELECT * FROM Eintraege"; $result = mysql_query($query);
?>
<form action="deletescript.php" method="post">
<select name="loeschen">
<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line['ID'];?>"><?php echo $line['Titel'];?></option>
<?php
}
?>
</select>
<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<input type="hidden" name="titel" value="<?php echo $line['Titel'];?>" />
<?php
}
?>
Vorname <br /><input type="text" name="name" value="" class="text" /><br /><br />
Name <br /><input type="text" name="vorname" value="" class="text" /><br /><br />
Email <br /><input type="text" name="email" value="" class="text" /><br /><br />
<input type="submit" name="submit" />
</form>
You should at least use mysqli
, making sure you have the connection on a secure page like:
// connect.php
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
You have a couple of other problems too.
1) Since mysql_fetch_array()
always returns the next row of results, when mysql_fetch_array()
is called again in your second while loop, $line
is falsey
, because there are no more rows to fetch, so the loop does not run. You could reset($line)
if you're using fetch like that, but I recommend otherwise.
2) You cannot use the same HTML name
attribute twice, unless you add []
to the end of it. Then you can access it as an Array in PHP.
// otherpage.php
<?php
include 'connect.php'; $db = db(); $opts = $hdns = '';
if($q = $db->query('SELECT * FROM Eintraege')){
if($q->num_rows > 0){
while($r = $q->fetch_object()){
$t = $r->Titel;
$opts .= "<option value='$t'>$t</option>";
$hdns .= "<input name='titel[]' type='hidden' value='$t' />";
}
// now you can echo $opts and $hdns where you want
}
else{
$errors[] = 'No result rows were found';
}
$q->free();
}
else{
$errors[] = 'database connection failure';
}
$db->close(); if(isset($errors))die(implode(' & ', $errors));
?>
To get the titel
named inputs on the page you are submitting to, it's like:
<?php
if(isset($_POST['titel'])){
// get each one
foreach($_POST['titel'] as $t){
// $t is each one
}
}
?>
Note that getting data to put into hidden inputs then sending it back to the server is generally pointless, since you have access to that information anyways. You'll want to learn AJAX if you want something to go to the database based on Client input.