Given the code below when I select a value from my dropdown box [S, M, L] and hit submit I get one of the following outputs:
S is equal to
M is equal to
L is equal to
I would like the output to be along the lines of
S is equal to Small
M is equal to Medium
L is equal to Large
Can something be added to my code to accomplish this? Or do I need to take a different approach?
<form action="?" method="post">
<?php
$size = array();
$size[] = "";
$size[] = "S";
$size[] = "M";
$size[] = "L";
if(isset($_REQUEST['list'])){
echo $size[(int)$_REQUEST['list']]." is equal to "."<br />";
}
echo '<select name="list">'."\n";
$count = 0;
foreach($size as $size){
echo '<option value="'.$count.'">'.$size.'</option>'."\n";
$count++;
}
echo '</select>';
?>
<input type="submit" value="submit" />
</form>
<form action="?" method="post">
Why not use an associative array and then you don't have to mess around with ints or $counts?
<form action="?" method="post">
<?php
$sizes = array(
"S" => "Small",
"M" => "Medium",
"L" => "Large"
);
if(isset($_REQUEST['list'])){
echo "<p>" . $_REQUEST['list'] . " is equal to " . $sizes[$_REQUEST['list']] . "</p>";
}
?>
<select name="list">
<option value="">Choose one</option>
<?php
foreach($sizes as $key => $val){
echo "<option value='$key'>$key - $val</option>\n";
}
?>
</select>
<input type="submit" value="submit" />
</form>
The output will look something like this:
S is equal to Small
+------------+-+
| Choose one |▼|
+------------+-+
| S - Small |
| M - Medium |
| L - Large |
+--------------+
With this solution you can reuse the original static array to populate the post echo. Also try to avoid using \n in your html instead use the semantic <br>.
<form action="?" method="post">
<?php
$size = array(""=>"","Small"=>"S","Medium"=>"M","Large"=>"L");
if(isset($_REQUEST['list'])){
echo $size[$_REQUEST['list']]." is equal to ".$_REQUEST['list']."<br />";
}
echo "<select name='list'>";
foreach($size as $key=>$value){
echo "<option value='$key'>$value</option>";
}
echo '</select>';
?>
<input type="submit" value="submit" />
</form>
You need to make the array $sizes, then foreach ($sizes as $size) for your loop. THen in the echo you need this:
if(isset($_REQUEST['list'])){
switch($size[$_REQUEST['list']])
{
case "S":
$size = "Small";
break;
case "M":
$size = "Medium";
break;
case "L":
$size = "Large";
break;
}
echo $size[(int)$_REQUEST['list']] . " is equal to " . " . $size . "<br />";
}
But really you would be far better using the letters as keys for the array, and the sizes as the values: $sizes['S'] = "Small" then it would be simply in your loop
foreach ($sizes as $key => $size)
{
echo "<option value='" . $key . "'>" . $size . "</option>";
}
and to display:
$_REQUEST['list'] . " is equal to " . " . $sizes['$_REQUEST['list']] . "<br />";
You can get your desired result from rewriting your code using nested arrays for your size array like:
$size = array();
$size[] = "";
$size[] = array("S", "Small");
$size[] = array("M", "Medium");
$size[] = array("L", "Large");
if(isset($_REQUEST['list'])){
echo $size[(int)$_REQUEST['list']][0]." is equal to ". $size[(int)$_REQUEST['list']][1] ."<br />";
}
echo '<select name="list">'."\n";
$count = 0;
foreach($size as $size){
echo '<option value="'.$count.'">'.$size[0].'</option>'."\n";
$count++;
}
echo '</select>';
?>
<input type="submit" value="submit" />
</form>
Im not sure I get your problem right
But why not set the value to Small, Medium & Large while you keep the output S, M, L if you want that.
Then S = Small.
Related
OK let me be as specific as possible.... I would like to change the way my search bar behaves. Right now the string has to match the MySQL query exactly!!! or it won't show my products.
Here is what I got:
A search for "case iphone"
searchitems.php?tosearch=case+iphone&Search=Search
Now a search for "iphone case"
searchitems.php?tosearch=iphone+case&Search=Search
Now based on how the query would work...if I type in the URL manually to this... it works how I want it to:
searchitems.php?tosearch=%iphone%&%case%&Search=Search
So how do I go about changing the URL from
searchitems.php?tosearch=case+iphone&Search=Search
to
searchitems.php?tosearch=%iphone%&%case%&Search=Search
Here is the code that I have so far:
Search Form In index.php
<form method="GET" action="searchitems.php">
<input size="50" type="text" name="tosearch" value="Search" name="keyword" id="keyword" title="keyword" onfocus="clearText(this)" onblur="clearText(this)" class="txt_field">
<input type="submit" name="Search" value="Search" alt="Search" id="searchbutton" title="Search" class="sub_btn">
</form>
searchitems.php (Sorry if it isn't tabbed correctly just copied and pasted)
<?php
include('core/header2.php');
include ('core/connectdb.php');
if(isset($_GET['tosearch'])) {
$tosearch=$_GET['tosearch'];
$tosearch=urldecode($tosearch);
$tosearch = preg_replace('!\s+!', ' ', trim($tosearch));
$search_terms = explode(' ',$tosearch);
$search_terms[] = $tosearch;
$search_terms=array_unique($search_terms);
$query = "select * from products where ";
$query_fields = Array();
$sql = "SHOW COLUMNS FROM products";
$columnlist = $connect->query($sql);
while($arr = $columnlist->fetch_assoc()){
extract($arr);
$query_fields[] = $Field . " LIKE ('%". $tosearch . "%')";
}
$query .= implode(" OR ", $query_fields);
$results = mysqli_query($connect, $query) or die(mysql_error());
$rows = $results->num_rows;
if ($rows > 0) {
$cols = 5;
$counter = 1;
$nbsp = $cols - ($rows % $cols);
echo '<div id="content" class="float_r">';
echo "<table border=\"0\">";
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
if(($counter % $cols) == 1) { // Check if it's new row
echo '<tr align="center">';
}
extract($row);
echo '<td valign="top" style="padding-right:15px;">';
echo "<a href=itemdetails.php?itemcode=$item_code>";
echo '<img src=' . $imagename . ' style="max-width:120px;max-height:140px;
width:auto;height:auto;"></img><br/>';
echo $item_name .'<br/>';
echo "</a>";
echo '<div class="product_price">$'. $price .'</div>';
echo "<form method=\"POST\" action=\"cart.php?action=add&icode=$item_code&iname=$item_name&iprice=$price&ilocation=$location\">";
echo "<input type=\"submit\" name=\"addtocart\" value=\"Add To Cart\"></form>";
echo "</td>";
if(($counter % $cols) == 0 ){
echo "</tr>";
}
$counter++;
}
if($nbsp > 0) { // Add unused column in last row
for ($i = 0; $i < $nbsp; $i++) {
echo '<td> </td>';
}
echo '</tr>';
}
}
}
echo '</table></div><div class="cleaner"></div>';
include('core/footer.php');
?>
well, brother, it's a bad approach how you doing it. But for learning, its fine. For + sign issue, you can use php urldecode, example:
<?php
$tosearch = 'a+b';
echo urldecode($tosearch);
it has its own pro/con thing but on high-level it will work for you, you can dig more into it if you like.
My main question is why is PDO::exec not executing every iteration of my loop, and instead only executing in the first iteration.
I am trying to insert coordinates into my MySQL database.
My database structure is (number(primary key), x, y, z).
I ask the user to insert a number ($n), and then ask them to fill in $n sets of coordinates.
The users inputs are passed to another page with $_POST, then retrieved by dynamic variable names and inserted into the database.
Everything works, except the loop only writes to the database its first iteration. So I end up with results for x1,z1,y1 but nothing else.
Can anyone explain what I am doing wrong (other than not using arrays)?
<?php
require_once('db.php');
$n = $_POST['selectOption'];
for($i = 1; $i < $n+1;$i++){
${'x' . $i} = $_POST["x" . $i];
${'y' . $i} = $_POST["y" . $i];
${'z' . $i} = $_POST["z" . $i];
$rowsAffected = $db->exec("INSERT INTO coordinate3d (number,x,y,z)
VALUES ('$n', '${'x' . $i}', '${'y' . $i}', '${'z' . $i}')");
}
?>
Here is my form
<form action="aaron_stockdale_dynamic_process.php" method="post" name="coordinateForm">
<?php
for($i = 0; $i < $n; $i++)
{
?>
x<?php echo $i+1;?> <input name="x<?php echo $i+1;?>" type=text>, y<?php echo $i+1;?> <input name="y<?php echo $i+1;?>" type=text>, z<?php echo $i+1;?> <input name="z<?php echo $i+1;?>" type=text><br>
<?php
}
?>
<br>
<input type="hidden" name="selectOption" value="<?php echo $n;?>">
<input type="submit" oonClick="document.location.href='aaron_stockdale_dynamic_process.php'" value="Submit">
</form>
require_once('aaron_stockdale_database.php');
$n = $_POST['selectOption'];
for($i = 1; $i < $n+1;$i++){
$x = $_POST["x" . $i];
$y = $_POST["y" . $i];
$z = $_POST["z" . $i];
$rowsAffected = $db->exec("INSERT INTO coordinate3d (number,x,y,z)
VALUES ('$n', '$x', '$y', '$z')");
}
the rest is on you ;)
And also check if any of the fields a primary key, that will prevent insert it twice.
Since you have received an acceptable answer for your question, I'd like to give you a hint on your html code.
<form action="aaron_stockdale_dynamic_process.php" method="post" name="coordinateForm">
<?php
for($i = 0; $i < $n; $i++)
{
?>
x<?php echo $i+1;?> <input name="x<?php echo $i+1;?>" type=text>, y<?php echo $i+1;?> <input name="y<?php echo $i+1;?>" type=text>, z<?php echo $i+1;?> <input name="z<?php echo $i+1;?>" type=text><br>
<?php
}
?>
<br>
<input type="hidden" name="selectOption" value="<?php echo $n;?>">
<input type="submit" oonClick="document.location.href='aaron_stockdale_dynamic_process.php'" value="Submit">
</form>
Now, this code can be cleaned up a bit.
<form action="aaron_stockdale_dynamic_process.php" method="post" name="coordinateForm">
<?php
for($i = 0; $i < $n; $i++)
{
echo 'x' . $i+1 . '<input name="x' . $i+1 . '" type=text>, y' . $i+1 . ' <input name="y' . $i+1. '" type=text>, z' . $i+1 . '<input name="z' . $i+1 . '" type=text><br>'
}
?>
<br>
<input type="hidden" name="selectOption" value="<?php echo $n;?>">
<input type="submit" value="Submit">
</form>
I changed the "oonClick" to "onClick", and then afterwards I removed it, as when you submit, you don't need to navigate, as the browser will do this, upon submission.
And then I removed the repetitive opening and closing of php tags, and combined all the echos into one.
Here's my solution in one file:
<!DOCTYPE html>
<html lang=en>
<head>
<script>
function validcoord(e) {
var key;
var keychar;
if (window.event)
key = window.event.keyCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);
keychar = keychar.toLowerCase();
// control keys
if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
return true;
// Numeral Characters
else if ((("0123456789-.,").indexOf(keychar) > -1))
return true;
else
return false;
}
</script>
<style>
input[type="number"] { text-align: right; width: 50px; }
label { margin-left: 4em; }
</style>
</head>
<body>
<?php
define ("SELF", $_SERVER['PHP_SELF']);
define ("EOL", "\r\n");
// Modify as needed
define ("MINNUMCORDS" , "1");
define ("MAXNUMCORDS" , "10");
define ("DFLTNUMCORDS", "2");
$formSubmitted = (empty($_POST)) ? FALSE : TRUE;
if (!$formSubmitted) {
$htmlOutput = '
<form action="' . SELF . '" method=post name=foo id=foo>
<input type=hidden name=current value=0>
<label>Enter the number of Coordinates:
<input type=number autofocus onFocus="this.select()"' .
' min=' . MINNUMCORDS .
' max=' . MAXNUMCORDS .
' value=' . DFLTNUMCORDS .
' name=numcords /></label>
</form>' . EOL;
echo $htmlOutput;
} // end if not submitted
else { // a form HAS been submitted
foreach ($_POST as $key => $value) { $$key = $value; }
unset($_POST);
if (!empty($coord)) { // We got some input that may be a valid x,y,z coordinate
if ( substr_count($coord, ",") != 2 ) {
$error = "We're looking for THREE numbers seperated by TWO commas.";
} // end if we don't have three values
else { // We got three Values
$coord = trim($coord);
list($x,$y,$z) = explode(",", $coord);
if ( !(is_numeric($x) && is_numeric($y) && is_numeric($z)) ) {
$error = "We're looking for three VALID NUMBERS seperated by two commas.";
} // end if all three numbers are not valid
else { // We got three Values and each of them are numbers
require('db.php');
$rowsAffected = $db->exec("INSERT INTO coordinate3d (number,x,y,z)
VALUES ('$numcords', '$x', '$y', '$z')");
//echo "INSERT INTO coordinate3d (number,x,y,z) VALUES ('$numcords', '$x', '$y', '$z')<br />" . EOL;
} // end three valid numbers
} // end three values
} // end if we have some input in $coord
if ($error) {
echo "~~ " . $error . "<br /><br />" . EOL;
--$current;
} // end if error
if ( $current < $numcords ) {
$htmlOutput = 'Please enter the coordinate in the form: x,y,z (Ex: -.4,2,8.5)' . EOL;
$htmlOutput .= '<form action="' . SELF . '" method=post name=bar id=bar>' . EOL;
$htmlOutput .= ' <input type=hidden name=numcords value="' . $numcords . '" />' . EOL;
$htmlOutput .= ' <input type=hidden name=current value="' . ++$current . '" />' . EOL;
$htmlOutput .= ' <label>Coord #' . $current . ': ';
$htmlOutput .= '<input type=text name=coord size=12 maxlength=48 ' .
'autofocus onKeyPress="return validcoord(event);" /></label>' . EOL;
$htmlOutput .= '</form>' . EOL;
echo $htmlOutput;
} // end if we need to get another coord
} // end form was submitted
?>
</body>
</html>
I have a form with a loop inside.
Here is my code:
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<?php
for ($i = 1; $i <= 2; $i++) {
echo "Numero ";
echo $i;
echo "<input type='text' name='number2[$i]' id='number2{$i}' />";
}
?>
<input type="submit" name="submitbutton" value="Confirm!">
</form>
<?php
print_r( $_POST );
if(!isset($submitbutton)) {
if (isset($_POST['number2']) != "") {
echo "<b>{$_POST['number2']}</b>, !\n";
$nI = $_POST['number2'];
}
}
?>
The output I get is:
Array ( [number2] => Array ( [1] => 3 [2] => 4 ) [submitbutton] => Confirm! ) Array, !
I would like to know how can I put the number in a session.
For example Session[1]=3, Session[2]=4
I try with array and foreach but I always get error.
Something like this should work for you:
<?php
// Start a PHP Session
session_start();
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<?php
for ($i = 1; $i <= 2; $i++) {
echo "Numero ";
echo $i;
echo "<input type='text' name='number2[$i]' id='number2{$i}' />";
}
?>
<input type="submit" name="submitbutton" value="Confirm!">
</form>
<?php
// If the form was submitted and number2 is an array
if(isset($_POST['submitbutton'])
&& isset($_POST['number2'])
&& is_array($_POST['number2'])) {
// Loop through each posted value and save it to the session
foreach ($_POST['number2'] as $key => $value) {
$_SESSION["number2_{$key}"] = $value;
}
}
echo "number2_1 = " . $_SESSION["number2_1"] . "<br />";
echo "number2_2 = " . $_SESSION["number2_2"] . "<br />";
?>
What error are you getting? Note that isset() merely returns TRUE or FALSE, so isset($_POST['number2']) will never equal the empty string.
I got this piece of code here...
<form action="InvoiceNotice.php?action=invoicenotice" method="post">
<label for="fordays">Select Day</label>
<select name="daySelected" id="daySelected">
<option value="0">Today</option>
<?php
$array = array_combine(range(1,$InvoiceDaysArray['days']), range(1,$InvoiceDaysArray['days']));
foreach($array as $row => $value){
$selected = '';
$daySelected = 0;
if($daySelected == $row){
$selected = 'SELECTED';
}
echo "<option selected='" . $selected . "' value='" . $row . "'>" . $value . " days ago</option>";
}
?>
</select>
<input type="submit" name="button" id="button" value="Submit" />
</form>
My issue is with the $selected the $daysSelected variable comes from what has been selected. What I am trying to do is when a user selects an option, that option is now selected in the dropdown and the page returns, after the client hits submit.
Does any one know what I am talking about?
Thanks
I would do something like:
foreach($array as $row => $value){
$selected = '';
if($_POST['daySelected'] == $row){
$selected = ' selected="selected"';
}
echo "<option" . $selected . " value='" . $row . "'>" . $value . " days ago</option>";
}
Although you probably only need selected instead of selected="selected".
I see some problems in your code:
first you are setting $daySelected = 0; and then try compare with variable from database, day 0 is not in your foreach loop try this
<form action="InvoiceNotice.php?action=invoicenotice" method="post">
<label for="fordays">Select Day</label>
<select name="daySelected" id="daySelected">
<option value="0">Today</option>
<?php
$array = array_combine(range(1,$InvoiceDaysArray['days']), range(1,$InvoiceDaysArray['days']));
foreach($array as $row => $value){
$selected = '';
$daySelected = $_POST['daySelected'];
if($daySelected == $row){
$selected = "selected=SELECTED";
}else {$selected='';}
echo "<option '" . $selected . "' value='" . $row . "'>" . $value . " days ago</option>";
}
?>
</select>
<input type="submit" name="button" id="button" value="Submit" />
</form>
I have a form that records various fields with a variable name in autoincrement.
when I save my my form variables looks like
<form>
<?php
$i = 1;
foreach ($variables as $var ) {
echo '<input type="text" name="txt$i" value="$var->name" />';
$i ++;
}
?>
</form>
And my question is how to display the value of the input field, i make that, but not working
<?php
foreach ($variables as $var) {
echo $var->txt$i;
$i ++;
}
?>
There are couple of bugs in both of your scripts. Here they are fixed.
<form>
<?php
$i = 1;
foreach ($variables as $var ) {
echo '<input type="text" name="txt' . $i . '" value="' . $var->name . '" />';
$i++;
}
?>
</form>
<?php
$i = 1;
foreach ($variables as $var) {
echo $var->{"txt" . $i};
$i++;
}
?>
In PHP, single-quoted strings do not allow for variable interpolation.
Try:
echo '<input type="text" name="txt' . $i . '" value="' . $var->name . '" />';
This is happening because you are using single quotes:
echo '<input type="text" name="txt$i" value="$var->name" />';
and inside single quotes variable interpolation does not happen.
Instead use:
echo '<input type="text" name="txt'.$i.'" value="'.$var->name.'" />';
This should work,
<form>
<?php
$variables = array("red","yellow","blue","orange","green");
$i = 1;
foreach ($variables as $var ) {
$name = "txt".$i;
echo "<input type='text' name='".$name."' value='".$var."' />";
$i++;
} ?>
</form>
You need to put variables in double quotes, i thought it would be easier to create a name variable and concatenate the incremented value on to the end of it
Can't get what you want from your question.
May be just
echo $txt.$i;
?