I've been learning some PHP and MySQL from a book that teaches you how create a simple database driven site. In the book's examples, we're creating a joke database that store author names, joke text, date and id. Progressing I've been taught how to use includes in my main controller, index.php. I'm stuck at a part where they tell me to create a search feature for the joke database, coding as follows:
This is the first part of the controller called 'index.php' all it does is display the search form.
// Display search form
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
include 'searchform.html.php'; //CHANGE 1
?>
The next part of the controller builds the SQL and then sends it to jokes.html.php, fairly simple... no problems here.
if (isset($_GET['action']) and $_GET['action'] == 'search')
{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
//Build SQL statement and output results into an array code here
}
include 'jokes.html.php'; //CHANGE 2
exit();
}
How would you modify the code above if the your searchform.html and jokes.html are just the single html file? I find it inconvenient using 2 files for searching.
My first attempt (I've merged searchform and jokes into "jokesearch.html.php") was to include 'jokesearch.html.php' in CHANGE 1 and again in CHANGE 2, however that didn't help... it just reloaded the page.
2nd attempt was to use header('Location: .')... no luck here too it just reloaded.
EDIT: By popular demand, I'll include the two html files.
searchform.html.php:
<?php include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/helpers.inc.php'; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Manage Jokes</title>
<meta http-equiv="content-type"
content="text/html; charset=utf-8"/>
</head>
<body>
<h1>Manage Jokes</h1>
<p>Add new joke</p>
<form action="" method="get">
<p>View jokes satisfying the following criteria:</p>
<div>
<label for="author">By author:</label>
<select name="author" id="author">
<option value="">Any author</option>
<?php foreach ($authors as $author): ?>
<option value="<?php htmlout($author['id']); ?>"><?php
htmlout($author['name']); ?></option>
<?php endforeach; ?>
</select>
</div>
<div>
<label for="category">By category:</label>
<select name="category" id="category">
<option value="">Any category</option>
<?php foreach ($categories as $category): ?>
<option value="<?php htmlout($category['id']); ?>"><?php
htmlout($category['name']); ?></option>
<?php endforeach; ?>
</select>
</div>
<div>
<label for="text">Containing text:</label>
<input type="text" name="text" id="text"/>
</div>
<div>
<input type="hidden" name="action" value="search"/>
<input type="submit" value="Search"/>
</div>
</form>
<p>Return to JMS home</p>
</body>
</html>
jokes.html.php
<?php include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/helpers.inc.php'; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Manage Jokes: Search Results</title>
<meta http-equiv="content-type"
content="text/html; charset=utf-8"/>
</head>
<body>
<h1>Search Results</h1>
<?php if (isset($jokes)): ?>
<table>
<tr><th>Joke Text</th><th>Options</th></tr>
<?php foreach ($jokes as $joke): ?>
<tr valign="top">
<td><?php htmlout($joke['text']); ?></td>
<td>
<form action="?" method="post">
<div>
<input type="hidden" name="id" value="<?php
htmlout($joke['id']); ?>"/>
<input type="submit" name="action" value="Edit"/>
<input type="submit" name="action" value="Delete"/>
</div>
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<p>New search</p>
<p>Return to JMS home</p>
</body>
</html>
From a MVC perspective your initial setup is the right way to go.
Your controller collects and processes data and sends it to views (your .html.php files).
It is good practice to separate defferent elements into different views. So a search box or search results go in a different view than the jokes.
Putting both logical different elements in one view file makes maintenance harder.
Regards,
Erwin Vrolijk
snow.nl
maybe something like this
if (isset($_GET['action']) and $_GET['action'] == 'search') {
// search result
} else {
// show search form
}
Related
My question maybe has been asked many times before but i couldn't apply the given solutions on my project yet
I'm trying to post only the selected children check-boxes not the parents
my page code is:
<?php $db = mysqli_connect('localhost', 'root', '123', 'test'); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="jquery.min.js"></script>
<script src="cbFamily.js"></script>
</head>
<body>
<form name="myform" method="post" action="test.php">
<section class="demo2" style="margin-top:2px;">
<?php
$query=mysqli_query($db,"SELECT * FROM tblmainjobs");
while ($row = mysqli_fetch_assoc($query)):
?>
<section>
<h3><label><input type="checkbox" /> <?php echo $row["mainjob"]; ?>
</label></h3>
<?php
$query2=mysqli_query($db,"SELECT userjob FROM users WHERE
'".$row["mainjob"]."' = users.mainjob GROUP BY users.userjob");
while ($row2 = mysqli_fetch_assoc($query2)):
?>
<div class="children">
<label><input type="checkbox" name="checkbox" value="<?php echo
$row2["userjob"]; ?>"/> <?php echo $row2["userjob"]; ?></label>
<?php endwhile; ?>
</section>
<?php endwhile; ?>
<script type="text/javascript"> <!-- this function for selecting all
children checkboxes once the parents checkbox bieng selected -->
$("h3 input:checkbox").cbFamily(function (){
return $(this).parents("h3").next().find("input:checkbox");
});
</script>
</section>
<br>
<div><input class="submit" type="submit" name="submit" value="submit"/>
</div>
</form>
</body>
</html>
my page looks like this
test.php
my entire project is attached here
https://www.sendspace.com/file/6ikcaa
Use array:
<input type="checkbox" name="checkbox[]" value="<?php echo
$row2["userjob"]; ?>"/> <?php echo $row2["userjob"]; ?>
notice the [] in the name attribute.
You could use javascript to disable the "parent" checkboxes before they get posted to the server.
Add a class to your parent checkboxes to make for an easy jquery selector:
<input type="checkbox" class="parent" />
Then some javascript to disable the checkboxes:
$(".parent").prop("disabled",true);
I'm trying to make a form that acts as a search engine and returns results. However, the data from the user's entry is either unable to save to a session or the session cannot be passed to another file. Here is the code for the "home" search page and the "Search-Engine" results page.
Home.php
<html lang="en-US">
<html>
<head>
</head>
<body>
<form action="Search-Engine.php" method="GET">
<input type="text" id="query" placeholder="I'm looking for..." onkeydown = "if (event.keyCode == 13) document.getElementById('searchbtn').click()">
<input type="submit" id="searchbtn" value="Search">
</form>
<?php session_register(); session_start(); ?>
<?php $_GET['query'] = $_SESSION['Query']; ?>
</body>
</html>
Search-Engine.php
<html lang="en-US">
<html>
<head>
</head>
<body>
<div class="results">
<?php session_start(); ?>
We could not find: <?php echo $_SESSION['Query']; ?>
</div>
</body>
</html>
I don't know the exact purpose of using Sessions in your form. But you are doing in a wrong way by starting Session in middle of page and using Sessions within the form. You can add value in Sessions in another page after submitting the form.
You can update your files in the below way:
Home.php
<html lang="en-US">
<html>
<head>
</head>
<body>
<form action="Search-Engine.php" method="GET">
<input type="text" name="query" id="query" placeholder="I'm looking for..." onkeydown = "if (event.keyCode == 13) document.getElementById('searchbtn').click()">
<input type="submit" id="searchbtn" value="Search">
</form>
</body>
</html>
Search-Engine.php
<?php session_start();
$_SESSION['Query'] = $_GET['query']; ?>
<html lang="en-US">
<html>
<head>
</head>
<body>
<div class="results">
We could not find: <?php echo $_SESSION['Query']; ?>
</div>
</body>
</html>
i create a combobox with sql values but how i know what the value selected?
this is my code, have a lot of scrap but is my tests :)
I link to send the selected option to another php file already created.
<?php
require_once('auth.php');
require_once('config.php');
require_once('no-cache-headers.php');
require_once('functions.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Nova Mensagem</title>
<link href="Formatacao.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Bem-vindo <?php echo $_SESSION['USERNAME'];?></h1>
<form id="regForm" name="regForm" method="post" action="verificarMensagem.php">
<table width="300" border="0" align="center" cellpadding="2" cellspacing="0">
<tr>
<?php
mysql_connect('localhost','comunicat','comunicat');
mysql_select_db('Comunicat');
$iduser =$_SESSION['SESS_MEMBER_ID'];
$query="Select * from Usuarios where id <> '$iduser'";
$resultado=mysql_query($query);
echo '<select name=”Nome”>';
while($linha=mysql_fetch_array($resultado))
{
echo '<option value="' . $linha['ID'] . '">' . $linha['Nome'] . '</option>';
}
echo '</select>';
?>
<textarea rows="4" cols="50" name="mensagem" id="mensagem">
</textarea>
<td> </td>
<td><input type="submit" name="Submit" value="Enviar" /></td>
</tr>
</table>
</form>
</body>
</html>
You can get value of select element in php by using $_POST[name-of-element]:
<?php
echo $_POST['Nome'];
?>
That works also with checkboxs,radios,etc
When the form that contains your "combobox" is submitted, you can get the selected value from your combobox with the line of code below:
$val = $_POST['Nome']; // if the form was submitted using post method
$val = $_GET['Nome']; // if the form was submitted using get method
NB
Do not use mysql_* no more, it is officially deprecated. Use mysqli or PDO instead.
I have two pages: order.php and checkout.php. I have 3 items in the order page and I want to pass quantity of the items to the checkout page.
I guess the problem is with isset($_POST['Submit']). My guess is that it still goes straight to the checkout page when I press submit without putting values to session variables.
I have been trying to pass the values from order like this:
<?php echo '<?xml version="1.0" encoding="iso-8859-15"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">';
session_start();
?>
<html>
<head>
<title>Lomake-esimerkki</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-15" />
</head>
<body>
<?php
error_reporting(E_ALL); // raportoidaan virheet
ini_set('display_errors','On'); // näytetään ne myös
echo <<<END
<form action="checkout.php"
method="post">
<p>Gaming Computer - 5 e/kpl <label>How many? <input type="text" name="maara1" /></label></p>
<p>Frigge - 10 e/kpl <label>How many? <input type="text" name="maara2" /></label></p>
<p>IKEA-table - 15 e/kpl <label>How many? <input type="text" name="maara3" /></label></p>
<p><input type="submit" name="submit" value="Order"/></p>
<input type=hidden name=price1 value=5>
<input type=hidden name=price2 value=10>
<input type=hidden name=price3 value=15>
</form>
<hr />
END;
if (isset($_POST['Submit'])) {
$_SESSION["maara1"] = $_POST["maara1"];
$_SESSION["maara2"] = $_POST["maara2"];
$_SESSION["maara3"] = $_POST["maara3"];
}
?>
</body>
</html>
And here in checkout I'm trying to print one session value as test:
<?php echo '<?xml version="1.0" encoding="iso-8859-15"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">';
session_start();
?>
<html>
<head>
<title>Lomake-esimerkki</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-15" />
</head>
<body>
<?php
error_reporting(E_ALL); // raportoidaan virheet
ini_set('display_errors','On'); // näytetään ne myös
print ($_SESSION["maara1"]);
?>
</body>
</html>
"I guess the problem is with isset($_POST['Submit'])."
Yes, the problem is with if (isset($_POST['Submit']))
Your submit button is named submit instead of Submit.
<input type="submit" name="submit" value="Order"/>
Change it to
<input type="submit" name="Submit" value="Order"/>
They are case-sensitive.
Or leave it the way it is and change
if (isset($_POST['Submit']))
to
if (isset($_POST['submit']))
Either method will work. You just need to make them both (letter cases) match.
What is happening is, PHP is looking for a named element called Submit.
That alone would have and should have thrown:
Undefined index Submit...
Sidenote:
I noticed:
<input type=hidden name=price1 value=5>
and other inputs.
I would suggest that you use quotes around it:
<input type="hidden" name="price1" value="5">
while doing the same for the others, as it could have adverse effects and/or unexpected results.
I have seen that happen before.
Edit:
You'll need to move this whole block in your second page and not be in the first page.
if (isset($_POST['Submit'])) {
$_SESSION["maara1"] = $_POST["maara1"];
$_SESSION["maara2"] = $_POST["maara2"];
$_SESSION["maara3"] = $_POST["maara3"];
}
then do print ($_SESSION["maara1"]); from there.
Your first page does not recognize the POST variables because they have not been set.
Edit #2:
You could try setting a value value="{$_SESSION["maara1"]}" to your inputs.
I.e.:
Sidenote: You could try <form action="" method="post"> instead of <form action="checkout.php" method="post">
However, I'm unsure if the following is what you're looking to get. It does work if action="" but it won't work trying to get a value before it has been set. That's not how sessions work.
It's kind of like expecting an A+ in a test you haven't written yet, if I can say.
echo <<<END
<form action="checkout.php" method="post">
<p>Gaming Computer - 5 e/kpl <label>How many? <input type="text" name="maara1" value="{$_SESSION["maara1"]}" /></label></p>
<p>Frigge - 10 e/kpl <label>How many? <input type="text" name="maara2" /></label></p>
<p>IKEA-table - 15 e/kpl <label>How many? <input type="text" name="maara3" /></label></p>
<p><input type="submit" name="Submit" value="Order"/></p>
<input type=hidden name=price1 value=5>
<input type=hidden name=price2 value=10>
<input type=hidden name=price3 value=15>
</form>
<hr />
END;
if (isset($_POST['Submit'])){
$_SESSION["maara1"] = $_POST["maara1"];
$mar1 = $_SESSION["maara1"];
echo $mar1;
}
But as you said in a comment: "what is the point of me using session variables on second page then if I can refer them from $_POST anyways?"
A: Exactly.
I went and did it like this. With two button and it is also more close to webstore now. So I press first button to add the quantity of the items and at the same time it sets session variables. Then I press second button to proceed to the second page which is checkout. What you guys think?
First page:
<?php echo '<?xml version="1.0" encoding="iso-8859-15"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">';
session_start();
?>
<html>
<head>
<title>Lomake-esimerkki</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-15" />
</head>
<body>
<?php
error_reporting(E_ALL); // raportoidaan virheet
ini_set('display_errors','On'); // näytetään ne myös
echo <<<END
<form action="teht7.php"
method="post">
<p>Gaming Computer - 5 e/kpl <label>How many? <input type="text" name="maara1" /></label></p>
<p>Fridge - 10 e/kpl <label>How many? <input type="text" name="maara2" /></label></p>
<p>IKEA-table - 15 e/kpl <label>How many? <input type="text" name="maara3" /></label></p>
<p><input type="submit" name="submit" value="Valitse tuotteet"/></p>
</form>
<hr />
<form action="teht7_kassa.php"
method="post">
<p><input type="submit" name="submit" value="Siirry kasssalle"/></p>
<input type=hidden name=price1 value=5>
<input type=hidden name=price2 value=10>
<input type=hidden name=price3 value=15>
</form>
<hr />
END;
if (isset($_POST['submit'])) {
$ostostenmaara = $_POST["maara1"] + $_POST["maara2"] + $_POST["maara3"];
print ("Ostoskorissa on: $ostostenmaara tuotetta");
$_SESSION["maara1"] = $_POST["maara1"];
$_SESSION["maara2"] = $_POST["maara2"];
$_SESSION["maara3"] = $_POST["maara3"];
}
?>
</body>
</html>
Second page:
<?php echo '<?xml version="1.0" encoding="iso-8859-15"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">';
session_start();
?>
<html>
<head>
<title>Lomake-esimerkki</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-15" />
</head>
<body>
<?php
error_reporting(E_ALL); // raportoidaan virheet
ini_set('display_errors','On'); // näytetään ne myös
$maara1 = $_SESSION["maara1"];
$maara2 = $_SESSION["maara2"];
$maara3 = $_SESSION["maara3"];
$summa = $_POST["price1"]*$maara1+$_POST["price2"]*$maara2+$_POST["price3"]*$maara3;
print ("Ostostesi yhteissumma on: $summa euroa");
?>
</body>
</html>
I have a drop down box that contains a list of names and a search field.
The drop down is populated with a list of names from the database and the search field allows you to perform a wild card search.
At the moment the wild card search works as expected but choosing a name from the drop down does not work.
I believe this might be possibly because of some unwanted characters as I am seeing the below in my address bar on the browser having chosen a name from the drop down list and clicked the search button:
http://localhost:81/connect/players/?name=%0D%0A3&text=&action=search
I think that text above (%0D%0A) is causing a problem as my code looks like this:
if (isset($_GET['action']) and $_GET['action'] == 'search')
{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
$id = $_GET['name']; // name slightly confusing but does return the id
$text = $_GET['text'];
try
{
$sql = "SELECT id, name, age FROM player
WHERE player.id = '$id'
OR player.name LIKE '%$text%'
GROUP BY player.id";
$s = $pdo->query($sql);
}
catch (PDOException $e)
{
$error = 'Error fetching names.' . $e->getMessage();;
include 'error.html.php';
exit();
}
// This is responsible for populating the new player info underneath all
foreach ($s as $row)
{
$names[] = array('id' => $row['id'], 'name' => $row['name'], 'age' => $row['age']);
}
include 'searchprofiles.html.php';
exit();
}
And I believe this is preventing it from comparing the id in the database with the id that is stored in the variable $id.
I have however also just manually stripped %0D%0A out from the address bar and it still doesn't work so perhaps there might be another issue?
It should also be noted that if no value is selected from the drop down and no wild card is entered then all rows are returned.
HTML is as follows:
SEARCHPROFILES.HTML.PHP
<?php include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/helpers.inc.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Manage Jokes: Search Results</title>
</head>
<body>
<h1>Search Results</h1>
<?php if (isset($names)): ?>
<table>
<tr><th>Name</th><th>Options</th></tr>
<?php foreach ($names as $name): ?>
<tr>
<td><?php htmlout($name['name']); ?></td>
<td><?php htmlout($name['age']); ?></td>
<td>
<form action="?" method="post">
<div>
<input type="" name="id" value="<?php
htmlout($name['id']); ?>">
<input type="submit" name="action" value="Edit">
<input type="submit" name="action" value="Delete">
</div>
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<p>New search</p>
<p>Return to JMS home</p>
</body>
</html>
BELOW IS THE HTML FOR THE FORM WHERE THE VALUES ARE ADDED.
<?php include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/helpers.inc.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Manage Profiles</title>
</head>
<body>
<h1>Manage Profile</h1>
<p>Add new profile</p>
<form action="" method="get">
<p>View player profiles satisfying the following criteria:</p>
<div>
<label for="name">By name:</label>
<select name="name" id="name">
<option value="">Any name</option>
<!-- populates the drop down with names -->
<?php foreach ($names as $name): ?>
<option value="
<?php htmlout($name['id']); ?>">
<?php htmlout($name['name']); ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div>
<label for="text">Containing text:</label>
<input type="text" name="text" id="text">
</div>
<div>
<input type="hidden" name="action" value="search">
<input type="submit" value="Search">
</div>
</form>
</body>
</html>
Any help is greatly appreciated.
Thanks
The reason is the line break you have in your form control:
Change
<option value="
<?php htmlout($name['id']); ?>">
<?php htmlout($name['name']); ?>
</option>
To
<option value="<?php htmlout($name['id']); ?>">
<?php htmlout($name['name']); ?>
</option>