Im a newbie to this forum and have just started coding in php. Need some help. I have the following code
You mean you need the value what you have used to display it. Then, Change to :
<option value="<?php echo $value['profile']; ?>">
<?php echo $value['profile']; ?>
</option>
Give
<option value="<?php echo $value['profile']; ?>"><?php echo $value['profile']; ?></option>
instead of
<option value="<?php echo $key; ?>"><?php echo $value['profile']; ?></option>
It will obviously echo the key, as you assigned the value of options as $key
if you need the options in the $_POST['pty_select']
use this:
<select name="pty_select" >
<?php foreach($results_array as $key => $value){ ?>
<option value="<?php echo $value['profile'];?>"><?php echo $value['profile']; ?></option>
<?php } ?>
</select>
if (isset($_POST['Submit'])) {
echo "<pre>"; echo ($_POST['pty_select']); echo "</pre>"; } ?>
Change it to something like
if(isset($_POST['Submit'])) {
echo $results_array[$_POST['pty_select']]['profile'];
}
Or alternatively use profile option value.
And now let's go to ideal world :)
Build data pairs database_id => name
for options:
$q = "SELECT pty.id, pty.pty_profile_name AS profile FROM pty, users
WHERE users.username = 'testaccount'";
$r = mysqli_query($dbc, $q);
$values = array();
while($r = mysqli_fetch_row($r)) {
$values[$r[0]] = $r[1];
}
Never use @
when working with database, why do you want to suppress errors instead of preventing/handling them?
Now you have real database IDs and respective values (in general, using unique IDs are better... if nothing else they have greater entropy - more efficient search). And sice displaying select box is really common in webs, lets:
function selectbox( $values = array(), $attributes = array(), $selected_value = null)
{
// Header
echo '<select';
foreach( $attributes as $key => $val){
echo ' ' . htmlspecialchars($key) . '="' . htmlspecialchars( $val) . '"';
}
echo '>';
// Values
foreach( $values as $key => $val){
echo '<option value="' . htmlspecialchars( $key) .'"';
if( $key === $selected_value){
echo ' selected="selected"';
}
echo '>' . htmlspecialchars( $val) . '</option>';
}
echo '</select>';
}
And now usage :)
<form method="post" action="foreach2.php">
<label for="Property Select" class="title">Select Property</label>
<?php selectbox( $values, array( 'name' => 'pty_select')); ?>
<input type="submit" name="Submit" />
</form>
And what to do with it then?
$id = (int)(isset( $_POST['pty_select']) ? $_POST['pty_select'] : 0);
$name = null;
if( $id && isset( $values[$id])){
$name = $values[$id];
}