How to compare form data in php - php

HTML/PHP:
<form method="post" name="contact" id="frmContact" action="sM.php">
<img id="main-img" src="theimage/img1.png" name="imageval" />
<div style="clear: both; padding: 10px 0 0 0; overflow: hidden;">
Please enter the number(s) from the image above: <input type="text" id="tNum" placeholder="Enter Number(s)" name="numval" />
</div>
<input type="submit" value="Send" id="submit" name="submit" class="submit_btn" />
</form>
PHP:
$arrImg = array("img1", "img2", "img3", "img4", "img5", "img6");
$arrImgText = array("56", "342", "34534", "12", "444", "652");
$imgval = trim(strip_tags(stripslashes($_POST['imageval']))); //get the image source that was displayed in the form
$numval = trim(strip_tags(stripslashes($_POST['numval']))); //get the number that the user entered
//if ({arrImg[imgval] == arrImgText[numval]}) {
//do something;
//}
The image that is displayed in the form has some numbers. When the user hit send, I would like to compare the number that was entered that was displayed in the image and compare.
How can I do that.

In your form, create hidden input:
<input type="hidden" name="imageval" value="img1" />
In your PHP file you can have now two $_POST variables:
$secretImg = $_POST['imageval'];
$token = $_POST['numval'];
Now you need to find key of image:
$imgKey = array_search($secretImg, $arrImg);
Using the key value, check the proper token:
if ($arrImgText[$imgKey] === $token) {
// Token is valid
}

You can't pass images because it is not an input element, what you could do is use a hidden input element instead:
<form method="post" name="contact" id="frmContact" action="sM.php">
<img id="main-img" src="theimage/img1.png" />
<input type="hidden" val="img1" name="imageval" /> <!-- THIS IS THE HIDDEN INPUT ELEMENT THAT WILL BE SUBMITTED -->
<div style="clear: both; padding: 10px 0 0 0; overflow: hidden;">
Please enter the number(s) from the image above: <input type="text" id="tNum" placeholder="Enter Number(s)" name="numval" />
</div>
<input type="submit" value="Send" id="submit" name="submit" class="submit_btn" />
</form>
In order to search the image value in the array using PHP, you can use in_array:
if( in_array( $_POST['imageval'], $arrImgText ) {
echo "Image found";
}
Edit: To get the specific index, use the example in #GrzegorzGajda'a answer

Related

If-else statement if theres no value input

Im trying to handle error in my code, how do i if-else when there is no value on the input of user and the user calculates it?
<h1> Triangle</h1>
<div style="border:1px solid black">
<form action="triangle.php" method="get">
Base: <input type="number" name="base"> meters
<br>
Height: <input type="number" name="height"> meters
<br>
<input type="submit" value="Calculate">
</form>
</div>
<?php
if (isset($_GET['base'])) {
$base1 = $_GET['base'];
$height1 = $_GET['height'];
$area = triangleArea($base1, $height1);
echo "Area is: " . $area;
}
?>
You're already checking whether the base value exists or not. It looks like you need to also check whether the height value exists - so just add that into the isset function call:
if (isset($_GET['base'], $_GET['height'])) {

How to collect values of input fields from a form displayed with a loop

I have a form in which input fields are displayed via a while loop with but I'm having issues with collecting the data from the input fields to save to the DB. What should be the possible php script to collect the form data?
if(isset($_GET['submit'])){
//collect form data
}
$sql="SELECT * FROM epl";
$result=mysqli_query($db_conx,$sql);
if($nr=mysqli_num_rows($result)>0){
These two variables are initialized as with 1 which is used in the while loop to increase the values will serve as the names of the input fields.
$Inum1=1;
$Inum2=1;
while($row=mysqli_fetch_array($result)){
$t1=$row['team1'];
$t2=$row['team2'];
echo '<form METHOD="get">
<div class="block">
<div class="epl_form_g">
<div class="eplT">
<label >'.$t1.'</label>
</div>
<input type="text" name="t_'.$Inum1.'_score" id="input">
</div>
<label class="vs">vs</label>
<div class="epl_form_g">
<input type="text" name="t_'.$Inum2.'_score" id="input">
<div class="eplT">
<label>'.$t2.'</label>
</div>
</div>
</div> ';
$Inum1++;
$Inum2++;
}
echo ' <center><input name="submit" type="submit" value="ENTER NOW!"
style="width:30%; background-color:#379BFF; text-align:center;border:none; border-radius:3px; height:41px; color:#FFF;
font-size:24px; box-shadow:none; margin-top:20PX;">
</form>';
}
As there is a form for every record and each form has it's own submit button they are effectively unique and separate entities on the page which means the field names can be repeated ( the ID however cannot )
The form is submitted and there will only be data for that row sent via the form submission - with predefined field names t_1_score and t_2_scoreso it is simple to get the values from the $_GET array and use them in an update/insert statement. If it is an update statement then I think you will need a hidden field per form with that contains the ID for the db record.
/* process form submission */
if( isset( $_GET['t_1_score'],$_GET['t_2_score'] ) ){
/*
As you submit only 1 form at a time the field names
can be the same in each form
*/
$score_team_1=$_GET['t_1_score'];
$score_team_2=$_GET['t_2_score'];
/* pseudo database code */
$sql='insert or update some table';
$res=$db->query( $sql );
}
/* display your form and the input fields for each row */
if( $result ){
while( $row=mysqli_fetch_array( $result ) ){
$t1=$row['team1'];
$t2=$row['team2'];
/*$id=$row['id'];*/
echo "
<form method='get'>
<div class='block'>
<div class='epl_form_g'>
<div class='eplT'><label>".$t1."</label></div>
<input type='text' name='t_1_score'>
</div>
<label class='vs'>vs</label>
<div class='epl_form_g'>
<input type='text' name='t_2_score'>
<div class='eplT'><label>".$t2."</label></div>
</div>
<!--<input type='hidden' name='id' value='{$id}' />-->
<input name='sub' type='submit' value='ENTER NOW!' style='width:30%; background-color:#379BFF; text-align:center; border:none; border-radius:3px; height:41px; color:#FFF; font-size:24px; box-shadow:none; margin-top:20px auto 0 auto; float:none;' />
</div>
</form>";
}
}

How to add up value via function - PHP

I am trying to create a function that add up number to a given variable each time a button was click.
I have 4 buttons: farm, cave, house, casino
So what I am trying to achieve here is I need to send the random numbers generated by the buttons to a variable that will add up all of the SCORE on the "YOUR GOLD" section. So let's say I click the farm and the cave button so there will be 20 for the cave and 15 for farm for a total of 35 gold already.
Here's my form.php
<div class="wrapper">
<div id="gold">
<form action="process-game.php" method="post" >
YOUR GOLD: <input type="hidden" name="building" value="gold"/>
</form>
</div>
<div class="farm_form">
<h2>Farm</h2>
<form action="process-game.php" method="post" >
<input type="hidden" name="building" value="farm"/>
<input type="submit" value="Find Gold!"/>
</form>
</div>
<div class="farm_form">
<h2>Cave</h2>
<form action="process-game.php" method="post">
<input type="hidden" name="building" value="cave"/>
<input type="submit" value="Find Gold!"/>
</form>
</div>
<div class="farm_form">
<h2>House</h2>
<form action="process-game.php" method="post">
<input type="hidden" name="building" value="house"/>
<input type="submit" value="Find Gold!"/>
</form>
</div>
<div class="farm_form">
<h2>Casino</h2>
<form action="process-game.php" method="post">
<input type="hidden" name="building" value="casino"/>
<input type="submit" value="Find Gold!"/>
</form>
</div>
</div>
Here's my process.php:
<?php
session_start();
if(isset($_POST['building'])){
echo earn_gold();
}
function earn_gold(){
if($_POST['building'] == "farm"){
$gold = rand(10,20);
}else if($_POST['building'] == "cave"){
$gold = rand(5,10);
}else if($_POST['building'] == "house"){
$gold = rand(2,5);
}else if($_POST['building'] == "casino"){
$gold = rand(0,50);
}
return $gold;
}
?>
Any idea how to do this?
I know, you basically wanted a solution in PHP. Still, I could not resist showing you, how easy it would be doing the same in JavaScript/jQuery. Have a look at it or simply ignore it. It is up to you ... ;-)
// define gold amounts for each button (min,max):
var finds={farm:[10,20],cave:[5,10],house:[2,5],casino:[0,50]};
$(function(){
$(':submit').click(function(){ // for all submit buttons: bind the click event to a function ...
var place=$(this).closest('div[id]').attr('id'); // get the id of the buttin's parent div
var fnd=finds[place]; // get the min/max array for the current button
with ($('#gold span')) // locate and use the <span> inside the div with id=gold
text(parseFloat(text()) // get the current value of the span (convert to float)
+fnd[0]+Math.ceil(Math.random()*(fnd[1]-fnd[0]))); // add the gold ...
});
})
div {display:inline-block; width: 120px; border:1px solid grey}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="farm_form" id="gold">
<h2>Your Gold</h2><span>0</span>
</div><br>
<div class="farm_form" id="farm">
<h2>Farm</h2><input type="submit" value="Find Gold!"/>
</div>
<div class="farm_form" id="cave">
<h2>Cave</h2><input type="submit" value="Find Gold!"/>
</div>
<div class="farm_form" id="house">
<h2>House</h2><input type="submit" value="Find Gold!"/>
</div>
<div class="farm_form" id="casino">
<h2>Casino</h2><input type="submit" value="Find Gold!"/>
</div>
If you really need it, I guess you can do it with sessions.
if (isset($_POST['building'])) {
// getting random gold
$earn_gold = earn_gold();
// adding to session called "gold"
$_SESSION['gold'] = (isset($_SESSION['gold']) ? $_SESSION['gold'] + $earn_gold : $earn_gold);
// redirect back to process page
header('Location: process.php');
exit;
}
And then outputting it like so
<div id="gold">
<form method="post" >
YOUR GOLD: <input type="hidden" name="building" value="gold"/>
<?php
// if set, outputting sessions "gold" value
if (isset($_SESSION['gold'])) echo $_SESSION['gold'];
?>
</form>
</div>
When the user click on find gold then submit a form which will add the gold to the total result. For example if the user gets 3 gold then add the gold variable.
$totalGold = 0;
when user.click button then $totalgold +3;
Have one form element and use javascript to assign onclick events to each of the butons and may be use ajax to submit the form dynamically and display the results back on same page.

PHP multiple image button submit form

I have been creating a website where my users can rate images that have been uploaded. Currently i use radio buttons and a submit button to get the users rating and save it within the system. I would like to change this so that the code uses image clicks to get the users rating. So far i have the following code however it only works for one image button. Is there any way to change this to get the result depending on what image has been clicked.
Code:
HTML
<form>
<input
type="image"
name="flag_submit"
src="img/Flag.png"
onmouseover="this.src='img/Flag_Click.png'"
onmouseout="this.src='img/Flag.png'"
height="30"
width="30"
/>
</form>
PHP
if (isset($_POST['flag_submit_x']))
{
//Do process of rating.
}
Is there any way that i could create multiple image buttons and in the PHP code detect what image button has been pressed?
Change name to an array name="flag_submit[1]". Assign a different value for each image and you got it.
Read it as an array on php side: if (isset($_POST['flag_submit'][1])).
Or better would be, loop throu if $_POST['flag_submit'] and find all values:
foreach ( $_POST['flag_submit'] as $value ) {
echo $value . ' has been clicked.';
}
<form method="post">
<input type="image" name="rateButton[1]" src="img/Rate1.png" height="40" width="40" value="1"/> T
<input type="image" name="rateButton[2]" src="img/Rate1.png" height="40" width="40" value="1"/> T
<input type="image" name="rateButton[3]" src="img/Rate1.png" height="40" width="40" value="1"/> T
<input type="image" name="rateButton[4]" src="img/Rate1.png" height="40" width="40" value="1"/> T
</form>
<pre>
<?php
if ( isset( $_POST['rateButton'] ) ) {
foreach ( $_POST['rateButton'] as $key => $value ) {
echo 'Image number '.$key.' was clicked.';
}
}
?>
In your case, you don't care, what value it sends, all you need to care about it is the key that was used to submit the form, because there will always be only one key set.
Here's a trick that might be of help:
I have created an HTML page of the form:
CODE
<html><body><form method="post" action="show_post.php">
<input type="image" name="stamp[1134118800]" src="redstar.gif" value="red">
<input type="image" name="stamp[1134140400]" src="greenstar.gif" value="green">
</form></body></html>
The script to which the form submits, show_post.php, reads:
CODE
<?php
print '<html><body><pre>';
print_r ($_POST);
print '</pre></body></html>';
?>
When I click on the first image, I get:
Array
(
[stamp] => Array
(
[1134118800] => 21
)
)
When I click on the second image, I get:
Array
(
[stamp] => Array
(
[1134140400] => 15
)
)
This works with Opera, IE, and Mozilla.
The First code works fine for me, the
Change name to an array name="flag_submit[1]". Assign a different value for each image and you got it.
Read it as an array on php side:
if (isset($_POST['flag_submit'][1]))
You can have multiple <button type="submit"> elements with the same name but different values that can contain the images, only the value of the one that has been clicked will be sent.
For more info, see the specification: http://www.w3.org/html/wg/drafts/html/master/forms.html#the-button-element
this might help you
<?php
if($_POST['button'])
{
echo "you have pressed button ".$_POST['button'];
}
?>
<style>
input.overridecss {
background-color: transparent;
border: 0px;
background-position: center;
background-repeat: no-repeat;
background-image: url(http://i49.tinypic.com/rm2w0i.png);
}
</style>
<form method="POST">
<input type="submit" name="button" value="1" class="overridecss"/>
<input type="submit" name="button" value="2" class="overridecss"/>
<input type="submit" name="button" value="3" class="overridecss"/>
<input type="submit" name="button" value="4" class="overridecss"/>
<input type="submit" name="button" value="5" class="overridecss"/>
</form>

extra input added by jquery doesn't work

Hi I'm trying to get a dinamically input added with Jquery, but when I try to get the code it's not working
The code in codeigniter catch all POST but less the one added by jquery
here is the code:
<script type="text/javascript">
$(document).ready(function(){
var value = parseFloat($("#subtotal").val());
$('.subtotal').html(value);
$('#subtotal').val(value);
$('input[name="phprop"]').change(function(event){
if($('input[name="phprop"]:checked').val() == 'Yes'){
$('#sections').show();
}else if($('input[name="phprop"]:checked').val() == 'No'){ $('#sections').hide();}
});
$('input[name="xsst"]').change(function(event){
if($('input[name="xsst"]:checked').val() == 'Yes'){
$('#xtraphotos').show();
$('<input type="text" name="extraid'+i+'" id="extraid'+ i +'" style="width:80px;margin-left:4px;"/>').appendTo('#xtrabox');
var num = value + 9.95;
value = parseFloat(num.toFixed(2));
$('.subtotal').html(value);
$('#subtotal').val(value);
$('#extrass').val(i); i++;
}else if($('input[name="xsst"]:checked').val() == 'No'){
$('#xtraphotos').hide();
$('#xtraphotos input[type="text"]').remove();
var num = value - 9.95 * (i - 1);
value = parseFloat(num.toFixed(2));
$('.subtotal').html(value);
$('#subtotal').val(value);
$('#extrass').val(0);
i = 1;
}
});
var scntDiv = $('#xtrabox');
var i = 1;
$('#addScnt').live('click', function() {
$('<input type="text" name="extraid'+i+'" id="extraid'+ i +'" style="width:80px;margin-left:4px;"/>').appendTo(scntDiv);
num = value + 9.95;
value = parseFloat(num.toFixed(2));
$('.subtotal').html(value);
$('#subtotal').val(value);
$('#extrass').val(i);
i++;
return false;
});
});
</script>
Here is the HTML
<div style="margin-left: 50px;">
<label><b>Do you need more photos for your web?</b> </label>Yes<input type="radio" name="xsst" id="xsst" value="Yes"/>No<input type="radio" name="xsst" id="xsst" value="No"/> (Each aditional photo has a cost of <b>$9.95</b>)
<div id="xtraphotos" style="display:none;">Add another picture box<div id="xtrabox"></div></div></div>
Here is the Codeigniter code:
if($_POST['extrass'] !=0){
for($i=1;$i<=$_POST['extrass'];$i++){
$names = "extraid".$i;
$extras .= $_POST[$names];
if($i!=$_POST['extrass']){
$extras .= "-";
}
}
Here is the complete HTML (Just the form Section):
<?php echo form_open_multipart(base_url() . 'purchase/confirmation')?>
<p style="float:left">Image ID of the Photos for your Website</p><div style="float:left;margin: 13px 0 0 110px;width: 450px;"><?php
if($idtype == 4){$x=3;}elseif($idtype == 1){$x=5;}elseif($idtype == 2){$x=10;}elseif($idtype == 3){$x=13;}
for($i=1;$i<=$x;$i++){?><input type="text" name="ssid[]" id="ssid_<?=$i?>" value="" style="width:80px; margin-left:4px;"/><?php }?></div>
</div>
<div style="margin-left: 50px;">
<label><b>Do you need more photos for your web?</b> </label>Yes<input type="radio" name="xsst" id="xsst" value="Yes"/>No<input type="radio" name="xsst" id="xsst" value="No"/> (Each aditional photo has a cost of <b>$9.95</b>)
<div id="xtraphotos" style="display:none;">Add another picture box<div id="xtrabox"></div></div></div>
<br />
<div id="choose_your_template" style="background-image:url(<?=base_url()?>images/step_4.png)"><div style="padding-left:5px; float:left">
<span style=" position: relative; top: 14px; left: 210px; font-size: 18px; color: gray; ">Step 4: Do you have Photos? Upload the pictures for your website.</span></div>
</div>
<div style="margin-left: 50px;">
<label>Do you have photos of your property? </label>Yes<input type="radio" name="phprop" id="phprop" value="Yes"/>No<input type="radio" name="phprop" id="phprop" value="No"/><br />
<div id="sections" style="display:none;">
<p>Upload the photos in the theme that they should be used. The photos should be in jpge.format. Otherwise the system will not accept. them.</p><br/>
<?php
if($idtype == 4){$x=1;}elseif($idtype == 1){$x=3;}elseif($idtype == 2){$x=4;}elseif($idtype == 3){$x=5;}
for($i=1;$i<=$x;$i++){?>
<label>Section</label><select name="section[]" id="section"><option value="">Choose Section</option><option value="home">Home</option><option value="about-us">About Us</option><option value="contact-us">Contact Us</option></select><?php for($j=1;$j<=4;$j++){?><input type="file" name="userphoto<?=$i?><?=$j?>" /><?php }?><br /> <br />
<?php }?>
<p>I certify that the photos that i am uploading for the website development are of my entire property and that I have all the copyrights.</p></div>
</div><br />
<input type="hidden" id="domain" name="domain" value="<?=$domain?>" />
<input type="hidden" id="payment_plan" name="payment_plan" value="<?=$poption?>" />
<?php if($ownamedomain){?>
<input type="hidden" name="ownamedomain" id="ownamedomain" value="<?=$ownamedomain?>" />
<?php }?>
<input type="hidden" name="idtype" id="idtype" value="<?=$idtype?>" />
<input type="hidden" name="templateid" id="templateid" value="<?=$templateid?>" />
<input type="hidden" name="extrass" id="extrass" value="0" />
<input type="hidden" name="subtotal" id="subtotal" value="<?=$subtotal?>" />
<div style="padding-left:45px; padding-top:15px;">
<hr style=" width: 868px; margin: 0 0 16px; "/>
<div align="center">
<p>Subtotal: USD$<span class="subtotal"><?=$subtotal?></span> </p></div>
</div>
<div style="background:url(<?=base_url()?>images/bottombar.png) no-repeat;display: block;height: 16px;margin: 0 36px 10px;width: 902px;"></div>
<input type="submit" name="continue" id="continue"/><input type="button" value="Back" onClick="history.back();" class="back">
</div>
Your HTML have a tag form?
When.you not put forms elements inside a form, onload, some brownser add a form to correct code syntax... But when you add nes elements using DOM, maybe this elements not include inside this form...

Categories