PHP, linking variables to a specific date in a form - php

How can I assign a variable to a specific date for use in a form?
I want a warning to appear when the user tries to book too many a people on a specific date. I started writing this code but didn't know where to go from there:
<?php
$spaces = 20;
$num_people = GET('#people');
$message = "Unfortunately we don't have this many spaces avilable on this date. We have a maximum of $spaces.";
if($spaces < $num_people) {
echo $message;
}
?>
How could I assign the value $spaces to a specific date and link it into a form? Here is the form:
<form method="post">
Name:<br>
<textarea id="name"></textarea><br>
<br>
Date leaving:<br>
<br>
<textarea id="date"></textarea><br>
<br>
How many people?:<br>
<textarea id="people"></textarea><br>
<br>
<input type="submit">

$num_people = GET('#people');
This line should be
$num_people = $_GET['people'];
and
<textarea id="people"></textarea><br>
shoul be
<textarea id="people" name="people"></textarea><br>
And your method ahould be GET. Since you are sending GET request.
Your code should look like this:
<?php
if(isset($_GET['people'])){
$spaces = 20;
$num_people = $_GET['people'];
$message = "Unfortunately we don't have this many spaces avilable on this date. We have a maximum of $spaces.";
if($spaces < $num_people) {
echo $message;
}
}
?>
<form method="get" action="">
Name:<br>
<textarea id="name"></textarea><br>
<br>
Date leaving:<br>
<br>
<textarea id="date"></textarea><br>
<br>
How many people?:<br>
<textarea id="people" name="people"></textarea><br>
<br>
<input type="submit">

Related

Getting x amount of items from array

I'm doing this task in school where I'm to do something with arrays and loops in PHP.
What I've done so far is make this piece of code, that makes an array with names from a separate text-file, and chooses a random name from that array.
What I'd like it to do now is to display x amount of random names. The amount of names can be chosen in an input field, preferably with a for or while loop (those are the ones I know somewhat).
Here is my code (Don't think the text-file is necessary. If it is, just let me know):
<form method="POST">
How many names do you need?
<input type="number" name="amount" min="1" max="28"><br><br>
<input type="submit" name="proceed" value="Get name(s)">
</form>
<?php
$text = file_get_contents("names2t.txt");
$Array = explode("\n", $text);
$randNameNum = array_rand($Array);
$randPhrase = $Array[$randNameNum];
if (isset($_POST["proceed"])){
echo $randPhrase;
}
?>
Is it possible to do what I'm asking?
Just add another field on your form and loop on it :
<form method="POST">
How many names do you need? <input type="number" name="amount" min="1" max="28"><br>
How many times? <input type="number" name="repeat-count"><br>
<input type="submit" name="proceed" value="Get name(s)">
</form>
<?php
if(isset($_POST['proceed'])) {
for($i = 0; $i < $_POST['repeat-count']; $i++) {
$text = file_get_contents("names2t.txt");
$Array = explode("\n", $text);
$randNameNum = array_rand($Array);
echo $Array[$randNameNum];
}
}
?>

Form with random number as validation

The following PHP code is for generating a random number of four digits ($numero) and using it as a validation for a simple HTML form with three input boxes. The last input box is for entering the code (the random number). If the user doesn't write the right number in that last input box the program skips its purpose, which is adding some text to a database (agregar.txt). I think the code is fine, except for if ($_POST['password'] != $numero) {. Should I change it to a string or use another kind of variable? Each time I run the code it acts as if $numero was different from password, and I'm sure I'm writing the right number. Please some help.
<html>
<body>
<center>
<h2>Agregar entradas a diccionarioie</h2>
<?php
// RANDOM FOUR DIGITS NUMBER
$numero = rand(1000, 9999);
echo "<b>Código: </b><big>".$numero."</big><p>";
if ($_POST['password'] != $numero) {
?>
<form name="form" method="post" action="">
<input title=" LEMA " size="30" type="text" name="lema" autofocus><br>
<input title=" TRADUCCIÓN " size="30" type="text" name="trad"><br>
<input title=" CÓDIGO " size="30" type="text" name="password"><br>
Gracias por colaborar <input title=" ENVIAR " type="submit" value="•"></form>
<?php
} else {
$lema = $_POST['lema'];
$trad = $_POST['trad'];
// ADDING TEXT TO A DATABASE
$texto = $lema." __ ".$trad."\n";
$docu = fopen("agregar.txt", "a+");
fwrite($docu, $texto);
fclose($docu);
}
?>
</center>
</body>
</html>
As pointed out by #Fred -ii-, the problem in your code is the $numero get generated to different random number when you submit the form. The solution is to use session: PHP session example
The session can be used to store your $numero value after the form being submitted. Here's the updated code:
<?php
// Make sure to start the session before any output.
session_start();
if (isset($_POST['password']) && isset($_SESSION['numero']) && $_POST['password'] == $_SESSION['numero']) {
unset($_SESSION['numero']);
$lema = $_POST['lema'];
$trad = $_POST['trad'];
// ADDING TEXT TO A DATABASE
$texto = $lema." __ ".$trad."\n";
$docu = fopen("agregar.txt", "a+");
fwrite($docu, $texto);
fclose($docu);
} else {
// RANDOM FOUR DIGITS NUMBER & STORE IT IN SESSION.
$numero = $_SESSION['numero'] = rand(1000, 9999);
?>
<html>
<body>
<center>
<h2>Agregar entradas a diccionarioie</h2>
<b>Código: </b><big><?php echo $numero; ?></big><p>
<form name="form" method="post" action="">
<input title="LEMA " size="30" type="text" name="lema" autofocus><br>
<input title="TRADUCCIÓN " size="30" type="text" name="trad"><br>
<input title="CÓDIGO " size="30" type="text" name="password"><br>
Gracias por colaborar <input title=" ENVIAR " type="submit" value="•">
</form>
</center>
</body>
</html>
<?php }
Just make sure that you call session_start() before any output (in your case the HTML document).
Hope this help.

PHP - Insert elemens into an array

I'm working on a formular, but for the moment I just want to insert into an array my elements (I have books and authors).
I can display my books with author (name + surname) with the foreach, but I can't add more elements.
Here is the code with the form.
<H1>Exercice 2</H1>
<form method="POST">
<label for"code" >Number :</label>
<input id="code" name="code" type="number" />
<label for"title">Title :</label>
<input id="title" name="title" type="text" />
<label for"author" >Author :</label>
<input id="author" name="author" type="text" />
<button type="input" type="submit">Ok</button>
$title = $_POST['title'];
$code = $_POST['code'];
$author = $_POST['author'];
$book = array();
$book['code'] = 123;
$book['title'] = "Legendes";
$book['author'] = array("David", "Gemmel");
foreach($book as $value){
$book['key'] = $value;
var_dump($book);
if (is_array($value)) {
foreach($value as $otherValue) {
echo($otherValue);
}
} else {
echo($value);
}
}
I did some searcch, but I don't think it works, it's using the array_push() method with the POST, but I don't know where I can manipulate my form into the array.
If you want some details, I'll be happy to do that =) I'm working on it, if i have some news, you will know =)
Have a nice day =)
1) Assignments are in reverse. Correct way:
$myVar = $myValue
2) You need to set the name attribute in your inputs in order to be sent:
<input id="code" type="number" name="code" />
Then you can access them like:
$_POST['code']
3) To add an element by key in an array, use:
$array['key'] = $value;
Your Exercise 2 have some mistakes :
First, your HTML inputs must have the name attribute to be retrieved by post:
<h1>Exercice 2</h1>
<form method="post">
<label>
<input name="code" type="number" />
</label>
<button type="submit">Ok</button>
</form>
With PHP, you can access to any input value using the name:
$code = $_POST['code'];
Now, I think you want to "add" several books using this HTML form without a storage system. The problem is you can not do this if for every a new request since all the elements you have in your array will be deleted each time you run a new post request. To keep this information you need to use some persistent storage system as a database or others.
Since you seem to want to keep the information for each book together, you need to use a multidimensional array - hence, you'll need to redo the whole thing. Here's a suggestion:
Form:
<h2>Exercice 2</h2>
<form method="post">
<label for"code">Number :</label>
<input id="code" name="code" type="number">
<label for"title">Title :</label>
<input id="title" name="title" type="text">
<label for"author-firstname">Author First Name:</label>
<input id="author-firstname" name="author-firstname" type="text">
<label for "author-lastname">Author Last Name:</label>
<input id="author-lastname" name="author-lastname" type="text">
<input type="submit" name="submit_book" value="Ok">
</form>
Fixed the name-problems, changed the heading (you never, ever use H1 for a form, H1 is strictly used for the site-wide heading/logo/name of site). Also changed the button into a simple input type="submit".
$title = $_POST['title'];
$code = $_POST['code'];
$author = $_POST['author'];
$book = []; // changed this to modern PHP version array assignment
$book[0]['code'] = 123;
$book[0]['title'] = "Legendes";
$book[0]['author-firstname'] = "David";
$book[0]['author-lastname'] = "Gemmel"; // no reason to assign a separate array for first and last name, just use two array-keys
for ($c = 0; $c <= count($book); $c++) { //changed this to a for, counting the amount of entries in the $book array
echo 'Title: '.$book[$c]['title'];
echo 'Author: '.$book[$c]['author-firstname'].' '.$book[$c]['author-lastname'];
} // the content should probably be wrapped in a container of some sort, probably a <li> (and then a <ul>-list declared before the for-loop)
Now. None of this has anything to do with putting stuff INTO the array. That would be something like this (there isn't even a point of assigning the $_POST-variables for the code you posted. But, you can do something like this:
if (isset($_POST['submit_book'])) {
$title = $_POST['title'];
$code = $_POST['code'];
$author-firstname = $_POST['author-firstname'];
$author-lastname = $_POST['author-lastname'];
// however, if all you're doing is putting this into the array, no need to assigne the $_POST to variables, you can just do this:
$temp_array = ['code'=>$_POST['code'],'title'=>$_POST['title'],'author-firstname'=>$_POST['author-firstname'],'author-lastname'=>$_POST['author-lastname']];
$book[] = $temp_array;
}
So, that would replace the assigned variables at the beginning of your code.

Add Update And Delete Button In Retrieved Data From SQL Using PHP

I am retrieving data from SQL using PHP on a page and showing many records at a time using below code.
<?php
//Database Connection File
require_once("config.php");
//Everything Is Okay So Let's Garb This User Contacts Data
$garb = mysqli_query($connection, "SELECT * FROM contacts WHERE A_Id = '$A_Id'");
if(!$garb){
$error = "<div class='error'>There's Little Problem: ".mysql_error()."</div>";
} else {
//Data Is Collected
//Showing The User Data
$idNo = 0;
while($row = mysqli_fetch_array($garb)) {
$C_FullName = $row['C_FullName'];
$C_Gender = $row['C_Gender'];
$C_ContactPhone = $row['C_ContactPhone'];
$C_ContactCell = $row['C_ContactCell'];
$C_Email = $row['C_Email'];
$C_Address = $row['C_Address'];
$C_Group = $row['C_Group'];
$C_Notes = $row['C_Notes'];
echo '
<div class="accordionItem close">
<h3 class="accordionItemHeading">'.$C_FullName.'</h3>
<div class="accordionItemContent">
<div id="contactDetailes">
<form id="updateAllContact'.$idNo.'" method="post" action="">
<p><label>Full Name:* </label><input type="text" name="C_FullName" value="'.$C_FullName.'"></input></p>
<p><label>Gender:* </label><input type="text" name="C_Gender" value="'.$C_Gender.'"></input></p>
<p><label>Contact No(Phone): </label><input type="text" name="C_ContactPhone" value="'.$C_ContactPhone.'"></input></p>
<p><label>Contact No(Cell): </label><input type="text" name="C_ContactCell" value="'.$C_ContactCell.'"></input></p>
<p><label>Email Address:* </label><input type="text" name="C_Email" value="'.$C_Email.'"></input></p>
<p><label>Address: </label><input type="text" name="C_Address" value="'.$C_Address.'"></input></p>
<p><label>Group: </label><input type="text" name="C_Group" value="'.$C_Group.'"></input></p>
<p><label>Notes: </label><textarea type="text" name="C_Notes">'.$C_Notes.'</textarea></p>
<span>
<a class="updateButton">Update</a>
<a class="deleteButton">Delete</a>
</span>
</form>
</div>
</div>
</div>
';
$idNo++;
}
}
?>
Now the problem is that I want to add Update and Delete function for every row retrieved from database. What I want is something like HTML5 Web SQL Databases And Usage or something like HTML5 Address Book using PHP and SQL. So how can I add functions of Update and Delete in my every row data...???

How to submit a single form value multiple times and store (preserve) them in an array each time that I refresh my page?

Attempt 1: This shows what I want to achieve. The same array but different key and value pair.When printed, it list out all the keys and values.
<?php
$rental[]=array('day'=>1,'rate'=>10);
$rental[]=array('day'=>2,'rate'=>20);
$rental[]=array('day'=>3,'rate'=>30);
$rental[]=array('day'=>4,'rate'=>40);
print_r($rental);
?>
Attempt 2: Now, I'm using a single form to submit multiple times.I expect the key and values to be stored inside an array each time the form is submitted. But what happens is, the last value pair overwrites the previous one.Therefore only one pair is shown. So far, I can store them with the help of session. But I just wonder if there's a way to achieve it via php array on the same page?
<?php
$rental[]=array('day'=>$_POST['days'],'rate'=>$_POST['rental']);
print_r($rental);
?>
<form action="#" method="post">
Number of Days: <input type="text" name="days" value=""><br/>
Rental rate: <input type="text" name="rental" value=""><br/>
<input type="submit" name="add_rental_rate" value="Add Rental Rate">
</form>
You can use session to achieve what you want, see this code:
<?php
session_start();
if(isset($_POST['days']) && isset($_POST['rental'])){
$_SESSION['info'][] = array($_POST['days'] => $_POST['rental']);
}
if(isset($_SESSION['info'])) {
for($i = 0; $i < count($_SESSION['info']); $i++) {
foreach($_SESSION['info'][$i] as $days => $rental){
echo '<p>' . $days . '<br>';
echo $rental . '</p>';
}
}
}
?>
<form action="#" method="post">
Number of Days: <input type="text" name="days" value=""><br/>
Rental rate: <input type="text" name="rental" value=""><br/>
<input type="submit" name="add_rental_rate" value="Add Rental Rate">
</form>
You should read some docs about session:
http://php.net/manual/en/intro.session.php

Categories