Echo images for multiple checkboxes in PHP? - php

I am making a site with checkboxes for toppings on pizza.
I have the problem that whenever I select one topping it does show and image of that topping but if I select two toppings it still only shows one image.
How can I make it so that it echoes the images of multiple checkboxes?
This is my index.php for the checkboxes and values:
<html>
<head>
</head>
<body>
<form action="process.php" method="POST">
<h4>Kies een Pizza:</h4><br>
<input type="checkbox" name="check[]" value="Pepperoni">Pepperoni<br>
<input type="checkbox" name="check[]" value="Ananas">Ananas<br>
<input type="checkbox" name="check[]" value="Ansjovis">Ansjovis<br>
<input type="checkbox" name="check[]" value="Broccoli">Broccoli<br>
<h4>Kies een bodem:</h4><br><br>
Megadik: <input type="radio" name="bodem" value="Megadik"><br>
Dun: <input type="radio" name="bodem" value="Dun"><br>
Calzone: <input type="radio" name="bodem" value="Calzone"><br>
</p>
<p>
<input type="submit" name="submit[]" value="Koop Pizza">
</p>
</form>
<br/><br/>
Home
</body>
</html>
And this is my process.php where it needs to happen:
<html>
<?php
if(isset($_POST['bodem']) && ($_POST['check'])){
$bodem = $_POST["bodem"];
echo("Je koos een pizza met:<br/> ");
}
else{
echo("Geen pizza gekozen!");
}
$selected_radio = $_POST['bodem'];
if(isset($_POST['submit'])){}
if(!empty($_POST['check'])){}
foreach($_POST['check'] as $selected){
echo $selected."</br>";
}
//Toppings
if (($selected == 'Pepperoni')) {
echo "<IMG SRC=\"pepperoni.jpg\">";
}
if (($selected == 'Ananas')) {
echo "<IMG SRC=\"ananas.jpg\">";
}
if (($selected == 'Ansjovis')) {
echo "<IMG SRC=\"ansjovis.jpg\">";
}
if (($selected == 'Broccoli')) {
echo "<IMG SRC=\"broccoli.jpg\">";
}
//Bodems
if(($selected_radio == 'Megadik')) {
echo ("<p>En de bodem Megadik</p>");
echo "<IMG SRC=\"megadik.jpg\">";
}
if(($selected_radio == 'Dun')) {
echo ("<p>En de bodem Dun</p>");
echo "<IMG SRC=\"dun.jpg\">";
}
if(($selected_radio == 'Calzone')) {
echo ("<p>En de bodem Calzone</p>");
echo "<IMG SRC=\"calzone.png\">";
}
?>
<br/><br/>
Home
</html>
Im sorry its in Dutch.

The value of $selected is updated each iteration of the loop. Then when the loop is done it will keep the last value. It will not "remember" all the values it had while looping. So you need to echo the img tag in the loop (or, if you want them separately somewhere else, in another loop).
Also, you can shorten the code by not having an if clause per topping, but instead using the fact that the file names of the images correspond to the topping names.
Then you get something like this:
foreach($_POST['check'] as $selected) {
echo $selected . "</br>";
echo "<img src=\"" . $selected . ".jpg\">";
}
Or if you want the separately:
foreach($_POST['check'] as $selected) {
echo $selected . "</br>";
}
//Some other stuff...
foreach($_POST['check'] as $selected) {
echo "<img src=\"" . $selected . ".jpg\">";
}
Please note that is is recommended to write HTML tags in lowercase.

What happens when this piece of code executes:
foreach ($_POST['check'] as $selected){
echo $selected."</br>";
}
On each iteration you echo the value. But when foreach is over $selected value is the last value of $_POST['check']. So, only your last value is checked against you if statements.
So the answer is - move your if statements into a foreach loop.

You get this error because you change the value of $selected inside the loop, but then check it outside the loop after it finishes:
You could make life easier on yourself by just applying the image inside your loop:
foreach($_POST['check'] as $selected){
echo $selected."</br>";
echo "<IMG SRC=\"{$selected}.jpg\">";
}
Here is a working sample: https://eval.in/437716

Related

displaying mulitiple field of checkbox with php

i have a form with different checkbox fields. However, I was able to display their values using a foreach loop but was wondering if it possible to display them via how they are selected. below is my code.
<html>
<head></head>
<body>
<form action="states.php" method="post">
Draft<input type="checkbox" name="states[]" id="design_states" value="Draft">
Design<input type="checkbox" name="states[]" id="design_states" value="design">
Review<input type="checkbox" name="states[]" id="design_states" value="Review">
Approved<input type="checkbox" name="states[]" id="design_states" value="Approved">
Issued For Construction<input type="checkbox" name="states[]" id="color" value="Issued For Construction">
<input type="submit" value="submit">
</form>
<body>
</html>
<?php
if(isset($_POST['states'])) {
$name = $_POST['states'];
echo "You chose the following workflow: <br>";
foreach ($name as $states){
echo $states."<br />";
}} // end brace for if(isset
else {
echo "You did not choose a workflow.";
}
?>
if a user picks issued for construction first followed by draft I want that values to be displayed as picked not draft first and then issued for construction.
echo "You chose the following workflow: <br>";
foreach (array_intersect($states, $name) as $state){
echo $state."<br />";
}
echo "You don't chose the following workflow: <br>";
foreach (array_diff($states, $name) as $state){
echo $state."<br />";
}

Best Solution for this array

I am using checkboxes to query the database and I am struggling with this one, I am new to MySQL and PHP so sorry if this is simple!
Here is my code that I have...
<input type="checkbox" name="season2005" value="2005" <?php if(isset($_POST['season2005'])) echo "checked='checked'"; ?> > 2005-06
<input type="checkbox" name="season2006" value="2006" <?php if(isset($_POST['season2006'])) echo "checked='checked'"; ?> > 2006-07
<input type="checkbox" name="season2007" value="2007" <?php if(isset($_POST['season2007'])) echo "checked='checked'"; ?> > 2007-08
<input type="checkbox" name="season2008" value="2008" <?php if(isset($_POST['season2008'])) echo "checked='checked'"; ?> > 2008-09
<input type="checkbox" name="season2009" value="2009" <?php if(isset($_POST['season2009'])) echo "checked='checked'"; ?> > 2009-10
<input type="checkbox" name="season2010" value="2010" <?php if(isset($_POST['season2010'])) echo "checked='checked'"; ?> > 2010-11
<input type="checkbox" name="season2011" value="2011" <?php if(isset($_POST['season2011'])) echo "checked='checked'"; ?> > 2011-12
<input type="checkbox" name="season2012" value="2012" <?php if(isset($_POST['season2012'])) echo "checked='checked'"; ?> > 2012-13
<input type="checkbox" name="season2013" value="2013" <?php if(isset($_POST['season2013'])) echo "checked='checked'"; ?> > 2013-14
if (#$_POST['season2005'] == ""){ $season2005 = "0000"; } else { $season2005 = "2005"; }
if (#$_POST['season2006'] == ""){ $season2006 = "0000"; } else { $season2006 = "2006"; }
if (#$_POST['season2007'] == ""){ $season2007 = "0000"; } else { $season2007 = "2007"; }
if (#$_POST['season2008'] == ""){ $season2008 = "0000"; } else { $season2008 = "2008"; }
if (#$_POST['season2009'] == ""){ $season2009 = "0000"; } else { $season2009 = "2009"; }
if (#$_POST['season2010'] == ""){ $season2010 = "0000"; } else { $season2010 = "2010"; }
if (#$_POST['season2011'] == ""){ $season2011 = "0000"; } else { $season2011 = "2011"; }
if (#$_POST['season2012'] == ""){ $season2012 = "0000"; } else { $season2012 = "2012"; }
if (#$_POST['season2013'] == ""){ $season2013 = "0000"; } else { $season2013 = "2013"; }
$seasons = array($season2005,$season2006,$season2007,$season2008,$season2009,$season2010,$season2011,$season2012,$season2013);
$seasonpick = implode(",",$seasons);;
$matcharrays = array("AND season in ($seasonpick)");
At the moment all of the data is being queried to the database, so if nothing is selected them then part of query from this is "AND season in (0000,0000,0000,0000) etc
How would I go about only getting those selected into the array and if none are selected then the array would be blank.
Hope you understand what I mean!
Here is a working form with some checkboxes that will allow you to test and get the sql you intended.
<?php
$dateArr=array();
if(isset($_POST['season']))
{
$dateArr=array_unique($_POST['season']);
$dateSearch=implode(",", $dateArr);
$sql=".... and season in (".$dateSearch.")";
echo $sql;
}
?>
<html>
<form action="?" method="post">
<?php
for($i=0;$i<10;$i++)
{
echo "<input type=\"checkbox\" name=\"season[]\" value=\"".($i+2005)."\"> ".($i+2005);
}
?>
<input type="submit">
</form>
Output when 2009, 2010 and 2011 selected:
.... and season in (2009,2010,2011)
Okay, so how it works:
Checkboxes are best used when they all have the same name ending in a []. This makes it a nice array on it's own.
If post data is set, we then quickly throw an array unique over it (good habit for the most part in these types of queries) so that there are no duplicate values.
Then simply implode it into a string and pop it into the SQL query.
Edit: Added functionality to re-check checkboxes when submitted.
<?php
$dateArr=array();
if(isset($_POST['season']))
{
$dateArr=array_unique($_POST['season']);
$dateSearch=implode(",", $dateArr);
$sql=".... and season in (".$dateSearch.")";
echo $sql;
}
?>
<html>
<form action="?" method="post">
<?php
for($i=0;$i<10;$i++)
{
$chk="";
if(!empty($_POST['season']))
{
if(in_array($i+2005, $_POST['season']))
{
$chk=" checked=\"checked\" ";
}
}
echo "<input type=\"checkbox\" name=\"season[]\" ".$chk." value=\"".($i+2005)."\"> ".($i+2005);
}
?>
<input type="submit">
</form>
Edit 2: Just add quotes in the right places :)
<?php
$dateArr=array();
if(isset($_POST['season']))
{
$dateArr=array_unique($_POST['season']);
$dateSearch=implode("', '", $dateArr);
$sql=".... and season in ('".$dateSearch."')";
echo $sql;
}
?>
<html>
<form action="?" method="post">
<?php
for($i=0;$i<10;$i++)
{
$chk="";
if(!empty($_POST['season']))
{
if(in_array(($i+2005)."i", $_POST['season']))
{
$chk=" checked=\"checked\" ";
}
}
echo "<input type=\"checkbox\" name=\"season[]\" ".$chk." value=\"".(($i+2005)."i")."\"> ".($i+2005)."i";
}
?>
<input type="submit">
</form>
Edit 3: I feel like this is starting to really answer much more than one question :)
You can simply check the textbox to make sure it isn't empty and then append to a SQL string:
$sql="";
if(!empty($_POST['text1']))
{
$sql.=" and ftgf>= ".$_POST['text1']." ";
}
Having said that, I would strongly suggest that you NEVER allow the user to enter in parts of the actual SQL you will run - unless it is a closed/secure environment, which means NOT an ope website.
Insert the below code
$seasons = array($season2005,$season2006,$season2007,$season2008,$season2009,$season2010,$season2011,$season2012,$season2013);
//start
$seasons2 = array();
foreach ($seasons as $season)
{
if($season!=="0000")
{
array_push($seasons2,$season);
}
}
$seasonpick = implode(",",$seasons2);
//end

Insert group only if checkbox is checked

I am a little stuck with this. I am trying to insert groups of items only if that groups checkbox is clicked. I have tested the SQL insert without the checkboxes, and the SQL works perfectly and inserts the data. But when I added the checkboxes and if/else statement, it started to give me troubles.
For example:
-If I select group 1 and not group 2 - the SQL works correctly only inserting group 1 data
-If I select group 2 and not group 1 - The insert still inserts group 1 data
-If I select group 1 and group 2 - The SQL inserts two rows of group 1 data
-If I do not select any groups, then I get "Warning: Invalid argument supplied for foreach() in /home..." - which I will sort out later.
I have marked "Group 1" and "Group 2". I need the code to insert only the groups if checkbox is clicked, and ignore the non clicked checkbox groups. Any help would be great. Thanks.
I have been testing with the following code:
Form:
<form id="Form" method="post" action="/random.php" name="Form">
<input id="itemCurrency" type="hidden" value="2" name="itemCurrency"></input>
<div class="row">
<div class="col-lg-4">
<div class="itemHolder">
<img class="itemImg thumbnail" src="http://images.com/i/images.jpg"></img>
<div class="itemName">swim Shorts Wi...</div><
<div class="itemPrice">$33.33</div>
<div class="itemHref"><a target="_blank" href="http://random.com/product.aspx?id=40"> Visit Item Page </a></div>
</div>
</div>
//GROUP 1
<input id="itemCheckBox[]" type="checkbox" value="checked" name="itemCheckBox[]"></input>
<input id="itemName[]" type="hidden" value="some random text" name="itemName[]"></input>
<input id="itemHref[]" type="hidden" value="http://random.com/product.aspx?id=2140" name="itemHref[]"></input>
<input id="itemImg[]" type="hidden" value="http://images.com/i/image1s.jpg" name="itemImg[]"></input>
<input id="itemPrice[]" type="hidden" value="$37.33" name="itemPrice[]"></input>
//END GROUP 1
<div class="col-lg-4">
<div class="itemHolder">
<img class="itemImg thumbnail" src="http://images.com/i/image_xl.jpg"></img>
<div class="itemName">Bomber Jacket With Fur</div>
<div class="itemPrice"> $88.88</div>
<div class="itemHref"><a target="_blank" href="http://random.com/Bomber-Jacket-With-fur/..">Visit Item Page</a></div>
</div>
</div>
//GROUP 2
<input id="itemCheckBox[]" type="checkbox" value="checked" name="itemCheckBox[]"></input>
<input id="itemName[]" type="hidden" value="Bomber Jacket With Fur" name="itemName[]"></input>
<input id="itemHref[]" type="hidden" value="http://random.com/Bomber-Jacket-With-fur/.." name="itemHref[]"></input>
<input id="itemImg[]" type="hidden" value="http://images.com/i/image_xl.jpg" name="itemImg[]"></input>
<input id="itemPrice[]" type="hidden" value="$88.88" name="itemPrice[]"></input>
//END GROUP 2
<input id="site" type="hidden" value="1" name="site"></input>
<input id="submit_form" type="submit" value="yes" name="submit_form"></input>
</form>
PHP
if($submitForm == "yes" && $site == "1") {
foreach($_POST['itemCheckBox'] as $key => $val)
{
$fields[] = array(
'itemCheckBox'=>$_POST['itemCheckBox'] [$key],
'itemName' =>$_POST['itemName'] [$key],
'itemHref' =>$_POST['itemHref'] [$key],
'itemImg' =>$_POST['itemImg'] [$key],
'itemPrice' =>$_POST['itemPrice'][$key] );
//Remove non numaric characters from price(leave commas).
$itemPrice = preg_replace('/[^0-9,.]/s', '', $itemPrice);
//Data fields not in form
$userId = "username";
$userIp = $_SERVER['REMOTE_ADDR'];
$itemType = "ADD LATER";
$itemOutFit = "ADD LATER";
$site = "1";
$itemSale = "1";
//Only insert if checkbox is clicked --NOT WORKING, ????
if (isset($_POST['itemCheckBox'])){
echo "CHECKED";
echo "<br>";
/*** INSERT data ***/
$sql = "INSERT INTO items (userId,itemHref,itemImg,itemPrice,itemName,userIp,itemSite,itemType,itemCurrency,itemOutFit,itemSale) VALUES (:userId,:itemHref,:itemImg,:itemPrice,:itemName,:userIp,:itemSite,:itemType,:itemCurrency,:itemOutFit,:itemSale)";
$q = $conn->prepare($sql);
$q->execute(array(':userId'=>$userId,
':itemHref'=>$itemHref[$key],
':itemImg'=>$itemImg[$key],
':itemPrice'=>$itemPrice[$key],
':itemName'=>$itemName[$key],
':userIp'=>$userIp,
':itemSite'=>$itemSite,
':itemType'=>$itemType,
':itemCurrency'=>$itemCurrency,
':itemOutFit'=>$itemOutFit,
':itemSale'=>$itemSale));
} else {
echo "NOT CHECKED";
echo "<br>";
}
/*
echo $conn->errorCode();
echo "<br>"; ('SET CHARACTER SET utf8')
echo $conn->errorInfo();
echo "<br>";
//die(print_r($q->errorInfo(), true));
*/
}
UPDATE Tried to strip php down to basic code, still no luck. Does the same thing....anyone have an idea how I can fix this.
foreach($_POST['itemCheckBox'] as $key => $val)
{
$i = 0;
$itemCheckBox = $_POST['itemCheckBox'];
$itemName = $_POST['itemName'];
$itemHref = $_POST['itemHref'];
$itemImg = $_POST['itemImg'];
$itemPrice = $_POST['itemPrice'];
echo $i;
echo "<br>";
$i = $i +1;
if (isset($_POST['itemCheckBox'])){
echo "<br>";
echo "CHECKED";
echo "<br>";
echo "<br>";
echo $itemCheckBox[$i];
echo "<br>";
echo $itemName[$i];
echo "<br>";
echo $itemHref[$i];
echo "<br>";
echo $itemImg[$i];
echo "<br>";
echo $itemPrice[$i];
} else {
echo "NOT CHECKED";
echo "<br>";
$i = $i +1;
}
}
A couple things I spots that may be contributing to the issue:
In your PHP you have a line that has this:
//Remove non numaric characters from price(leave commas).
$itemPrice = preg_replace('/[^0-9,.]/s', '', $itemPrice);
I don't see where $itemPrice is defined though, should it be:
$itemPrice = preg_replace('/[^0-9,.]/s', '', $fields['itemPrice']);
Your issue of getting the "Warning: Invalid argument supplied for foreach() in /home..." can be solved by checking to make sure it exists and is an array beforelooping. You can use !empty() and is_array() to check.
if(!empty($_POST['itemCheckBox']) and is_array($_POST['itemCheckBox'])){}
Side Issue:
Your IDs for the inputs are all the same, "itemCheckBox[]", "itemName[]", etc.. are the same ID used for all of them. This may cause problems in the future if you want to use javascript or css properly.
Edit:
In your revised example the issue is that each time it cycles into the loop it is setting $i=0 because you declare it at the top of the foreach. If you go back to using the $key as the index it should work. See below:
//GROUP 1 checkbox
<input id="itemCheckBox[]" type="checkbox" value="0" name="itemCheckBox[]"></input>
//GROUP 2 checkbox
<input id="itemCheckBox[]" type="checkbox" value="1" name="itemCheckBox[]"></input>
I may also advise that you adjust your HTML items to match the Key you are passing:
<input id="itemName[1]" type="hidden" value="Bomber Jacket With Fur" name="itemName[]"></input>
<input id="itemHref[1]" type="hidden" value="http://random.com/Bomber-Jacket-With-fur/.." name="itemHref[]"></input>
<input id="itemImg[1]" type="hidden" value="http://images.com/i/image_xl.jpg" name="itemImg[]"></input>
<input id="itemPrice[1]" type="hidden" value="$88.88" name="itemPrice[]"></input>
foreach($_POST['itemCheckBox'] as $key => $val) {
$itemCheckBox = $_POST['itemCheckBox'];
$itemName = $_POST['itemName'];
$itemHref = $_POST['itemHref'];
$itemImg = $_POST['itemImg'];
$itemPrice = $_POST['itemPrice'];
if (isset($_POST['itemCheckBox'])){
echo "<br>";
echo "CHECKED";
echo $itemCheckBox[$key];
echo "<br>";
echo "<br>";
echo $itemCheckBox[$itemCheckBox[$key]];
echo "<br>";
echo $itemName[$itemCheckBox[$key]];
echo "<br>";
echo $itemHref[$itemCheckBox[$key]];
echo "<br>";
echo $itemImg[$itemCheckBox[$key]];
echo "<br>";
echo $itemPrice[$itemCheckBox[$key]];
} else {
echo "NOT CHECKED";
echo "<br>";
}
}

php checkbox from mysql

I've managed to pull records from a mysql database using php with a checkbox to select. I'm struggling to make the selected records (with the checkboxes) appear on a new page. Here is my code so far:
<?php
include('connect.php');
$query = 'SELECT * FROM grades';
if ($r = mysql_query($query)) {
print "<form>
<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['InstitutionName']}</td>
<td>{$row['InstitutionAddress']}</td>
<td>{$row['SubjectArea']}</td>
<td><input type='checkbox' name='check[$row{['GradeID']}] value='check' /></td>
</tr>";
}
print "</table>
</form>";
$checkbox[] = isset($_POST['checkbox']) ? true : false;
} else {
print '<p style="color: blue">Error!</p>';
}
?>
<html>
<form action="check2.php" method="POST">
<input type='submit' name='Submit' value='Submit'>
</html>
And on the page where I want the selected records to display, I have:
<?php
if(isset($checkbox))
{
foreach($checkbox as $value)
{
echo $value."<br>"; //it will print the value of your checkbox that you checked
}
}
?>
Any assistance would be appreciated!
Put checked="checked" just like you have put value="check":
<td><input type='checkbox' name='check[$row{['GradeID']}] value='check' checked="checked" /></td>
Edit:
Probably I misunderstood you. What do you expect to see?
First, you should make the form to perform POST request instead of GET (default):
print "<form method='POST' action='THE_FILE_YOU_PRINT_RESULTS.php'>"
Then in "THE_FILE_YOU_PRINT_RESULTS.php" do a print_r($_POST); to see what you get and how to display it.
A better way to do this would be to name your checkboxes check[]. Each checkbox value should then be the ID (rather than check).
Then on your results page, just loop through each instance of check[] and print the value out.
check[$row{['GradeID']}]
Seems incorrect to me, should it be:
check[{$row['GradeID']}]
Notice the moved opening curly bracket to before the $
Sorry if this is wrong haven't used PHP in long time but it stood out for me
The are a couple of error in the form print function.
You have to put the action on the first form, not on the second, you have to change the way how you print the checkbox as well.
Try to print the form in this way:
<?php
include('connect.php');
$query = 'SELECT * FROM grades';
if ($r = mysql_query($query)) {
print "
<form action=\"check2.php\" method=\"POST\">
<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['InstitutionName']}</td>
<td>{$row['InstitutionAddress']}</td>
<td>{$row['SubjectArea']}</td>
<td><input type='checkbox' name='check[".$row['GradeID']."] value='".$row['GradeID']."' /></td>
</tr>";
}
print "</table>
<input type='submit' name='Submit' value='Submit'>
</form>";
$checkbox[] = isset($_POST['checkbox']) ? true : false;
} else {
print '<p style="color: blue">Error!</p>';
}
?>
And print the checked box reading the _REQUEST array:
<?php
if(isset($_REQUEST["check"]))
{
foreach($_REQUEST["check"] as $key=>$value)
{
echo $key."<br>"; //it will print the value of your checkbox that you checked
}
}
?>
This should work.

how to loop and compare two arrays at the same time(PHP)

I have two array. What I want to do is compare the key ['user_id'] of two arrays, if they are the same, pass the ['user_id'] and ['ref'] in hidden form. I tried to put them into two foreach, but system seems into a dead lock.
<?php foreach($_SESSION['printing_set'] as $data) { ?>
<?php foreach(getProvenaMailableUserlist() as $userlist){ ?>
<input type="hidden" name="reference[<?php echo $data['user_id'] ?>]" value="<? if($userlist['user_id'] == $data['user_id']){echo $userlist['ref'];} ?>" />
<?php } ?>
<?php } ?>
What is the right way to do that?
What you are doing is printing again and again the part of '<input type="hidden" name="...'. here is what you should do
<?php
echo '<input type="hidden" name="reference[' . $data['user_id'] . ']" value="'; //olny one time.
foreach($_SESSION['printing_set'] as $data) {
foreach(getProvenaMailableUserlist() as $userlist){
if($userlist['user_id'] == $data['user_id']){
echo $userlist['ref']; //only if condition is true
}
}
}
echo '" />'; //only one time
?>
You've got some funky formatting going on, so it's hard to tell where the error might be. Try it like this:
<?php
foreach($_SESSION['printing_set'] as $data) {
foreach(getProvenaMailableUserlist() as $userlist){
$value = "";
if($userlist['user_id'] == $data['user_id'])
$value = $userlist['ref'];
echo "<input type='hidden' name='reference$user_id' value='$value' /> \n";
}
}
?>

Categories