PHP - Getting back Post from forEach select form - php

i have a website where the admin can choose to add a certain number of bbcode tags and the corresponding html tags.
First he chooses how many tags he wants to add from a drop down select form in a for Each loop.
Depending on how many tags he chose when he clicked the submit button, the corresponding number of input tags appear in a second form, also in a for Each loop. He fills in the bbcode and html input and clicks the submit button. Normally the tags should be added to my database but in this case when he clicks submit the form disappears and nothing is added..
Here is the code :
//FIRST FORM WHERE HE DECIDES HOW MANY TAGS TO ADD
<form id='nbbalises' action='config.ini.php' method='post' accept-charset='UTF-8'>
<fieldset>
<legend>How many tags ?</legend>
<input type='hidden' name='submitted' id='submitted' value='1' />
<?php
echo '<select name="number">';
$range = range(1,50,1);
foreach ($range as $nb) {
echo "<option value='$nb'>$nb</option>";
}
echo "</select>";
?>
<input type='submit' name='Submit' value='Submit' />
</fieldset>
</form><br /> <br />
<?php
if (!(empty($_POST['number']))) {
if ($_POST['number'] >= 1 && $_POST['number']<= 50){
$number = $_POST['number'];
$range2 = range(1,$number,1);
?>
//SECOND FORM WHERE I GENERATE THE INPUT DEPENDING ON THE NUMBER CHOSEN FROM FIRST FORM
<form id='balises' action='config.ini.php' method='post' accept-charset='UTF-8'>
<fieldset>
<legend>Balises bbc : </legend>
<input type='hidden' name='submitted' id='submitted' value='1' />
<?php
foreach ($range2 as $nb2) {
echo "<label>bbcode tag $nb2 :</label>
<input type='text' size='40' name='bbc$nb2' id='bbc$nb2' maxlength='40' />
<label>html tag $nb2 :</label>
<input type='text' size='40' name='html$nb2' id='html$nb2' maxlength='40' />
<br />";
}
}
?>
<input type='submit' name='Submit2' value='Submit2' />
</fieldset>
</form>
<?php
//PROBLEM STARTS HERE, NOTHING WORKS UNDER HERE
if (isset($_POST['Submit2'])){
//CONNECT TO MY DATABASE
connectDB();
for ($i=0; $i<$number ; $i++){
if (!(empty($_POST["bbc$i"])) && (empty($_POST["html$i"])))
//FUNCTION ADDS TAGS TO DATABASE
addBbc($_POST["bbc$i"], $_POST["html$i"]);
}
mysql_close();
}
}
//MY FUNCTIONS TO ADD THE BBCODE AND HTML TO DATABASE
function connectDB(){
//connexion DB
$link = mysql_connect('127.0.0.1', 'USERNAME', 'PASSWORD');
if (!$link) {
die('Erreur de connexion: ' . mysql_error());
}
$db = mysql_select_db('1213he200967',$link) or die("N'a pu selectionner
1213he200967");
mysql_query("SET NAMES 'utf8'");
}
function addBbc($bbc, $html){
$b = mysql_real_escape_string($bbc);
$h = mysql_real_escape_string($html);
$query="INSERT INTO bbcode (BBC,HTML) VALUES ('$b','$h')";
$result = mysql_query($query) or die("error");
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
die($message);
return false;
}
else return true;
}
Thank you very much, and sorry if my code is amateur-ish, i'm only starting in php.
EDIT
Found part of my problem
$number = $_POST['number'];
$range2 = range(1,$number,1);
This goes from 1 to the number chosen by the user in the first form.
for ($i=0; $i<$number ; $i++){
if (!(empty($_POST["bbc$i"])) && (empty($_POST["html$i"])))
//FUNCTION ADDS TAGS TO DATABASE
addBbc($_POST["bbc$i"], $_POST["html$i"]);
This goes from 0 to $number - 1
So i changed my code to this.
for ($i=0; $i<$number ; $i++){
$nb = $i + 1;
if (!(empty($_POST["bbc$nb"])) && (empty($_POST["html$nb"]))) {
addBbc($_POST["bbc$nb"], $_POST["html$nb"]);
}
else echo "$nb tags empty ";
This works a bit better but now it goes to the else just here above and displays "2 tags empty", so it still doesn't quite work.

Ok to solve it I finally decided to post the data from the second form to another page and i modified my code to this.
for ($i=0; $i<$number ; $i++){
$nb = $i + 1;
$varBbc = 'bbc'.$nb;
$varHtml = 'html'.$nb;
if ((isset($_POST[$varBbc])) && (isset($_POST[$varHtml]))) {
addBbc($varBbc, $varHtml);
}
else echo "$nb tags empty ";
}
Apparently using !empty instead of isset doesn't work in this case, maybe because of the html tags.

$nb should be in double quotes.
so echo "<option value='$nb'>$nb</option>"
change to echo "<option value='".$nb."'>$nb</option>";
and also
if (!(empty($_POST['number']))) {
if ($_POST['number'] >= 1 && $_POST['number']<= 50){
$number = $_POST['number'];
$range2 = range(1,$number,1);
?>
change to:
if (isset($_POST['submit'])) {
if ($_POST['number'] >= 1 && $_POST['number']<= 50){
$number = $_POST['number'];
$range2 = range(1,$number,1);
?>

Related

PHP: Generating a html table through a form [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 5 months ago.
This is practice coursework for my Informatics course. We've just started programming in PHP and our task is to program a website that generates tables for the user.
password prompt
ask the user how many rows and columns the table should have
based on the last question; create a form with the same amount of input boxes
generate the table with the input of step 3
I've accomplished everything until step 4. The user can input data in the form, but I the problem is that when I try to generate the table, PHP will show me this error message: "Undefined index: rows on line 70".
As I described earlier I'm just about to learn PHP, so there may be many "not so very nice programming approaches"; therefore I'm open to all kinds of recommendations.
<!DOCTYPE html>
<html>
<body>
<form method="post" target="">
<label for="login">User: </label>
<input name="login">
<br />
<label for="password">Password: </label>
<input name="password" type="password">
<br />
<input type="submit" name="generate" value="Login" />
</form>
<?php
if (isset($_POST['generate'])) {
$username = $_POST['login'];
$password = $_POST['password'];
$hashed_username = sha1($username);
$hashed_password = sha1($password);
$correct_username = '9d6035e25958ec12fca7ec76d68c8daaf4815b9b'; //wims
$correct_password = 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3'; //test
if ($hashed_username != $correct_username)
die("Wrong user name!");
if ($hashed_password != $correct_password)
die("Wrong password!");
echo "How many rows and columns should the table have? <br />";
echo('
<form method="POST" target="">
Rows: <input type="number" name="rows" min="1" max="100"/><br/>
columns: <input type="number" name="columns" min="2" max="100"/><br/>
<input type="submit" name="generate1" value="Generate Table" />
</form>');
}
if (isset($_POST['generate1'])) {
$rows = $_POST['rows'];
$columns = $_POST['columns'];
global $rows, $columns;
if ($rows > 100 || $rows < 1)
die("Nope!");
if ($columns > 100 || $columns < 2)
die("Nope!");
echo '<form method="POST" target="">';
echo "<table>";
for ($a=1;$a<=$rows;$a++) {
echo "<tr>";
for ($b=0;$b<=$columns;$b++) {
if ($b==0)
echo "<td>$a. Row</td>";
else {
$c = $a . $b;
echo "<td><input type='text' name='$c' /></td>";
}
}
echo "</tr>";
}
echo "</table>";
echo "<input type='submit' name='generate2' value='Generate' />";
echo "</form>";
}
if (isset($_POST['generate2'])) {
echo "<table>";
for ($a=1;$a<=$GLOBALS['rows'];$a++) {
echo "<tr>";
for ($b=0;$b<=$GLOBALS['columns'];$b++) {
if ($b==0)
echo "<td>$a. row</td>";
else {
$c = $a . $b;
echo "<td>$_POST[$c]</td>";
}
echo "</tr>";
}
echo "</table>";
}
}
?>
</body>
</html>
You need to store your $rows and $columns in $_SESSION variables. With $Globals, I assume you cannot reach to that point, and you get the warning at this point: for ($a=1;$a<=$GLOBALS['rows'];$a++), because $GLOBALS are not declared the second time you reload the page by submitting the second form.
In fact, as W3Schools states, "$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script", while a "session is a way to store information (in variables) to be used across multiple pages." When you submit the pages for the second time, you are in fact refreshing the page, and here Globals are not a pick for you access your rows and columns. Instead you should use sessions to store your $_POST['rows'] and $_POST['columns'].
So, try the following instead. Start Session and then declare new $_Session variables for your $_POST['rows'] and $_POST['columns']. Then voila, the problem is solved.
IMPORTANT: add session_start(); at the top of your page. The very first line.
if (isset($_POST['generate'])) {
$username = $_POST['login'];
$password = $_POST['password'];
$hashed_username = sha1($username);
$hashed_password = sha1($password);
$correct_username = '9d6035e25958ec12fca7ec76d68c8daaf4815b9b'; //wims
$correct_password = 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3'; //test
if ($hashed_username != $correct_username)
die("Wrong user name!");
if ($hashed_password != $correct_password)
die("Wrong password!");
echo "How many rows and columns should the table have? <br />";
echo('
<form method="POST" target="">
Rows: <input type="number" name="rows" min="1" max="100"/><br/>
columns: <input type="number" name="columns" min="2" max="100"/><br/>
<input type="submit" name="generate1" value="Generate Table" />
</form>');
}
if (isset($_POST['generate1'])) {
$rows = $_POST['rows'] ?? '';
$columns = $_POST['columns'] ?? '';
$_SESSION['rows'] = $rows;
$_SESSION['columns'] = $columns;
global $rows, $columns;
if ($rows > 100 || $rows < 1)
die("Nope!");
if ($columns > 100 || $columns < 2)
die("Nope!");
echo '<form method="POST" target="">';
echo "<table>";
for ($a = 1; $a <= $rows; $a++) {
echo "<tr>";
for ($b = 0; $b <= $columns; $b++) {
if ($b == 0)
echo "<td>$a. Row</td>";
else {
$c = $a . $b;
echo "<td><input type='text' name='$c' /></td>";
}
}
echo "</tr>";
}
echo "</table>";
echo "<input type='submit' name='generate2' value='Generate' />";
echo "</form>";
}
if (isset($_POST['generate2'])) {
echo "<table>";
$row = $_SESSION['rows'] ?? '';
$columns = $_SESSION['columns'] ?? '';
for ($a = 1; $a <= $row; $a++) {
echo "<tr class='border: 1px solid #BDBDBD'>";
for ($b = 0; $b <= $columns; $b++) {
if ($b == 0)
echo "<td style='border: 1px solid #BDBDBD'>$a. row</td>";
else {
$c = $a . $b;
echo "<td style='border: 1px solid #BDBDBD'>$_POST[$c]</td>";
}
echo "</tr>";
}
echo "</table>";
}
session_destroy();
}
Your code here is the problem
if (!isset($_POST['generate1']))
die('');
Here you are checking if $_POST['generate1] is set, if it is not then die (halt/terminate execution of the script)
php die();
So when you submit your second form (submit has name of generate2) then the above check will fail (it is not set so it will die(); and end execution of your script.
if (isset($_POST['generate1'])) {
// Show the form....
}
Do this for both the generate1 and generate2 and it will only execute that code if the if statements evaluates to true.
instead using "if (!isset($_POST['generate1']))" change it into "if(isset($_POST['generate1']))".When you click generate2 it will be die because that condition is not fulfilled.
<!DOCTYPE html>
<html>
<body>
<form method="post" target="">
<label for="login">User: </label>
<input name="login">
<br />
<label for="password">Password: </label>
<input name="password" type="password">
<br />
<input type="submit" name="generate" value="Login" />
</form>
<?php
if (isset($_POST['generate'])) {
$username = $_POST['login'];
$password = $_POST['password'];
$hashed_username = sha1($username);
$hashed_password = sha1($password);
$correct_username = '9d6035e25958ec12fca7ec76d68c8daaf4815b9b'; //wims
$correct_password = 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3'; //test
if ($hashed_username != $correct_username)
die("Wrong user name!");
if ($hashed_password != $correct_password)
die("Wrong password!");
echo "How many rows and columns should the table have? <br />";
echo('
<form method="POST" target="">
Rows: <input type="number" name="rows" min="1" max="100"/><br/>
columns: <input type="number" name="columns" min="2" max="100"/><br/>
<input type="submit" name="generate1" value="Generate Table" />
</form>');
}
if (isset($_POST['generate1'])){
$rows = $_POST['rows'];
$columns = $_POST['columns'];
if ($rows > 100 || $rows < 1)
die("Nope!");
if ($columns > 100 || $columns < 2)
die("Nope!");
echo "<form method='POST' target=''>";
echo "<input type='hidden' name='row' value='$rows'/>";
echo "<input type='hidden' name='column' value='$columns'/>";
echo "<table>";
for ($a=1;$a<=$rows;$a++) {
echo "<tr>";
for ($b=0;$b<=$columns;$b++) {
if ($b==0)
echo "<td>$a. Row</td>";
else {
$c = $a . $b;
echo "<td><input type='text' name='$c' /></td>";
}
}
echo "</tr>";
}
echo "</table>";
echo "<input type='submit' name='a' value='Generate' />";
echo "</form>";
}
if (isset($_POST['a'])) {
$rows = $_POST['row'];
$columns = $_POST['column'];
echo "<table border='1'>";
for ($a=1;$a<=$rows;$a++) {
echo "<tr>";
for ($b=0;$b<=$columns;$b++) {
if ($b==0){
echo "<td>$a. row</td>";
}else {
$c = $a . $b;
echo "<td>$_POST[$c]</td>";
}
}
echo "</tr>";
}
echo "</table>";
}
?>
</body>
</html>
First
Your primary need is to READ THE MANUAL for all the things you're doing, thus you will see that the sha1() Manaul page states:
Warning
It is not recommended to use this function to secure passwords, due to the fast nature of this hashing algorithm.
You REALLY should be fixing this issue.
Anyway, your issue is:
Undefined index: rows on line 70
Which (I guess, because you didn't indicate in your question) is this line:
for ($a=1;$a<=$GLOBALS['rows'];$a++) {
This means that $GLOBALS key rows doesn't exist. Why? All PHP data is generated when a script is executed; before ANY script starts, the PHP knows NOTHING, there is never any incoming data at the start if the PHP script.
Some people here might shout and scream "SESSIONS!!" but even the $_SESSION array is empty at the start of the script, until the PHP code has read the stored session data in the cookie key.
So how do you populate $GLOBALS? What you did was not far off, but you ran the form and submitted the data to $_POST['generate1'] which worked, and this populated the data, but this presented a form to the end user so that user then had to resubmit the form, and by default that reloads the page, therefore restarting the PHP script from zero again, so all data in $GLOBALS is forgotten.
How do you make PHP "remember" data when loading a page? In general there are several ways; all of them have positive and negative sides:
Database. Read and write data to a third party
Sessions. Read and write data to a file/database associated with that specific client only.
Form data, reading data from a submitted form or via URL parameters (GET/POST).
Using (3) is probably easiest for you; so when you run the $_POST['generate1'] you need to add hidden inputs to your form so your "part 2" form can then pass on this data to "part3" form ($_POST['generate2']) .
And that's the data you need to read, not the GLOBALS.

Selection box insert multiple times in database

This is what the page looks like:
And this is what the database looks like:
Now, I had this all working with textfields. (When you press save, the text fields get inserted in the bogie_nr.
Now, I don't want to have text fields but checkboxes.
So, if I select the first 2 checkboxes, and press save. I want the database to insert the number 1 by the axle_nr 1 and 2.
Now, I want the first 2 boxes to be disabled (So you can't check them again).
Now when you select the 3rd and 4th box, and press save. I want the database to insert the number 2 by the 3rd and 4th axle_nr.
When everything is filled in, I want a button that redirects me to a new page.
How do I do this?
Code (for the checkboxes only):
<tr>
<?php
$show_axle = $database->bogies($_GET['train_id']);
foreach($show_axle as $bogiebox){ ?>
<input type='hidden' name='bogie_id[<?php echo $bogiebox['bogie_id']?>]' value='<?php echo $bogiebox['bogie_id']?>'>
<td>
<input type='checkbox' id="bogie_axle_fields" name='bogie_nr[<?php echo $bogiebox['bogie_id']?>]' placeholder = "enter bogie number">
</td>
<?php
}
?>
</tr>
Function:
function bogies($id){
$sql = "SELECT * FROM bogie WHERE train_id = :id2";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(":id2", $id, PDO::PARAM_STR);
$sth->execute();
return $sth->fetchAll();
}
EDIT:
Behind my save button is right now a page: end_result.php . Right there I have a function:
function update_bogie($id) {
$sql = "UPDATE bogie SET bogie_nr = :bogie_nr WHERE bogie_id = :bogie_id";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(':bogie_id', $id, PDO::PARAM_INT);
$sth->bindParam(":bogie_nr", $_POST['bogie_nr'][$id], PDO::PARAM_STR);
$sth->execute();
}
This updates the bogie table (Works when I change the checkboxes to textfields)
What i want now:
Checkboxes. When I check the first 2 boxes, and press save. I want the number 1 to be inserted 2 times for axle 1 and 2 in the database.
After that, I want the first 2 boxes to be disabled selected. So you can't select them once again.
EDIT:
What the ids look like:
THE ALMOST WORKING EDIT:
Okay, so the checkboxes now insert in the database. Also they are disabled when they are inserted in the database.Only a few problems now:
When i insert them for the first time. The value = 1. But on the
2nd insert it also is 1. while it should be 2.
I need to refresh the page in order to see wich select boxes are
disabled. I want this to happen immediately.
When i insert new values. the old (Disabled one) go back to NULL. But it should keep the old value.
Code i have now:
<form method='POST'>
<input type="hidden" value="true" id="y" name="y">
<div id="axle_bogie_border">
<div id="train_adjusted">
<h2>
Train
</h2>
</div>
<table id="distance_margin">
<div id="bogiebox">
<tr>
<?php
$x = 1;
foreach($show_axle as $bogiebox){ ?>
<input type='hidden' name='bogie_id[<?php echo $bogiebox['bogie_id']?>]' value='<?php echo $bogiebox['bogie_id']?>'>
<td>
<?php
if($bogiebox['bogie_nr'] == ''){
?>
<input type='checkbox' id="bogie_axle_fields" value="<?= $x ?>" name='bogie_nr[<?php echo $bogiebox['bogie_id']?>]' placeholder = "enter bogie number"></td>
<?php
}
else{
?>
<input type='checkbox' id="bogie_axle_fields" checked disabled value="<?= $x ?>" name='bogie_nr[<?php echo $bogiebox['bogie_id']?>]' placeholder = "enter bogie number"></td><?php } }
?>
</tr>
</div>
</table>
<input type='submit' id="add_train_button1" value='Save'>
<?php
if(isset($_POST['y'])){
$validbogies = false;
//validate
if(($_POST['bogie_id']) >0){
if($_POST['bogie_id'] >0){
$validbogies = true;
}elseif($_POST['bogie_id'] <= 0){
echo "Error!";
}
else{
echo "Error!." . "<br>";
}
}else{
echo "Error!" . "<br>";
}
//If valid, then insert.
if($validbogies){
foreach($_POST['bogie_id'] as $id) {
$update_axle = $database->update_bogie($id);
}
$x++;
unset($_POST['y']);
echo "Yea! Things have been moved to the database :)";
}
}
?>
</div>
</form>
And the function is still the same as the old one.
EDIT:
Here a example:
<?php
$show_axle = $database->bogies($_GET['train_id']);
// First question : When everything is filled in,
// i want a button that redirects me to a new page.
if(count($show_axle) == 4)
echo "<button type=\"button\" onClick=location.href=''>Click Me!</button>";
// Second question :
// WE display the missing checkboxes
// We will display until we found the first value axle_nr
// (i.e. the checkbox the user click last time)
// when we found we need to move to the next value of axle_nr
else
{
$j = 0;
for($i = 0; $i < 4; ++$i)
{
if($show_axle[$j]['axle_nr'] != ($i + 1))
{
echo "<input type='hidden' name='bogie_id[" .
$bogiebox['bogie_id']. "]' value='" .
$bogiebox['bogie_id'] . "'><td>";
echo "<input type='checkbox' id='bogie_axle_fields'
name='bogie_nr[" . $bogiebox['bogie_id'] .
"]' placeholder='enter bogie number'></td>";
}
else
++$j;
}
?>
That should do it (mb some mistakes on echo but algorithm is ok).
In the code behind your save button try this: (I am assuming the id's for your checkboxes are like this: bogie_nr[455]
function update_bogie($id) {
$sql = "UPDATE bogie SET bogie_nr = :bogie_nr WHERE bogie_id = :bogie_id";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(':bogie_id', $id, PDO::PARAM_INT);
if(isset($_POST['bogie_nr' . '[' . $id .']' ]){
$sth->bindParam(":bogie_nr", $_POST['bogie_nr' . '[' . $id .']' ], PDO::PARAM_STR);
}
else {
$sth->bindParam(":bogie_nr", 'NULL', PDO::PARAM_STR);
}
$sth->execute();
}
EDIT FOR CORRECT NUMBER:
Mitch to get your number try doing a query like this:
SELECT COUNT(*)
FROM bogie
WHERE train_id = #youridhere;
This will return you the amount of bogies you already have for that train, just do +1 or +2 depending on how many elements you are adding (use a counter in your for loop) and you have your correct number to insert

PHP While Loop logic

Can you Help me?? I am trying for some validation in my system, but I got stuck up on my ideas.
I created a text box that will looped when you enter any number. When the text box appear the user will have to fill up names, but if the user accidentally type a duplicated name the prompt message will appear saying: "Errors".
There is minor bug in my system and I want to fix it. I have think a lot of methods but this is the best fit to my system.
Here is the code:
<form action="fq1.php" method="post">
<input type="text" name="num" id="num">
<input type="submit" value="select" name="select" id="select" />
<?php include 'conectthis.php';
$num = $_POST['num'];
if(isset($_POST['select']))
{
$x = 0;
while($x <= $num)
{
$x++;
echo "<input type='text' name='txt".$x."' />";
}
echo "<input type='submit' name='save' id='save' value='Save'>";
}
if(isset($_POST['save']))
{
$y = 0;
while($y<=$num)
{
$y++;
$mypost1 = "txt". $y;
if($_POST[$mypost1] == $_POST[$mypost1])
{
$prompts = "<script>alert('Names was not saved, please ensure that there are no duplicated Names');</script>";
}
else
{
$runthis = "Update sampletable SET samplename = '$_POST[$mypost1]' WHERE id = '$y'";
mysql_query($runthis) or die(mysql_error());
}
}
echo $prompts;
}
?>
</form>
Now my problem is if($_POST[$mypost1] == $_POST[$mypost1]) the textbox will recognize it self and show the prompt message even there is no duplicated name(s).
It's a scratch from my code I think I know it is right.
Thank you in advance, I am new to this and still studying.

How to use MYSQL and two different Submit buttons?

I have created a song database (mysql) where a user can enter data into the textfield, select "by artist" or a "by title" radio button and click submit. This all works fine. :)
However, I would like to add another submit button that bypasses the above query and simply lists all of the songs that have been added to the database with a year's time.
I believe that the query I need is:
select * from dt_tb where `dt` >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)
but I cannot figure out how to code the PHP to run the query for the songs within the past year.
Here are the two forms I have:
<p>
<form name="form" method="get" action="">
Search for: <input type="text" name="q" />
<input type="radio" name="field" value="title" <?=$checkTitle?> checked> Title
<input type="radio" name="field" value="artist" <?=$checkArtist?> > Artist
<input type="submit" name="Submit" value="Search" />
</form></p>
<form name="form" method="post" action="">
<br />
<input type="submit" name="Newsongs" value="New Releases" />
</form></p>
and here is the current, working php for the 1st query:
<?php
$delimiter = "\t";
$newline = "\n";
$var = #$_GET['q'] ;
$field = #$_GET['field'];
$var = htmlentities($var);
$trimmed = trim($var); //trim whitespace from the stored variable
$search_words = explode(' ', $var);
if ($var != "") {
// rows to return
$limit=100;
// check for an empty string and display a message.
if ($trimmed == "")
{
echo "<p>Please enter a search...</p>";
exit;
}
// check for a search parameter
if (!isset($var))
{
echo "<p>We dont seem to have a search parameter!</p>";
exit;
}
//connect to your database
mysql_connect("DBLocation","DatabaseName","PASSWORD"); //(host, username, password)
//specify database
mysql_select_db("DatabaseName") or die("Unable to select database"); //select which database we're using
// Build SQL Query
$query = "SELECT * FROM Songs where $field like \"%$trimmed%\" order by $field ";
$numresults=mysql_query($query);
$numrows=mysql_num_rows($numresults);
// If we have no results, offer a google search as an alternative
if ($numrows == 0)
{
echo "<h4>Results</h4>";
echo "<p>Sorry, your search: "" . $trimmed . "" returned zero results</p>";
}
// next determine if s has been passed to script, if not use 0
if (empty($s)) {
$s=0;
}
// get results
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
// display what the person searched for
echo "<p>You searched for: "" . $var . ""</p>";
// begin to show results set
echo "<p style=\"color: #00ff00; font-size: 1.2em;\">Results</p>";
$count = 1 + $s ;
// now you can display the results returned
while ($row= mysql_fetch_array($result)) {
$title = $row["title"];
$artist = $row["artist"];
echo "$title";
echo " - ";
echo "$artist";
echo "<br />";
echo $newline;
$count++ ;
}
$currPage = (($s/$limit) + 1);
//break before paging
echo "<br />";
$a = $s + ($limit) ;
if ($a > $numrows) { $a = $numrows ; }
$b = $s + 1 ;
echo "<p>Showing results $b to $a of $numrows</p>";
}
?>
You can add a hidden field and then check it on submit:
<input type="hidden" name="act" id="act" value="">
Then on your second submit button, use JavaScript to change the value:
<input type="submit" name="Newsongs" value="New Releases" onclick="document.getElementById('act').value = 'list_all'" />
If the value is "list_all", process that, else do your current processing.
if ($_POST['act'] == 'list_all') {
// process second submit button code
} else {
// all your current code
}
You'll want to check if the NewSongs submit button was on the form submitted, and use that in an if statement to do the query or not.
<?php
if (!isset($_POST['NewSongs'])){
//do the search
} else {
//don't do the search
}
?>
You could use 2 submit button inside a form :
<p><form name="form" method="get" action="">
Search for: <input type="text" name="q" />
<input type="radio" name="field" value="title" <?=$checkTitle?> checked> Title
<input type="radio" name="field" value="artist" <?=$checkArtist?> > Artist
<input type="submit" name="submit" value="Search" />
<input type="submit" name="submit" value="New" />
</form>
</p>
<?php
if(isset($_GET['submit']) && $_GET['submit'] == 'Search'){
// do search
}
if(isset($_GET['submit']) && $_GET['submit'] == 'New'){
// do second search
}
?>

Passing array with values php

is it possible to pass through $_POST or $_GET an array, with values in it, without using serialize() and unserialize() ?
here is an example code, trying to find a number..i entered value 4 instead of rand, just to do the testing..
i thought of the potential of using a foreach to make multiple input hidden, in case i could pass all variables every single time, but it seems not to be working..
any ideas..??? or it is just not possible without serializing?
<?php
$x = $_POST['x'];
$Num = $_POST['Num'];
$first_name[] = $_POST['first_name'];
if (!$x)
{
Echo "Please Choose a Number 1-100 <p>";
$x = 4; //rand (1,4) ;
}
else {
if ($Num >$x)
{Echo "Your number, $Num, is too high. Please try again<p>";}
elseif ($Num == $x)
{Echo "Congratulations you have won!<p>";
Echo "To play again, please Choose a Number 1-100 <p>";
$x = 4;// rand (1,4) ;
}
else
{Echo "Your number, $Num, is too low. Please try again<p>";}
}
?>
<form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method = "post"> <p>
Your Guess:<input name="Num" />
<input type = "submit" name = "Guess"/> <p>
<input type = "hidden" name = "x" value=<?php echo $x ?>>
<?php
foreach($first_name as $val){
echo "<input type=\"hidden\" name=\"first_name[]\" value=$val />";
}
?>
</form>
</body>
</html>
<?php
foreach($first_name as $k => $val)
echo "<input type='hidden' name='first_name[$k]' value='$val' />";
should work.
here is the solution that i figured out...
$x = $_POST['x'];
$Num = $_POST['Num'];
$first_name = $_POST['first_name']; //creating array from the begining
$first_name[] = $Num; // add current num to next available slot in array
$counter = $_POST['counter'] +1;
if (!$x) // below this is the same..
....
....
<input type = "hidden" name = "x" value=<?php echo $x; ?>>
<input type = "hidden" name = "counter" value=<?php echo $counter; ?>> //add a counter to count loops
<?php
if ($counter>=2){ //counter in first load of page will be 1, so we need to read enter value from the next load of page
for ($i=0; $i<=($counter-2); $i++){ // counter-2 gives us the actual number of elements
echo "<input type=\"hidden\" name=\"first_name[]\" value=$first_name[$i] />";
}
}
?>
</form>

Categories