php form using array - php

I want to create a form using array that user can select a number and echoes the number's corresponding object name after submit. I don't know why this code does not work, could someone please teach me how to do it the right way :( Thank you so much for your time.
<form name="train" method="GET" action="test.php">
<select name="object">
<option value="0">0</option>
<option value="1">1</option>
<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="all">Show All</option>
</select>
<input type="submit" name="submit" id="submit" value="submit" size="10">
</form>
<?php
$train[0] = "pencil";
$train[1] = "macaron";
$train[2] = "notes";
$train[3] = "book";
$train[4] = "eraser";
$train[5] = "cake";
$train[6] = "laptop";
$train[7] = "mint";
$train[8] = "cup";
if ($_GET['submit']) {
$train = $_GET['obejct'];
echo "<p>I have $train!</p>";
}
?>
Thank you so much!

Looks like you're setting $train to the value of whatever the form passes for the "object" select field, and then echoing that. You would expect then to see a number between 0 and 8, or the word "all" print out, but your reference of the object key has the word "object" misspelled as "obejct", so my guess is you're getting nothing to print as the value of $train.
Either way, what you really want to do is print the value at the key in the $train array that corresponds with what was provided by the user. This means that once you've created your array, which functions as a map, you must select the item from the array that you want to print.
You also need to handle the "all" case or you will get an error.
Here's how it would look if you continue using the array option:
<form name="train" method="GET" action="test.php">
<select name="object">
<option value="0">0</option>
<option value="1">1</option>
<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="all">Show All</option>
</select>
<input type="submit" name="submit" id="submit" value="submit" size="10">
</form>
<?php
$train[0] = "pencil";
$train[1] = "macaron";
$train[2] = "notes";
$train[3] = "book";
$train[4] = "eraser";
$train[5] = "cake";
$train[6] = "laptop";
$train[7] = "mint";
$train[8] = "cup";
if ($_GET['submit']) {
if ($_GET['object'] != 'all') {
//Handle the non-all case
$value = $train[$_GET['object']]; //This references a key in your array, like $train[0]
echo "<p>I have $value!</p>";
} else {
//Handle the all case here
}
}
?>

Related

PHP and SQL - How can I make this ID into a variable?

I am making a PHP website, and I want my user ID to load into the tickets table when you order a ticket. There is a webpage where you can select the ticket, the amount, and the ID is already given as a label.
The first code adds the data to my database
function best(){
global $db, $errors;
// receive all input values from the form
$ticket = e($_POST['tickety']);
$aantall = e($_POST['aantal']);
$usidd = e($_POST['usid']);
// form validation: ensure that the form is correctly filled
if (empty($ticket)) {
array_push($errors, "Ticket is verplicht");
}
if (empty($aantall)) {
array_push($errors, "Aantal is verplicht");
}
// order ticket if there are no errors in the form
if (count($errors) == 0) {
$con = new PDO("mysql: host=localhost; dbname=website", "root", "");
mysqli_query($db, $query);
$_SESSION['success'] = "Ticket besteld";
header('location: index.php');
$query = "INSERT INTO tickety (ticket, aantal, userid)
VALUES('$ticket', '$aantall', '$usidd')";
mysqli_query($db, $query);
}
}
This code defines the input fields
<form method="post" action="ticketpag.php">
<?php echo display_error(); ?>
<div class="input_group">
ID
</br>
<input type='hidden' name='usid'>
<h4><?php
echo $_SESSION['user']['id'];
?></h4>
</input>
Ticket
</br>
<select name='tickety'>
<?php
$query = "SELECT * FROM `stok`";
$result = mysql_query($query);
while($row=mysql_fetch_array($result, MYSQL_ASSOC)){
echo "<option>".$row['naam']."</option>";
}
?>
</select>
</br>
Aantal
</br>
<select name="aantal">
<option value="1">1</option>
<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>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
</select>
</div>
<div class="input-group">
<button type="submit" class="btn" name="bestel_btn"> Bestellen</button>
Terug
</div>
</form>
Add $_SESSION['user']['id']; to an input field instead of a label and it should work.
Example:
<input type="hidden" name="usid" id="usid" value="<?php echo $_SESSION['user']['id'];?>" />
Hidden fields are not shown to a user.
Addition:
But, as #mickmackusa mentioned, sending existing SESSION data using a POST request is a bad-practise. Instead test and see what happens when you echo $_SESSION['user']['id'] inside of best(). You should not be using POST to deliver existing SESSION data.

How to ajax this dropdown php variable

I simply don't get jquery or ajax.
I understand javascript just fine, but for some reason, I can't ajax through my head.
I'm sorry I have to ask this, but can some help me, I just spent literally the last day trying to make this jquery/ajax work for this drop down box, been through a bunch of examples. Tried them. Don't work.
This is what I'd like.
The below drop box to dynamically change a variable in php without a submit button.
I would like to use only one file, a php file named single-event.php .
then display $total php variable in that h2 everytime the drop down box is changed.
<?php $cost = 10.00;?>
<select id = "attendee" class='postform' onchange="Onchange(this)" >
<option value="1">1</option>
<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>
<?php $total=$cost*$(drop_down_box_selected); ?>
<h2>
<?php _e('Submit a payment of $' . $total , 'pippin_stripe'); ?>
</h2>
I normally wouldn't go this low and simply ask someone to do my work but I'm just sick of trying, this was the closest i got to anything i wanted, but discovered I NEED to convert the value to a php variable.
Please help, I'm basically pulling my hair(not really as I'm bald), tired and still have an entire different project that needs to be finished by Monday.
<select id = "attendee" class='postform' onchange="Onchange(this)" >
<option value="1">1</option>
<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>
<script type="text/javascript">
var dropdown = document.getElementById("attendee");
function onCatChange() {
if ( dropdown.options[dropdown.selectedIndex].value != -1 ) {
document.getElementById("hi").innerHTML = dropdown.options[dropdown.selectedIndex].value;
var price = document.getElementById("hto").value
var num = dropdown.options[dropdown.selectedIndex].value;
var total = price*num ;
dropdown.onchange = onCatChange;
</script>
Thank you to anyone who gives any help.

array in php function undefined

For training purposes i need to make a function which tells me the 'travel cost' between 2 cities. The book tells me to type this function:
<?php
function travelcost($start, $destination)
{
$travelcost = array();
$travelcost[1] = array();
$travelcost[2] = array();
$travelcost[3] = array();
$travelcost[4] = array();
$travelcost[1][1] = 0;
$travelcost[1][2] = 30;
$travelcost[1][3] = 60;
$travelcost[1][4] = 90;
echo($travelcost[$start][$destination] . " Euro's");
}
?>
In addition i've created this form to ask for a start and a destination:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Start: <select name="start" value="true">
<option value="start[]">Amsterdam</option>
<option value="start[]">Utrecht</option>
<option value="start[]">Den Haag</option>
<option value="start[]">Rotterdam</option>
</select>
Destination: <select name="destination" value="true">
<option value="destination[]">Amsterdam</option>
<option value="destination[]">Utrecht</option>
<option value="destination[]">Den Haag</option>
<option value="destination[]">Rotterdam</option>
</select>
<p><input type="submit" name="calculate" value="Calculate"</p>
</form>
Followed by:
<?php
if(isset($_POST["start"])&& isset($_POST["destination"]))
{
travelcost($_POST['start'], $_POST['destination']);
}
?>
This gives me Undefined index: start[]
I know im doing it wrong, but i just can't see the logic in the function and the array. I assume the function is correct because it's right out of the book but i'm also not sure about that.
Can someone help me out?
This is wrong,
<option value="start[]">Amsterdam</option>
^ ^
It should be
<option value="start">Amsterdam</option>
or
<option value="Amsterdam">Amsterdam</option>
Same for all options in start and destination.
According to your function `travelcost(), your select should be
Start: <select name="start" value="true">
<option value="1">Amsterdam</option>
<option value="1">Utrecht</option>
<option value="1">Den Haag</option>
<option value="1">Rotterdam</option>
</select>
Destination: <select name="destination" value="true">
<option value="1">Amsterdam</option>
<option value="2">Utrecht</option>
<option value="3">Den Haag</option>
<option value="4">Rotterdam</option>
</select>

html select value 0 is in php validation always empty

I try to post the selected value and check if the variable is empty.
html:
<select id="monitors-old" class="form-control" name="monitors-old">
<option value="">Auswählen...</option>
<option value="0" <?php if ($personData["cmo_mon"] == "0"){echo 'selected';}?>>0</option>
<option value="1" <?php if ($personData["cmo_mon"] == "1"){echo 'selected';}?>>1</option>
<option value="2" <?php if ($personData["cmo_mon"] == "2"){echo 'selected';}?>>2</option>
<option value="3" <?php if ($personData["cmo_mon"] == "3"){echo 'selected';}?>>3</option>
<option value="4" <?php if ($personData["cmo_mon"] == "4"){echo 'selected';}?>>4</option>
</select>
Result html:
<select id="monitors-old" class="form-control" name="monitors-old">
<option value="">Auswählen...</option>
<option value="0" selected="">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
POST Check:
if (empty($_POST["monitors-old"])) {
$errors[] = "Alt-Monitore is required.";
die;
} else {
$monitors_old = validateInput($_POST["monitors-old"]);
}
the value 0 is always empty and the script fired the die, all other values are working.
Is the value 0 like ""?
Also tried:
<select id="monitors-old" class="form-control" name="monitors-old">
<option>Auswählen...</option>
<option selected="">0</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
This is also working, but the same issue. And another question, why is the selected allocated to ="" ? I thought it is only a tag for html, that this value is the selected?
validateInput:
function validateInput($value) {
$value = trim($value);
$value = stripslashes($value);
$value = htmlspecialchars($value);
return $value;
}
The empty() function will return TRUE if the value is even 0.
So you should use the isset() function and != operation for checking
if(isset($_POST["monitors-old"]) and $_POST["monitors-old"]!=''){
// code here
}
else{
// code here
}

using AJAX to return values in javascript to php all on the same page

hello all im back with another question on my project. i keep getting stuck for some reason! i only started using AJAX today so i hope you will forgive my ignorance! okay first of all i have a type button and when i click on it i want it to return a number (which is the amount of a particular item the customer wants to purchase) and the name of a item. the number is selected from a dropdownlist and the name of the book is got from a input type=" hidden". to get the number from the dropdown list to php i want to use AJAX which i have set up as a method in the header of my html page. the code for this method is shown below at the moment im trying to use ajax to return the number of the item to this same php page. here is the method.
function ajax_post(myform)
{
var hr = new XMLHttpRequest();
var url = "islandshop.php";
var index = myform.quantity1.selectedIndex;
var value = document.getElementById("quantity1").options[index].value;
var variable = "value="+value;
hr.open("post", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(variable);
document.getElementById("status").innerHTML = "processing data";
}
next is where when i press the button i want just the number from the dropdown list returned to me in php. but when i clcik on the button which is my add to cart button it returns the whole page "islandshop.php" to me. but with the value at the end of the page which is not all bad at least it is returning the value. here is my form where i call the ajax_post() method with my button.
<form method="post" action="" name="form1">
<span style="color:#000"> <label for="quantity">Quantity:</label></span>
<select name="quantity1" id="quantity1" onchange="">
<option value="1" selected>1</option><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><option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option><option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option><option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option><option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option><option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option><option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option><option value="29">29</option>
<option value="30">30</option>
</select>
<input type="hidden" name="book1" value="cape clear island: its peopleand landscape" />
<input type="button" value="Add To Cart" name="submit1" onclick="javascript:ajax_post(this.form)"></button>
</form>
which to me seems fine. and the last part is just php tags at the end of the islandshop.php page where i try and print the value and get a copy of the whole page back. so essentially i have my page shown twice in the browser. but with the value in the second version of the page.
<?php
if(isset($_SESSION['username']))
{
echo 'Thank you you selected '. $_POST['value'];
}
?>
i think i know why im getting the whole page back when i press the button as i have the hr.open() url as this page "islandshop.php. i read something about this and it said something about sending the values to the browser and then the browser sending the variable back to a .php page which would redirect them to the original page but it wasnt explained very well. so really my main goal is to just get the value from the dropdown list back to me from the server in php form so i can use the value to do stuff on this page! thanks again for the help hopefully i wont have to post so many questions after i figure this one out. even if anyone can direct me to a good book or article on AJAX i would be delighted! cheers
If you are posting back to the same page then you can do a conditional check to see if the $_POST['value'] is set or not. If it is then do an echo, if not then display the html.
<?php
if( isset($_SESSION['username']) && isset( $_POST['value'] ) )
{
echo 'Thank you you selected '. $_POST['value'];
}
else
{
?>
<form method="post" action="" name="form1">
<span style="color:#000">
<label for="quantity">Quantity:</label></span>
<select name="quantity1" id="quantity1" onchange="">
<option value="1" selected>1</option><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><option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option><option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option><option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option><option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option><option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option><option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option><option value="29">29</option>
<option value="30">30</option>
</select>
<input type="hidden" name="book1" value="cape clear island: its peopleand landscape" />
<input type="button" value="Add To Cart" name="submit1" onclick="javascript:ajax_post(this.form)"></button>
</form>
<?php } ?>
I strongly advise you to take a look at the jQuery: http://jquery.com/

Categories