Adding multiple $_Posts from form into MYSQL DB - Using a loop? - php

Experts Exchange > Programming > Prog Languages > Scripting Languages > PHP > Adding Multiple Posts From Form Into M Y S Q L D B Using A Loop
Your question has been submitted.
Adding multiple $_Posts from form into MYSQL DB - Using a loop?!
Asked by: runnerjp2005
Hi,
The following code adds extra rows of text boxes to add further data.
But im having issue with looping through them and adding them into my database.
Is my mothod correct as im getting the error "Invalid argument supplied for foreach() "
below is my code
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.js"></script>
<?php
include "../include/db.php";
if (!empty($_POST['ok'])) {
if (!empty($_POST['Loop'])) {
$i = 0;
echo "hi";
foreach ($_POST['Loop'] as $r) {
//add to database
$dateFormated = split('/', $_POST['theDate' . $i]);
$Date = $dateFormated[2] . '-' . $dateFormated[1] . '-' . $dateFormated[0];
// check if name only contains letters and whitespace
$Sport = test_input($_POST["Sport" . $i]);
// check if name only contains letters and whitespace
$Pick = test_input($_POST["Pick" . $i]);
$Bookie = test_input($_POST["Bookie" . $i]);
// check if name only contains letters and whitespace
if (strpos($_POST["Odds" . $i], '/') !== false) {
$Odds = round(fraction(test_input($_POST["Odds" . $i])), 2);
} else {
$Odds = test_input($_POST["Odds" . $i]);
}
// check if name only contains letters and whitespace
$BackorLay = test_input($_POST["BackorLay" . $i]);
// check if name only contains letters and whitespace
$Stake = floatval(test_input($_POST["Stake" . $i]));
// check if name only contains letters and whitespace
$Com = test_input($_POST["Com" . $i]);
// check if name only contains letters and whitespace
$Outcome = test_input($_POST["Outcome" . $i]);
// check if name only contains letters and whitespace
$Reduction = test_input($_POST["Reduction" . $i]);
// check if name only contains letters and whitespace
$PlaceDiv = test_input($_POST["PlaceDiv" . $i]);
// check if name only contains letters and whitespace
if ($_POST['test' . $i] == 'EW') {
$ew = "yes";
} else {
$ew = "no";
}
$i = $i + 1;
$sql = "
INSERT INTO `Bets`
( `Date`, `Sport`, `Pick`, `Bookie`, `Odds`, `BackorLay`, `Stake`, `ew`, `Com`, `Result`, `Reduction`, `PlaceDiv`)
VALUES
('$Date', '$Sport', '$Pick', '$Bookie', '$Odds', '$BackorLay', '$Stake', '$ew', '$Com', '$Outcome', '$Reduction', '$PlaceDiv')";
$res = mysqli_query($db, $sql);
if (!$res) {
echo PHP_EOL . "FAIL: $sql";
trigger_error(mysqli_error($db), E_USER_ERROR);
}
}
}
}
?>
<div style="width:90%;margin:auto;">
<h1>Add Bets</h1>
<form method="post">
<center>
<p>
<input type="hidden" name="Loop" value="loop">
<input id="theDate0" size="10" value="<?
echo date(" d/m/Y ");
?>" name="theDate0" type="text">
<select id="Sport0" name="Sport0">
<option>Horse Racing</option>
<option>Football</option>
<option>Greyhounds</option>
<option>NFL</option>
</select>
<input id="Pick0" name="Pick0" type="text">
<select id="Bookie0" name="Bookie0">
<option>Bet365</option>
<option>Betfred</option>
<option>BetVictor</option>
<option>Boylesports</option>
<option>Bwin</option>
<option>Centrebet</option>
<option>Coral</option>
<option>Ladbrokes</option>
<option>Paddy Power</option>
<option>Pinnacle Sports</option>
<option>SBOBET</option>
<option>Sky Bet</option>
<option>Stan James</option>
<option>unibet</option>
<option>William Hill</option>
</select>
<input id="Odds0" name="Odds0" size="3" type="text">
<select id="BackorLay0" name="BackorLay0">
<option>Back</option>
<option>Lay</option>
</select>
<input id="Stake0" name="Stake0" size="3" type="text">E/W<input name="EW0" ID="EW0" value="EW" type="checkbox" />
<select id="Com0" name="Com0">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<select id="Outcome0" name="Outcome0">
<option>Unknown</option>
<option>Win</option>
<option>Loss</option>
<option>P</option>
<option>E/W Win</option>
<option>Void</option>
</select>
<select id="PlaceDiv0" name="PlaceDiv0">
<option>5</option>
<option>4</option>
</select>
<input onclick="addRow(this.form);" type="button" value="Add row" /> </p>
<div id="itemRows">
</div> <p><input type="submit" name="ok" value="Save Changes"></p>
</center>
</form>
</div>
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'"><input id="theDate'+rowNum+'" size="10" value="<?
echo date(" d/m/Y ");
?>" name="theDate'+rowNum+'" type="text"><select id="Sport'+rowNum+'" name="Sport'+rowNum+'"><option>Horse Racing</option><option>Football</option><option>Greyhounds</option><option>NFL</option></select><input id="Pick'+rowNum+'" name="Pick'+rowNum+'" type="text"></td><td><select id="Bookie'+rowNum+'" name="Bookie'+rowNum+'"><option>Bet365</option><option>Betfred</option><option>BetVictor</option><option>Boylesports</option><option>Bwin</option><option>Centrebet</option><option>Coral</option><option>Ladbrokes</option><option>Paddy Power</option><option>Pinnacle Sports</option><option>SBOBET</option><option>Sky Bet</option><option>Stan James</option><option>unibet</option><option>William Hill</option></select><input id="Odds'+rowNum+'" name="Odds'+rowNum+'" size="3" type="text"><select id="BackorLay'+rowNum+'" name="BackorLay'+rowNum+'"><option>Back</option><option>Lay</option></select><input id="Stake'+rowNum+'" name="Stake'+rowNum+'" size="3" type="text">E/W<input name="EW'+rowNum+'" ID="EW'+rowNum+'" value="EW" type="checkbox" /><select id="Com'+rowNum+'" name="Com'+rowNum+'"><option>0</option><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option></select><select id="Outcome'+rowNum+'" name="Outcome'+rowNum+'"><option>Unknown</option><option>Win</option><option>Loss</option><option>P</option><option>E/W Win</option><option>Void</option></select><select id="PlaceDiv'+rowNum+'" name="PlaceDiv'+rowNum+'"><option>5</option><option>4</option></select><input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>
</body>
</html>
---Update code---
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.js"></script>
<?php
include "../include/db.php";
function fraction($frac)
{
$fraction = explode("/", $frac);
if ($fraction[1] != 0)
{
return $fraction[0] / $fraction[1];
}
return "Division by zero error!";
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (!empty($_POST['ok']))
{
if (!empty($_POST['Loop']))
{
$i = 0;
echo "hi";
foreach($_POST['theDate'] AS $i => $theDate)
{
// add to database
$dateFormated = split('/', $_POST['theDate']);
$Date = $dateFormated[2] . '-' . $dateFormated[1] . '-' . $dateFormated[0];
// check if name only contains letters and whitespace
$Sport = test_input($_POST["Sport"]);
// check if name only contains letters and whitespace
$Pick = test_input($_POST["Pick"]);
$Bookie = test_input($_POST["Bookie"]);
// check if name only contains letters and whitespace
if (strpos($_POST["Odds"], '/') !== false)
{
$Odds = round(fraction(test_input($_POST["Odds"])) , 2);
}
else
{
$Odds = test_input($_POST["Odds"]);
}
// check if name only contains letters and whitespace
$BackorLay = test_input($_POST["BackorLay"]);
// check if name only contains letters and whitespace
$Stake = floatval(test_input($_POST["Stake"]));
// check if name only contains letters and whitespace
$Com = test_input($_POST["Com"]);
// check if name only contains letters and whitespace
$Outcome = test_input($_POST["Outcome"]);
// check if name only contains letters and whitespace
$Reduction = test_input($_POST["Reduction"]);
// check if name only contains letters and whitespace
$PlaceDiv = test_input($_POST["PlaceDiv"]);
// check if name only contains letters and whitespace
if ($_POST['test'] == 'EW')
{
$ew = "yes";
}
else
{
$ew = "no";
}
$i = $i + 1;
$sql = "
INSERT INTO `Bets`
( `Date`, `Sport`, `Pick`, `Bookie`, `Odds`, `BackorLay`, `Stake`, `ew`, `Com`, `Result`, `Reduction`, `PlaceDiv`)
VALUES
('$Date', '$Sport', '$Pick', '$Bookie', '$Odds', '$BackorLay', '$Stake', '$ew', '$Com', '$Outcome', '$Reduction', '$PlaceDiv')";
$res = mysqli_query($db, $sql);
if (!$res)
{
echo PHP_EOL . "FAIL: $sql";
trigger_error(mysqli_error($db) , E_USER_ERROR);
}
}
}
}
?>
<div style="width:90%;margin:auto;">
<h1>Add Bets</h1>
<form method="post">
<center>
<p>
<input type="hidden" name="Loop" value="loop">
<input id="theDate[]" size="10" value="<?php
echo date(" d/m/Y "); ?>" name="theDate[]" type="text">
<select id="Sport[]" name="Sport[]">
<option>Horse Racing</option>
<option>Football</option>
<option>Greyhounds</option>
<option>NFL</option>
</select>
<input id="Pick[]" name="Pick[]" type="text">
<select id="Bookie[]" name="Bookie[]">
<option>Bet365</option>
<option>Betfred</option>
<option>BetVictor</option>
<option>Boylesports</option>
<option>Bwin</option>
<option>Centrebet</option>
<option>Coral</option>
<option>Ladbrokes</option>
<option>Paddy Power</option>
<option>Pinnacle Sports</option>
<option>SBOBET</option>
<option>Sky Bet</option>
<option>Stan James</option>
<option>unibet</option>
<option>William Hill</option>
</select>
<input id="Odds[]" name="Odds[]" size="3" type="text">
<select id="BackorLay[]" name="BackorLay[]">
<option>Back</option>
<option>Lay</option>
</select>
<input id="Stake[]" name="Stake[]" size="3" type="text">E/W<input name="EW[]" ID="EW[]" value="EW" type="checkbox" />
<select id="Com[]" name="Com[]">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<select id="Outcome[]" name="Outcome[]">
<option>Unknown</option>
<option>Win</option>
<option>Loss</option>
<option>P</option>
<option>E/W Win</option>
<option>Void</option>
</select>
<select id="PlaceDiv[]" name="PlaceDiv[]">
<option>5</option>
<option>4</option>
</select>
<input onclick="addRow(this.form);" type="button" value="Add row" /> </p>
<div id="itemRows">
</div> <p><input type="submit" name="ok" value="Save Changes"></p>
</center>
</form>
</div>
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'"><input id="theDate[]" size="10" value="<?php
echo date(" d/m/Y "); ?>" name="theDate[]" type="text"><select id="Sport[]" name="Sport[]"><option>Horse Racing</option><option>Football</option><option>Greyhounds</option><option>NFL</option></select><input id="Pick[]" name="Pick[]" type="text"></td><td><select id="Bookie[]" name="Bookie[]"><option>Bet365</option><option>Betfred</option><option>BetVictor</option><option>Boylesports</option><option>Bwin</option><option>Centrebet</option><option>Coral</option><option>Ladbrokes</option><option>Paddy Power</option><option>Pinnacle Sports</option><option>SBOBET</option><option>Sky Bet</option><option>Stan James</option><option>unibet</option><option>William Hill</option></select><input id="Odds[]" name="Odds[]" size="3" type="text"><select id="BackorLay[]" name="BackorLay[]"><option>Back</option><option>Lay</option></select><input id="Stake[]" name="Stake[]" size="3" type="text">E/W<input name="EW[]" ID="EW[]" value="EW" type="checkbox" /><select id="Com[]" name="Com[]"><option>0</option><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option></select><select id="Outcome[]" name="Outcome[]"><option>Unknown</option><option>Win</option><option>Loss</option><option>P</option><option>E/W Win</option><option>Void</option></select><select id="PlaceDiv[]" name="PlaceDiv[]"><option>5</option><option>4</option></select><input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>

There are a lot of methodology improvements you could make to this, but I'll try to keep this answer as direct as possible.
As #devJunk said in the comment, your $_POST['Loop'] contains, literally, 'loop'. It is not an array, so you can't loop it with a foreach.
I see that what you're trying to do is iterate through all the rows you've submitted. There are a couple different ways to achieve this.
Minimal Changes Option
You are currently appending a number to the end of your variables (i.e. "Bookie0", "Bookie1", etc.). This will work, but you need to give the backend of the script a way to know how many rows you are submitting. So make this change to your Loop hidden:
<input type="hidden" name="Loop" id="Loop" value="1">
Then, in your addRow() and removeRow() functions, add this:
jQuery('#Loop').val((rowNum + 1));
Make sure you add it AFTER "rowNum ++" in your addRow function. You also need to add "rowNum --" to your removeRow() function, and add the above after that.
This will set Loop to be the value of the number of rows you have.
Then, when processing the post, get rid of "foreach ($_POST['Loop'] as $r)" and replace it with this:
for ($i = 0; $i < $_POST['Loop']; $i++) {
(Note that you will no longer need "$i = 0" nor "$i = $i + 1" in your post handling)
This will iterate however many rows you have submitted and do your processing.
Improved Methodology Option
If you want to change your methodology, you can use HTML Input Arrays to accomplish this instead. Basically, instead of using "Bookie0", "Bookie1", etc., you can just make every variable name end with "[]", like "Bookie[]", "Sport[]", etc. The addition of the square braces means that $_POST['Bookie'] will automatically be an array.
So in your addRow and removeRow functions, you would no longer have to worry about incrementing or decrementing the row number because that would no longer be relevant. you wouldn't need the Loop hidden at all. Then, when processing the post, you would do something like this:
foreach ($_POST['theDate'] AS $i => $theDate) {
And the rest of your processing should work fine.

In order to loop through an array, you have to send data as such, so you have to name your input fields 'name[]'. That way, data added to those fields is added to $_POST as elements of the 'name' array.
Example:
<form action="" method="post">
<input type="hidden" name="works[]" value="1">
<input type="hidden" name="works[]" value="2">
<input type="submit" name="submit" />
</form>
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['works'])) {
var_dump($_POST['works']);
}
}
?>
This renders an array with all the values of 'works[]' fields:
array(2) { [0]=> string(1) "1" [1]=> string(1) "2" }

Related

PHP, HTML multiple chexbox valuesc

I have got the php, html code.
And I want to post the multiple checkbox values, but this does not work dunno why, I can print count or array, it prints(0), does not matter
the array values is always empty
<form action = 'main.php?w=creatNewTemplate2' method = 'post'>
<input type = 'text' name = 'templateName' maxlength = '30'/><br />
<input type= 'checkbox' name= 'exercises[]' value='A' />A<br />
<input type= 'checkbox' name= 'exercises[]' value='B' />B<br />
<input type = 'submit' value = 'Sukurti'/>
</form>
if($w == "creatNewTemplate2")
{
$d = $_POST['exercises'];
$ddd = count($d);
print_r($_POST);
}
I think this could work for you:
if($w == "creatNewTemplate2")
{
$d = $_POST['exercises'];
$ddd = count($d);
for ($x = 0; $x < $ddd; $x++) {
echo $_POST['exercises'][$x].'<br>';
}
}
If you use same name you need to loop them
This should be work
Or you can change the two checkbox to select multiple
<form action="main.php?w=creatNewTemplate2" method="post">
<input type="text" name="templateName" maxlength="30"/><br/>
<select multiple name="exercices[]">
<option>A</option>
<option>B</option>
</select>
<input type="submit" value="Sukurti"/>
</form>
<?php
if($_GET["w"] == "creatNewTemplate2")
{
foreach ($_POST["exercises"] as $ex) {
echo $ex . '<br>';
}
}

How can I show the output vertically after submitting the html form?

The who;e sequence(having operands , opertors and answer) in output is generating randomly which is perfect. but I want to show that in vertical manner
and this is the output I want to show after clicking on generate
then Q(2)will show up in the same way but after Q(1).
this is my html form.
<form action="" method="POST">
<div class="row">
<div class="col-25">
<label for="qnum">Select no.of questions:</label>
</div>
<div class = "col-75"><input type="number" id="qnum" name="que" value="1" min="1" max="100"></div>
<br /><br />
</div>
<br />
<div class="row">
<div class="col-25">
<label for="int">How many numbers You want in a sequence:</label></div>
<div class="col-75">
<select name="select" id="int">
<option value="2"> 2 </option>
<option value="3"> 3 </option>
<option value="4"> 4 </option>
<option value="5"> 5 </option>
<option value="6"> 6 </option>
<option value="7"> 7 </option>
<option value="8"> 8 </option>
<option value="9"> 9 </option>
<option value="10"> 10 </option>
</select>
</div>
</div>
<br />
<div class="row">
<div class="col-25">
<label for="dig">Select no. of digits:</label></div>
<div class="col-75">
<select name="digits" id="dig">
<option value="1"> 1 digit</option>
</select>
</div>
<br /><br /><br /><br />
</div>
<div class="row">
<div class="col-25"><label>Select operations:</label><br /></div>
<div class="col-75">
<input type="checkbox" id="mix" value="all" class="toggle-button"><label>All</label>
<input type="checkbox" id="add" name="operation[]" value="Addition" checked><label>Addition</label>
<input type="checkbox" id="sub" name="operation[]" value="Subtraction"><label>Subtraction</label>
<input type="checkbox" id="mult" name="operation[]" value="Multiplication"><label>Multiplication</label>
<input type="checkbox" id="div" name="operation[]" value="Division"><label>Division</label>
</div>
<br /><br />
<br /><br />
</div><br />
<input type="submit" name="submit" value="Generate"><br>
<br />
</form>
</div>
<!---Toggle button to select all operations if user select checkbox named "All" -->
<script language="JavaScript">
$( '.col-75 .toggle-button' ).click( function () {
$( '.col-75 input[type="checkbox"]' ).prop('checked', this.checked)
})
</script>
Basically I generating a random sequence of arithmetic expressions which is working perfectly without any error.
But after clicking generate button the output is showing horizontally and I want to generate it vertically.
So how can I do that?
Below is my php code which is generating the sequence perfectly without any error. How can I generate the output vertically?
<?php
error_reporting(E_ALL & ~E_NOTICE);
if(isset($_POST['submit']))
{
//validation for no of operation selected
$operation = $_POST['operation'];
if(empty($operation))
{
echo "Please Select at least one operation <br/>";
}
else
{
$N = count($operation); //count selected operation
echo "<br />";
echo "You have selected $N operation(s):";
for($i=0; $i < $N; $i++) //for loop for for operator array.
{
echo($operation[$i] . ", "); //display selected operation
}
echo "<br />";
//checkbox operations
if($N==1) //if only one operation is selected
{
if($operation[0]=='Addition')
{
$rOperators = array('+');
}
else if($operation[0]=='Subtraction')
{
$rOperators = array('-');
}
else if($operation[0]=='Multiplication')
{
$rOperators = array('*');
}
else
{
$rOperators = array('/');
}
}
else if ($N==2) //if only two operations are selected by the user
{
if($operation[0]=='Addition')
{
if($operation[1]=='Subtraction')
{
$rOperators = array('+','-');
}
else if($operation[1]=='Multiplication')
{
$rOperators = array('+','*');
}
else
{
$rOperators = array('+','/');
}
}
else if($operation[0]=='Subtraction')
{
if($operation[1]=='Multiplication')
{
$rOperators = array('-','*');
}
else
{
$rOperators = array('-','/');
}
}
else
{
$rOperators = array('*','/');
}
}
else if ($N==3) //if 3 operators gets selected by user
{
if($operation[0]=='Addition')
{
if($operation[1]=='Subtraction')
{
if($operation[2]=='Multiplication')
{
$rOperators = array('+','-','*');
}
else
{
$rOperators = array('+','-','/');
}
}
else
{
$rOperators = array('+','*','/');
}
}
else
{
$rOperators = array('-','*','/');
}
}
else
{
$rOperators = array('+','-','*','/');
}
}
//display sequence having only single digit numbers
if($_POST['digits'] == 1)
{
$q = $_POST['que'];
$previousInt = null; //Track the previous operand
$s = $_POST['select'];
for ($x = 1; $x<=$q; $x++) //for loop for no. of questions
{
$randomOperands = array();
$randomOperators = array();
// loop over $i n times
for ($i = 1; $i <=$s; $i++) //for loop for no. of integers user entered
{
$nextInt = rand(1, 9); // assign random operand to array slot
$randomOperands[] = $nextInt;
if($i < $s)
{
if($previousInt === 0) //No operator after last opearnd
{
//avoid division-by-zero
$randomOperators[] = $rOperators[rand(0, 2)];
}
else
{
$randomOperators[] = $rOperators[rand(0, $N-1)];
}
}
$previousInt = $nextInt;
}
// print array values
$exp = ''; //Generating the expression
foreach($randomOperands as $key=>$value1)
{
$exp .= $value1 . " " ;
if(isset($randomOperators[$key]))
{
$exp .= $randomOperators[$key] ." ";
}
}
$res = eval("return ($exp);");//evaluate the expression
//print expression
echo ("This is Q(".$x."):"), $exp."=". $res."<br>";
}
}
}
?>
Modify the code in which you are generating the expression which you are using as the input to the eval() function. Create another string say $output_string which can be used to output your answer. In this newly created string use proper HTML tags along with the generated string, for formatting it the way you want your output to look like.
It should look something like this:
$exp = ''; //Generating the expression
$output_string = ''; // new string which can be used for generating the output string
foreach ( $randomOperands as $key => $value1 ) {
$exp .= $value1 . " " ;
$output_string .= $value1 . " <br>" ;
if ( isset($randomOperators[$key]) ) {
$exp .= $randomOperators[$key] ." ";
$output_string .= $randomOperators[$key] ." <br> ";
}
}
$res = eval("return ($exp);");//evaluate the expression
//print expression
echo ("This is Q(".$x."): <br>"), $output_string."= <br>". $res."<br>";

Warning: Illegal string offset error

I'm trying to create a simple search engine in php, in which if the user enters a keyword they can search by event name or location. Then the results to be displayed in date order. Most of the has been taken from another site, but I am trying to convert it.
Can someone explain the error below to a newbie, in simple terms and how to correct it?
/home/ubuntu/workspace/test/test.php:49: array(5) { 'eventID' => string(1) "1" 'eventName' => string(8) "Exciting" 'eventLocation' => string(7) "Stadium" 'commencing' => string(10) "2017-04-01" 'expires' => string(10) "2017-04-30" } Warning: Illegal string offset 'eventName' in /home/ubuntu/workspace/test/test.php on line 50 Call Stack: 0.0003 238624 1. {main}() /home/ubuntu/workspace/test/test.php:0 1
<?php
session_start();
//include files
include 'header/header.php';
include 'nav/navigation.php';
include 'init.php';
$expires = strtotime($_POST["expires"]);
$expires = date('Y-m-d', $expires);
$events = "";
$find = $_POST['find'];
$field = $_POST['field'];
$searching = true;
if(isset($_POST["submit"])) {
if(!empty($_POST["events"])) {
$searching = false;
}
//This is only displayed if the user submitted the form
if($searching == true)
{
echo "<h2>Results</h2><p>";
//If the user did not enter a search term, they receive an error
if ($find == "")
{
echo "<p>You forgot to enter a search term";
exit;
}
// Otherwise we connect to the database
//$result = mysqli_query($connection,$query) or exit ("Error in query:
$query. ".mysqli_error($connection));
// We preform a bit of filtering
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
//Now we search for our search term, in the field the user specified
$mysqli = new mysqli('localhost', 'root', '', 'c3470438');
$query = "SELECT * FROM events WHERE upper(eventLocation)
LIKE'%STADIUM%'";
$result = $mysqli->query($query);
//Temporarily echo $query for debugging purposes
//echo "$query";
//exit;
//And display the results
$row = $result->fetch_array(MYSQLI_ASSOC);
echo "<br>";
foreach($row as $item) {
var_dump($row);
echo $item['eventName'];
exit();
}
exit;
//This counts the number or results. If there aren't any, it gives an
explanation
$anymatches=mysql_num_rows($data);
if ($anymatches == 0) {
echo "Sorry, but we can not find an entry to match your query<br>
<br>";
}
//And reminds the user what they searched for
echo "<b>Searched For:</b> " .$find;
}
}
?>
<fieldset>
<legend><h2>Events</h2></legend>
<form name="search" method="post" action="<?=$PHP_SELF?>">
<tr> <th> <td>
<fieldset>
<legend>Find all events</legend>
<input type="radio" name="events" <?php if (isset($events) &&
$events=="all") echo "checked";?>value="all"> Display all events
</fieldset>
<fieldset>
<legend>Find events by date</legend>
<input type="date" name="date" min="<?php echo date("Y-m-d");?>"
max="2025-01-01" value="<?php echo date("Y-m-d");?>">
</fieldset>
<fieldset>
<legend>Find events by keywords</legend>
<input type="hidden" placeholder='Search by keyword'name="searching"
value="yes" />
Search for: <input type="text" name="find" /> in
<Select NAME="field">
<Option VALUE="eventName">Event Name</option>
<Option VALUE="eventLocation">Event Location</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="submit" value="submit" />
</form>
</fieldset>
<button name="submit" value="submit" type="submit" class="button
expanded">Submit </button>
<button type="reset" value="Clear"class="button expanded">
Clear</button>
</fieldset>
</select> </td></tr>
<?php
//include files
include 'footer/footer.php';
?>
<script src="js/vendor/jquery.js"></script>
<script src="js/foundation.min.js"></script>
<script>
</script>
</body>
Well $result->fetch_array(MYSQLI_ASSOC) returns a single row, but you are using it as if it returns all rows. So your foreach is iterating each field in the row, not each row and therefore you're trying to access an array key of a string.
Use a while like so:
while($row = $result->fetch_array(MYSQLI_ASSOC)){
echo $row['eventName'];
}
Also, you're using mysql_num_rows which is not part of mysqli. Instead use $result->num_rows.

Form showing no option is selected error message when options are selected

I have the following form:
<form action="#" method="POST" enctype="multipart/form-data">
from:
<select name="age_from" id="age_a" onchange="checkages_a()">
<option value=""></option>
<?php
for($i = 17; $i <= 50; ++$i) {
echo "\t", '<option value="', $i. '">', $i, '</option>', "\n";
}
?>
</select>
to:
<select name="age_to" id="age_b" onchange="checkages_b()">
<option value=""></option>
<?php
for($i = 18; $i <= 50; ++$i) {
echo "\t", '<option value="', $i, '">', $i, '</option>', "\n";
}
?>
</select>
<input type="radio" name="gender" value="male">Male</input> <br />
<input type="radio" name="gender" value="female">Female</input><br />
<input type="submit" class="btn btn-info"
name="submit_form" value="Click to start chat! " />
The way it works is that a user can select one of the two options from gender and age and search for a user. It is not required for both options to be completed to search.
However, if none of the options are selected, I want it to stay on the current page (`random_chat.php), and echo a message.
Here is my approach:
$refined_gender = isset($_POST['gender']) ? escape($_POST['gender']) : '';
$age_from = isset($_POST['age_from']) ? escape($_POST['age_from']) : '';
$age_to = isset($_POST['age_to']) ? escape($_POST['age_to']) : '';
if (isset($_POST['submit_form'])){
if (empty ($refined_gender) || empty($age_from) || empty ($age_to)) {
echo "<div class='no_user'><p> Please apply at least one of the filters above. </p> </div>";
} else {
// search user
}
Currently, when I have both search options empty, the message echos, which is good. But the message also echos when I am searching for a male user, or have age not empty, which shouldn't happen.
you need to change || to &&, (Some other changes are also stated as comment):-
<form method="POST" enctype="multipart/form-data"> <!-- remove action ='#' -->
from:
<select name="age_from" id="age_a" onchange="checkages_a()">
<option value=""></option>
<?php
for($i = 17; $i <= 50; ++$i) {
if(isset($_POST['age_from']) && $_POST['age_from'] == $i){ // to make selected value to be selected even after form submit
echo "\t", '<option value="', $i. '" selected ="selected">', $i, '</option>', "\n";
}else{
echo "\t", '<option value="', $i. '">', $i, '</option>', "\n";
}
}
?>
</select>
to:
<select name="age_to" id="age_b" onchange="checkages_b()">
<option value=""></option>
<?php
for($i = 18; $i <= 50; ++$i) {
if(isset($_POST['age_to']) && $_POST['age_to'] == $i){// to make selected value to be selected even after form submit
echo "\t", '<option value="', $i. '" selected ="selected">', $i, '</option>', "\n";
}else{
echo "\t", '<option value="', $i. '">', $i, '</option>', "\n";
}
}
?>
</select>
<input type="radio" name="gender" value="male">Male</input> <br />
<input type="radio" name="gender" value="female">Female</input><br />
<input type="submit" class="btn btn-info" name="submit_form" value="Click to start chat! " />
<form>
<?php
$refined_gender = isset($_POST['gender']) ? $_POST['gender'] : ''; // escape gives me undefined function error at my end so i removed it, but if it is working at your end thhen keep it up as it is.
$age_from = isset($_POST['age_from']) ? $_POST['age_from'] : '';
$age_to = isset($_POST['age_to']) ? $_POST['age_to'] : '';
if (empty ($refined_gender) && empty($age_from) && empty ($age_to)) { // check always with form posted value not submit button value and also cange || to &&
echo "<div class='no_user'><p> Please apply at least one of the filters above. </p> </div>";
} else {
// search user
}
?>
The if condition does not reflect what you want fix it like this
if (empty ($refined_gender) && empty($age_from) && empty ($age_to)) {
echo "<div class='no_user'><p> Please apply at least one of the filters above. </p> </div>";
} else { // search user }

How to output all checkbox value

hello please help me i have a problem outputting all the values of checkbox it outputs only one i need to show all the checked checkbox and output them please help me here is the code it only shows one whenever i checked them all i need this
<html>
<head>
<title>Cake Form</title>
<link rel="stylesheet" href="cakeform.css">
</head>
<body>
<?php
$nameErr = $addErr = $phoneErr = $scake = $flavorcake = $fill = "";
$name = $address = $phone = $rcake = $fillr = $cakeflavor = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["address"])) {
$addErr = "Email is required";
} else {
$address = test_input($_POST["address"]);
}
if (empty($_POST["phone"])) {
$phoneErr = "Gender is required";
} else {
$phone = test_input($_POST["phone"]);
}
if(isset($_POST['SelectedCake'])){
$x=$_POST['SelectedCake'];
}
if(isset($_POST['CakeFlavor'])){
$y=$_POST['CakeFlavor'];
}
if(isset($_POST['Filling'])){
$z=$_POST['Filling'];
}
if(empty($x)){
$scake='Select one Cake';
}else{
$rcake= $x;
}
if(empty($y) OR $y == 'Flavor'){
$flavorcake='Select one flavor';
}else{
$cakeflavor= $y;
}
if(empty($z)){
$fill='Select at least one Fillings';
}else{
foreach($z as $item){
$fillr=$item;
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="wrap">
<div class="cont_order">
<fieldset>
<legend>Make your own Cake</legend>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<h4>Select size for the Cake:</h4>
<input type="radio" name="SelectedCake" value="Round6">Round cake 6" - serves 8 people</br>
<input type="radio" name="SelectedCake" value="Round8">Round cake 8" - serves 12 people</br>
<input type="radio" name="SelectedCake" value="Round10">Round cake 10" - serves 16 people</br>
<input type="radio" name="SelectedCake" value="Round12">Round cake 12" - serves 30 people</br>
<span class="error">*<?php echo $scake;?></span>
<h4>Select a Cake Flavor: </h4>
<select name="CakeFlavor">
<option value="Flavor" selected="selected">Select Flavor</option>
<option value="Carrot" >Carrot</option>
<option value="Chocolate" >Chocolate</option>
<option value="Banana" >Banana</option>
<option value="Red Velvet" >Red Velvet</option>
<option value="Strawberry" >Strawberry</option>
<option value="Vanilla" >Vanilla</option>
<option value="Combo" >Combo</option>
</select>
<span class="error">*<?php echo $flavorcake;?></span>
<h4>Select Fillings:</h4>
<label><input type="checkbox" name="Filling[]" value="Cream"/>Cream</label><br>
<label><input type="checkbox" name="Filling[]" value="Fudge"/>Fudge</label><br>
<label><input type="checkbox" name="Filling[]" value="Ganache"/>Ganache</label><br>
<label><input type="checkbox" name="Filling[]" value="Hazelnut"/>Hazelnut</label><br>
<label><input type="checkbox" name="Filling[]" value="Mousse"/>Mousse</label><br>
<label><input type="checkbox" name="Filling[]" value="Pudding"/>Pudding</label><br>
<span class="error">*<?php echo $fill;?></span>
</fieldset>
</div>
<div class="cont_order">
<fieldset>
<legend>Contact Details</legend>
<label for="name">Name</label><br>
<input type="text" name="name" id="name"><span class="error">*<?php echo $nameErr;?></span>
<br>
<label for="address">Address</label><br>
<input type="text" name="address" id="address"><span class="error">*<?php echo $addErr;?></span>
<br>
<label for="phonenumber">Phone Number</label><br>
<input type="text" name="phone" id="phone"><span class="error">*<?php echo $phoneErr;?></span><br>
</fieldset>
<input type="submit" name="submitted" id="submit" value="Submit"/>
</div>
</form>
<div class="cont_order">
<?php
echo $name.'<br>';
echo $address.'<br>';
echo $phone.'<br>';
echo $rcake.'<br>';
echo $cakeflavor.'<br>';
echo $fillr.'<br>';
?>
</div>
</div>
</body>
</html>
You can do this:
var_dump($_POST['Filling']);
Or just this:
<?php
if(!empty($_POST['Filling'])) {
foreach($_POST['Filling'] as $check) {
echo $check;
}
}
?>
Tell me if it works =)
Fact is, you accept a list for filling.
In your code you do this :
foreach($z as $item){
$fillr=$item;
}
Replace it by :
$fillr = '';
foreach($z as $item){
$fillr .= '- ' . $item . '<br/>';
}
It should work better.
For comment :
#so let's say $z is an array :
$z = [1,2,3,4];
#then you say, for each element of the array as you will call $item, I do something
foreach($z as $item){
$fillr=$item; #here you say : for each element of $z (1,2,3,4), I put this value into $fillr.
}
#so let's do the loop together.
# First pass, $item == 1, so $fillr == 1.
# Second pass, $item == 2, so $fillr == 2.
# ...
# Last pass, $item == 4, so $fillr == 4.
# so then when you show $fillr it's the last item of the list (here 4).
# using PHP, .= means concatenate.
# for instance :
$a = "hello ";
$a .= "world";
echo $a;
> hello world
So basically, what I'm doing is :
Having an empty string I'll call $fillr.
For every element of the list,
Append "the_element plus a <br/>" to $fillr
so then when you output $fillr it looks sexy.
Do you get it bud?

Categories