Search wont show on same page - php

I have three files; index.php, searchbar.php and search.php
now when i have search.php show its results on its own page its fine but when i try to include the search page in index.php i get nothing.
so i include the searchbox.php in index.php so i have a search bar, i then search for something and include the search.php page by using the $_GET['p'] on the index.php but the search always come up blank, if i just leave search.php as its own page and dont try to include it then i get my results but id like for them to be included on the page they were searched from.
index.php
<?php
if (isset($_GET['p']) && $_GET['p'] != "") {
$p = $_GET['p'];
if (file_exists('include/'.$p.'.php')) {
#include ('include/'.$p.'.php');
} elseif (!file_exists('include/'.$p.'.php')) {
echo 'Page you are requesting doesn´t exist<br><br>';
}
} else {
#include ('news.php');
}
?>
searchbox.php
<div id="searchwrapper"><form action="?p=search" method="get">
<input type="text" class="searchbox" name="query" value="" id="query"/>
<input type="image" src="search.png" class="searchbox_submit" value="" ALT="Submit Form" id="submit"/>
</form>
</div>
search.php
<?php
include 'connect.php';
$searchTerms = $_GET['query'];
$query = mysql_query("SELECT * FROM misc WHERE itemname LIKE '%$searchTerms%' ORDER BY itemname ");
{
echo "<table border='1' cellpadding='2' cellspacing='0' width=608 id='misc' class='tablesorter'><thead>";
echo "<tr> <th> </th> <th>Item Name</th> <th>Desc.</th></tr></thead><tbody>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $query )) {
// Print out the contents of each row into a table
echo "<tr><td width=50>";
echo $row['image'];
echo "</td><td width=150>";
echo $row['itemname'];
echo "</td><td width=250>";
echo $row['desc'];
echo "</td></tr>";
}
echo "</tbody></table>";;
}
if (mysql_num_rows($query) == 0)
{
echo 'No Results';
}
?>

When I reproduced your code, the "p=search" wasn't carrying over. The better way to set it up is to have the action just go to your index.php file and have a hidden input with:
<input type="hidden" name="p" value="search" />
That will work properly for you!

A blank page almost always means you have whitespace after your closing ?>. Remove the closing ?> in index.php and search.php - this will force the preprocessor to dynamically determine EOF, which is exactly what you want (and what nearly every PHP framework/company includes within their coding standards).

Related

Show single listing from Search - PHP SQL

Hopefully the last question as I am not 100% sure how to solve this one.
I did see a similar question , but it does not really reflect my question and the other question is quite difficult to follow , so please see this as a original question and not a duplicate..
So on my website someone carried out a search from a search bar using the 'POST' method , teh search results show all whiskies in the databse. I have a number of whiskies with the same name but with different dates and prices. I would like it just to show one of each type that was searched for rather than all of them. I have attahced a clip of the databse. Really appreciate the help
Thanks
Index.php
</head>
<?php
$page='index';
include('header.php');
include('navbar.php');
?>
<script type="text/javascript">
function active(){
var search_bar= document.getElementById('search_bar');
if(search_bar.value == 'Search for your whisky here'){
search_bar.value=''
search_bar.placeholder= 'Search for your whisky here'
}
}
function inactive(){
var search_bar= document.getElementById('search_bar');
if(search_bar.value == ''){
search_bar.value='Search for your whisky here'
search_bar.placeholder= ''
}
}
</script>
<body>
<div class="third_bar">
<div class="background_image">
</div>
<div class="form"><form action= "search.php" method="post">
<input type="text" name="search" id="search_bar" placeholder="" value="Search for your whisky here" max length="30" autocomplete="off" onMouseDown="active();" onBlur="inactive();"/><input type="submit" id="search_button" value="Go!"/>
</form>
</div> </div>
</body>
</div>
<?php include ('footer.php');
?>
Search.php
<?php
$page='search';
include('header.php');
include ('navbar.php');
echo "<br>";
include ('connect.php');
if (isset ($_POST['search'])) { //the 'search' refers to the 'search' name=search on the index page and makes does something when the search is pushed.
$search = $_POST['search'];
$search = "%" . $search . "%"; // MySQL wildcard % either side of search to get partially matching results
// No wildcard if you want results to match fully
} else {
header ('location: index.php');
}
$stmt = $conn->prepare("SELECT * FROM test_db WHERE name LIKE :name ORDER BY name ASC"); // Use = instead of LIKE for full matching
$stmt->bindParam(':name', $search);
$stmt->execute();
$count = $stmt->rowCount(); // Added to count no. of results returned
if ($count >= 1) { // Only displays results if $count is 1 or more
echo "<div class='results_found'>";
echo $count;
echo " results found<br>";
echo "</div>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<div class='results'>";
echo "<div class='result_name'>";
echo "<b>Whisky Name:</b><br>";
echo "<a href='details1.php?id={$row['lot_id']}' >{$row['name']}</a>";
echo"<br>";
echo "</div>";
echo "</div>";
}
} else {
echo " Sorry no records were found";
}
?>
</htm

PHP/MySQL "Quiz" Game - Form Input Value

Alright, so I've been working on this for two days now - my code is somewhat sloppy & jumbled but I've gone over hundreds of questions, websites, etc. etc. looking for an answer or simply an explanation I understood; unfortunately, I still have been unsuccessful in my attempts.
I am build a "Quiz" Game in PHP/HTML - the website references a database, specifically, a tabled labeled "answers" which holds the following information:
- ID: Auto-Increment
- Question: Varchar
- Answer: Varchar
- Comment: Varchar
Now, for a little information on the site - Once a user logs in, he/she can "play" the game; the game is simply an HTML form, which above it displays a random "answers table" question. The form has 4 user inputs but only requires two. Let me get into the code details and then I will ask my question:
My index.php page (which contains the game form) is currently:
<?php # index.php
session_start();
//check session first
if (!isset($_SESSION['email'])){
include ('../includes/header.php');
}else
{
session_start();
include ('../includes/header.php');
require_once ('../../mysql_connect.php');
$query = "SELECT * FROM answers ORDER BY RAND() LIMIT 1";
$result = #mysql_query ($query);
$num = mysql_num_rows($result);
if ($num > 0) { // If it ran OK, display all the records.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<div class="newGame">
<h2>Are you a Question Master?<hr /></h2>
<h3 style="color:#000">Find Out Now!</h3>
</div>
<br />
<div class="newGameContain">
<form action="gameSubmit.php" method="post" autocomplete="off">
<h2><? echo $row["Question"]."<hr />"; ?></h2>
<h3>Enter Player Answers</h3>
<p><input type="text" placeholder="Player 1" name="player1" value="<? echo $_POST['player1']; ?>" /> <input type="text" placeholder="Player 2" name="player2" value="<? echo $_POST['player2']; ?>" /></p>
<p><input type="text" placeholder="Player 3" name="player3" value="<? echo $_POST['player3']; ?>" /> <input type="text" placeholder="Player 4" name="player4" value="<? echo $_POST['player4']; ?>" /></p>
<p><input type="submit" class="submitButton" /> <input type="reset" class="resetButton" value="Reset" /> </p>
<input type="hidden" name="ID" value="<?php echo $row["ID"]; ?>" />
<input type="hidden" name"Answer" value="<?php echo $row['Answer']; ?>" />
<input type="hidden" name="submitted" value="TRUE" />
</form>
<p></p>
</div>
<br />
<?php
} //end while statement
} //end if statement
mysql_close();
//include the footer
include ("../includes/footer.php");
}
?>
Then my gameSubmit.php page (form action) looks like this - I will only give a snapshot, not the whole thing:
<?php # index.php
session_start();
//check session first
if (!isset($_SESSION['email'])){
include ('../includes/header.php');
}else
{
session_start();
include ('../includes/header.php');
require_once ('../../mysql_connect.php');
$query = "SELECT * FROM answers ORDER BY RAND() LIMIT 1";
$result = #mysql_query ($query);
$num = mysql_num_rows($result);
if ($num > 0) { // If it ran OK, display all the records.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<? if (isset($_POST['submitted'])){
$correct1Msg = "<div class='correct1Msg'><p style='color:#000;font-family:Arial, Helvetica, sans-serif;'>Player 1 entered the <span id='answerUnder'>correct answer</span>.</p></div><p></p>";
$correct2Msg = "<div class='correct2Msg'><p style='color:#000;font-family:Arial, Helvetica, sans-serif;'>Player 2 entered the <span id='answerUnder'>correct answer</span>.</p></div><p></p>";
$incorrect1Msg = "<div class='incorrect1Msg'><p style='color:#F00;font-family:Arial, Helvetica, sans-serif;'>Player 1 entered the <span id='answerUnder'>incorrect answer</span>.</p></div><p></p>";
$incorrect2Msg = "<div class='incorrect2Msg'><p style='color:#F00;font-family:Arial, Helvetica, sans-serif;'>Player 2 entered the <span id='answerUnder'>incorrect answer</span>.</p></div><p></p>";
$player1Answer = $_POST['player1'];
$player2Answer = $_POST['player2'];
$player3Answer = $_POST['player3'];
$player4Answer = $_POST['player4'];
$questionID = $row['ID'];
if ($questionID == "1" && $player1Answer != "Red"){
echo $incorrect1Msg;
}elseif ($questionID == "2" && $player1Answer != "4"){
echo $incorrect1Msg;
}else {
echo $correct1Msg;
}
if ($questionID == "1" && $player2Answer == "Red"){
echo $correct2Msg;
}elseif ($questionID == "2" && $player2Answer == "4"){
echo $correct2Msg;
}else{
echo $incorrect2Msg;
}
}
?>
<?php
} //end while statement
} //end if statement
mysql_close();
//include the footer
include ("../includes/footer.php");
}
?>
As a note, the gameSubmit.php page also has identical message and if...elseif... statements for player3Answer & player4Answer.
So my question is...
If a user is logged in and opens the index.php page, he/she is prompted with the "echo $row ["Question"]" (which is a question pulled from the MySQL database using $query = "SELECT * FROM answers ORDER BY RAND() LIMIT 1"; - The user then proceeds to enter an answer in each player's respective text input. Once the user clicks the submit button, the form redirects to gameSubmit.php - once loaded, if(isset($_POST['submitted'])){ launches and cross checks each users answer and displays the respective message.
Currently, my form redirects to gameSubmit.php, however, it doesn't reference the previous question for the correct answer - thus its sheer luck the identical answer appears when "grading" the answers.
What do I need to do/what needs to be corrected in order to achieve input validation on the form action page?
Once again, I simply want to retrieve a question at random and on submit check the inputted answers with the correct answer - I would also like my code to be able to retrieve the correct answer rather than me having to type out each answer, so that way, if a record gets added, I dont have to update the code.
Thank for your time and the help, it is much appreciated! (It's finals week and I couldn't be more stressed)
Rockmandew
Just pass a POST element from index page to gameSubmit.php with the question id.
Add a hidden element in index page like..
<input type="hidden" name="questionId" value="<?php echo $row['id']; ?>">
So, You can get the question id in pageSubmit.php using $_POST['questionId']

Printing session variable content in PHP

Hi I have the following as my login script. (The script is not yet sanitized.) But I have an issue here. Once a successful log in attempt is made I need to echo the loggedUser but the information doen't get printed once echoed. Can someone pls help me understand where I have gone wrong?
Code as follows;
<?php
SESSION_start();
?>
<!doctype html>
<html>
<head></head>
<body>
<div>
<?php
include ("connect_db/index.php");
if(isset($_SESSION['loggedUser']))
{
echo '<div>User :'.$_SESSION['loggedUser'].'</div>';
}
else
{
echo "
<div id='u2'>
<form name='form1' method='post' action='''>
<table border='1'>
<tr>
<td>User Name: </td>
<td><label for='textfield'></label>
<input type='text' name='UnameZoom' id='UnameZoom' class='txss'></td>
<td> Password: </td>
<td><label for='txss'></label>
<input type='password' name='PwordZoom' id='PwordZoom' class='txss'></td>
<td> <input type='submit' name='loggedUser' id='loggedUser' class='mylog' value='Login'></td>
</tr>
</table>
</form>
<p> </p>
<p> </p>
</div>";
if(isset($_POST['loggedUser']))
{
$un = $_POST['UnameZoom'];
$pw = $_POST['PwordZoom'];
if($un=='' || $pw == '')
{echo "Empty fields"; return;}
$SQLSz = "SELECT pword FROM users WHERE username='$un'";
$rVz = mysqli_query($db,$SQLSz) or die ("SQL Error!!!");
$roVz = mysqli_fetch_array($rVz);
if($pw == $roVz['pword'])
{
$result = mysqli_query($db,"SELECT Lname AS Lna FROM users WHERE username='$un'");
$row11 = mysqli_fetch_assoc($result);
$sum = $row11['Lna'];
$_SESSION['loggedUser'] = $sum;
echo $_SESSION['loggedUser'];
}
else
{
echo "No user found";
}
}
}
?>
<div></body></html>
I think problem is in your variable. It can be array but u cant echo array. try dump your variable with var_dump.
As already mentioned - SESSION_start() shall be session_start()
Try another statement for displaying your SESSION array - for example:
echo '<pre>';
print_r($_SESSION);
echo '</pre'>;
This will show you all session keys in a nice and readable way

From index.php to detail.php

i have a troubles with my code.
I have html table in index.php (php, mysql)..this:
<?php
require ('../../inc/config.inc.php');
require ('../../inc/ini.php');
mysql_set_charset('utf8');
$sql = "SELECT * FROM {$cfg['tbl_dily']}";
$result = mysql_query($sql)or die(mysql_error());
echo "<table class=\"vypis\">";
echo "<h1 id=\"vypis\">Nabídka náhradních dílů</h1>\n";
$i = 0; //defaultní hodnota pro obarvení řádku
//start cyklu pro výpis z tbl_dily
while ($row = mysql_fetch_array($result)){
//přístup ke sloupcum tbl_dily
$part_id =$row['part_id'];
$img150 =$row['img150'];
$nazevdilu =$row['nazev'];
$vyrobce =$row['vyrobce'];
$model =$row['model'];
$cena =$row['cena'];
//start --- coloring every 2nd row of table
$i=1-$i;
$trclass="radek".$i;
//end --- coloring every 2nd row of table
echo "<tr class=\"".$trclass."\">\n";
if($img150 == null){ // podmínka pro existenci fotografie produktu
echo "<td class=\"img150\"> <img class=\"obrazek\" src=\"fotoneni.gif\"/> </td>\n";
}
else {
echo "<td class=\"img150\"> <img class=\"obrazek\" src=\"".$img150."\"/> </td>\n";
}
echo "<td class=\"nazevdilu\">".$nazevdilu."</td>\n";
echo "<td class=\"modely\">".$vyrobce." ".$model."</td>\n";
if($cena == 0){ //podmínka pro existenci přesné ceny produktu nebo "dohodou"
echo "<td class=\"cena\">dohodou</td>\n";
}
else{
echo "<td class=\"cena\">".$cena." Kč"."</td>\n";
}
echo "</tr>\n";
}
//konec cyklu pro výpis z tbl_dily
echo "</table>\n";
?>
So I have linked out part_id with no problems. Problems shows when I want to see detail of some product. My detail.php looks like this now:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="cs" lang="cs">
<head>
<?php
require ('../../inc/config.inc.php');
require ('../../inc/ini.php');
mysql_set_charset('utf8');
$part_id=$_GET['part_id'];
$data = mysql_query("SELECT * FROM {$cfg['tbl_dily']} WHERE part_id='$part_id'") or die(mysql_error());
while ($detail = mysql_fetch_array($data)){
$id =$detail['part_id'];
}
?>
<title><?php $id; ?></title>
</head>
<body>
<div class="detail">
<span id="detail_id">Výpis nabídky id <?php $id; ?></span>
<div class="detail_foto">
</div>
<div class="detail_info">
</div>
</div>
</body>
</html>
I need to help at least with getting part_id number in page title of detail.php. I dont understand so much how $_GET works..I hope you somebody show me how-to..
THANKS for helping me out:))
Your explanation is not terribly nice. You should maybe edit the Question and explain where the problem is at. But for now, let me just explain '$_GET'
'$_GET' is a way to deliver Data from one PHP Script to another. You can find them in almost every Formular. As you can see in the Code below, there is a simple way that sends Data to an "action.php" - the attribute "method" is for telling the formular what you want to do. You should maybe take a look at both options because GET displays the data you want to deliver in the link. Your user could start manipulating that which would be a very unsafe thing in your case because you work with mysql-Databases. Also you should take a look at Mysql String escaping.
Back to the topic: The HTML below would redirect $_GET['name'] AND $_GET['age'] to the action.php where you can work with those.
<form action="action.php" method="get">
<p>Your ame: <input type="text" name="name" /></p>
<p>Your age: <input type="text" name="age" /></p>
<p><input type="submit" /></p>
</form>

View/Edit/Delete in PHP

I got a system where users have to register and login to my website to add recipes in which the non-registered users and obviously registered users can view from the front end.
What I have done so far is, I have done the registration page, login page, and an 'my account' page for users to login and submit recipes. Everything works but now I am trying to add another functionality in my system whereby users can edit/delete their own recipes. The way I've done the login is by creating a session which holds the username rather then outputting it in the url like so: www.cooking.com/my-account.php?user_id=26.
I want the same sort of thing but this time I want the recipes to be stored in a session rather then the recipe id being shown on the url. I am clueless in how to do this. I have a 'starters' table in mysql with the following fields:
username ()
recipename
ingredients
method
time
id
Once you login and want to edit/delete the recipes you have uploaded, there is a table shown which contains all the recipes you uploaded. What i want is for the user to click on any recipe and it shall take the user to another page where it allows the user to edit their stuff.
I have tried this but with no success. The following are the codes I have used with the error displaying once clicked on edit:
EDIT STARTERS PAGE (editstarters.php)
<?php
session_start();
require_once '../database.php';
if (isset($_SESSION['myusername'])){
echo "Welcome ". $_SESSION['myusername'];
}
?>
<br /><br />You have uploaded the following starters:
<br /><BR />
<?php
include '../database.php';
$userid = $_SESSION["myusername"];
$result = mysql_query("SELECT * FROM starters WHERE username = '". $_SESSION['myusername']."' ");
echo "<table border='1'><table border width=65%><tr><th>Recipie Name</th><th>Ingredients</th><th>Method</th><th>Time</th></tr>";
while($getrecipie = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $recipiename = $getrecipie['recipename']. "</td>";
echo "<td>" . $ingredients = $getrecipie['ingredients']. "</td>";
echo "<td>" . $method = $getrecipie['method']. "</td>";
echo "<td>" . $time = $getrecipie['time']. 'minutes'."</td>";
?>
<td><a href = "startersedited.php?rec=<?php echo $getrecipie['id'] ?>" >Edit</a></td>
<td><a href = "DELETE1.php?rec=<?php echo $getrecipie['Recipie_ID'] ?>&id=<?php echo $user_id?>" >Delete</a></td>
<!--using the stu_id value in the URL to select the correct data when wego to the relevant pages -->
<?php
}
echo "</tr>";
echo "</table>";
?>
STARTERS EDITED PAGE (startersedited.php)
<?php
session_start();
require_once '../database.php';
if (isset($_SESSION['myusername'])){
echo "Welcome ". $_SESSION['myusername'];
}
?>
<br /><br />EDIT/DELETE YOUR STARTERS
<br /><BR />
<?php
include '../database.php';
$userid = $_SESSION["myusername"];
$result = mysql_query("SELECT * FROM starters WHERE username = '". $_SESSION['myusername']."' AND recipie_id='{$_GET['rec']}'");
$getrecipie = mysql_fetch_array($result);
$recipie = $getrecipie['recipename'];
$ingredients = $getrecipie['ingredients'];
$method = $getrecipie['method'];
$time = $getrecipie['time'];
?>
<h1>Edit Recipies</h1>
<p> </p>
<form name="form1" method="post" action="startereditsuccess.php?rec=<?php echo $_GET['id']?>">
<table width="609" height="250" border="0">
<tr>
<td width="155">Recipie Name</td>
<td width="347"><label for="recipiename"></label> <input type="text" name="recipename" value="<? echo $recipe ?>" id="recipename" >
</td>
</tr>
<tr>
<td>Ingredients</td>
<td><label for="ingredients"></label> <textarea name="ingredients" cols="50" rows="5" id="ingredients"><? echo $ingredients ?></textarea></td>
</tr>
<tr>
<td>Method</td>
<td><label for="method"></label> <textarea name="method" cols="50" rows="5" id="method"><? echo $method ?></textarea></td>
</tr>
<tr>
<td>Time</td>
<td><label for="time"></label> <input type="text" name="time" value="<? echo $time ?>" id="time"></td>
</tr>
</table>
<p>
<input type="submit" name="update" id="update" value="Update">
</p>
</form>
This is the error I get:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/jahedhus/public_html/cook/editdelete/startersedited.php on line 55
Please help me, I am LOST!
First off, don't shout in your posting titles. It's not necessary.
Second, we don't need a wall of code showing everything, when the actual only relevant bit is your error message. That particular error message means that your query has failed (probably due to a syntax error), which means mysql_query() has returned its usual boolean FALSE, and you didn't check for that. You used this false as a statement handle and tried to fetch a row from it, which has caused the actual error message.
As a general rule, NEVER assume that a database query succeeds. Even if the query string itself is 100% syntactically valid, there's many many other reasons that can cause it to fail.
Your basic MySQL query code structure should be:
$sql = "...";
$result = mysql_query($sql) or die(mysql_error());
This is good for debugging/development: if a query fails, it'll halt the script immediately and tell you why. For production code, you'd want something a bit more robust, rather than sending a long SQL error message to your users.
Your call to mysql_query() in startersedited.php at this line:
$result = mysql_query("SELECT * FROM starters WHERE username = '". $_SESSION['myusername']."' AND recipie_id='{$_GET['rec']}'");
is returning boolean FALSE, because an error has occurred. You should add some error handling code to deal with this whenever you call mysql_query(), for example:
$result = mysql_query("SELECT * FROM starters WHERE username = '". $_SESSION['myusername']."' AND recipie_id='{$_GET['rec']}'");
if($result === FALSE) {
echo "Database Error: ".mysql_error() ;
exit ;
}
$getrecipie = mysql_fetch_array($result);
The above is probably more useful for development error checking, in a production site you would probably want to capture the error and display something more graceful.
Also, I noticed you are calling require_once '../database.php'; and include '../database.php';. You don't need both, just the first will do.

Categories