redirecting a page in php - php

I managed to create a search bar that searches my forum,it searches the categories table then displays the results,however i want to make a link that redirects me to that result found ,for example i search for a category called business and it displays the result but i want the result to have a link such that when i click it it redirects me to that category
but i am getting an error
Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ',' or ';' in C:\xampp\htdocs\mysite\captcha2\tut.php on line 43
my code on line 43 is
<td>'.$category_title.="<a href='view_category.php?cid=".$id."' class='cat_links'>".$title." - <font size='-1'>".$description."</font></a>"'</td>
</tr>'
and this is my search bar code
if(isset($_POST['search'])){ //form submitted, clicked Submit Search
$query = strip_tags(mysql_real_escape_string($_POST['query'])); //try to prevent sql injections
if(!$query){ //not enterered a query
echo 'You must enter a search query!';
}else{
$table = 'categories'; //the table you want to search
$row = 'category_title'; //the row in which you want to search
$sql = mysql_query("SELECT * FROM `".$table."` WHERE `".$row."` LIKE '%".$query."%'"); //search query
if($sql){ //no errors
if(mysql_num_rows($sql) == 0){ //No results found.
echo 'No results were found for <strong>'.$query.'</strong>';
}else{ //one or more results have been found
echo 'We have found <strong>'.mysql_num_rows($sql).'</strong> for <strong>'.$query.'</strong>.<br><br>
<table>
<tbody>
<tr>
<td><strong>category_title</strong></td>
</tr>';
while($r = mysql_fetch_array($sql)){ //get data of every user where their category_title is like the $query string
$category_title = $r["category_title"];
//lets put the part they searched in bold.
$category_title = str_ireplace($query, '<strong>'.$query.'</strong>', $category_title);
//lets put the part they searched in bold.
echo '<tr>
<td>'.$category_title.="<a href='view_category.php?cid=".$id."' class='cat_links'>".$title." - <font size='-1'>".$description."</font></a>"'</td>
</tr>';
}
echo '</tbody></table>';
}
}else{
echo 'Sorry, an MySQL error occurred:<br><br>'.mysql_error(); //an error occurred, so echo it
}
}
}else{ //not clicked Submit Search, so echo the form
echo '<h3>Search</h3>
<br><br>
<form method="post">
<label for="q"></label> <input type="text" size="100" name="query" id="q" value="m0nsta.">
<input type="submit" name="search" value="Search">
</form>';
}
?>

Get rid of the = sign, and an extra quotation
<td>'.$category_title.="<a href='view_category.php?cid=".$id."' class='cat_links'>".$title." - <font size='-1'>".$description."</font></a>"'</td>
</tr>'
Should be
<td>'.$category_title."<a href='view_category.php?cid=".$id."' class='cat_links'>".$title." - <font size='-1'>".$description."</font></a></td>
</tr>"

."</font></a>"'</td>
</tr>';
This should end with a double quotation mark and not single like
echo '<tr> <td>'.$category_title."<a href='view_category.php?cid=".$id."' class='cat_links'>".$title." - <font size='-1'>".$description."</font></a></td></tr>";

USE
<td>'.$category_title."=<a href='view_category.php?cid=".$id."' class='cat_links'>".$title." - <font size='-1'>".$description."</font></a></td>
</tr>'";
Make use of eclipse IDE as a habit, it will really help you to avoid such errors

Related

search box creation in php

this is my coding for search box in my database but when i run it it shows the error Notice: Undefined variable: searching in /opt/lampp/htdocs/1234.php on line 15
then i i type anything in my search box
it says
Object not found!
The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.
If you think this is a server error, please contact the webmaster.
Error 404
localhost
Apache/2.4.3 (Unix) OpenSSL/1.0.1c PHP/5.4.7
<html>
<h2>Search</h2>
<form name="search" method="post" action="<?=$PHP_SELF?>">
Seach for: <input type="text" name="find" /> in
<Select NAME="field">
<Option VALUE="fname">diseasename</option>
<Option VALUE="lname">genename</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" value="Search" />
</form>
</html>
<?php
//This is only displayed if they have submitted the form
if ($searching =="yes")
{
echo "<h2>Results</h2><p>";
//If they did not enter a search term we give them an error
if ($find == "")
{
echo "<p>You forgot to enter a search term";
exit;
}
// Otherwise we connect to our Database
mysql_connect("localhost", "root", "****") or die(mysql_error());
mysql_select_db("missensencemuttation") or die(mysql_error());
// We preform a bit of filtering
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
//Now we search for our search term, in the field the user specified
$data = mysql_query("SELECT * FROM users WHERE upper($field) LIKE'%$find%'");
//And we display the results
while($result = mysql_fetch_array( $data ))
{
echo $result['fname'];
echo " ";
echo $result['lname'];
echo "<br>";
echo $result['info'];
echo "<br>";
echo "<br>";
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
//And we remind them what they searched for
echo "<b>Searched For:</b> " .$find;
}
?>
i dont know what i did wrong in my script. and i am a beginner in php and i am using internet reference for gaining knowledge in php.can one correct this script
use like below:
extract($_POST);
if ($searching =="yes")
$searching is not defined at this moment in the script. I think you mean $_POST['searching'].
Add an if (isset($_POST['searching'])) { //old if } around the comparison to be sure that $_POST['searching'] is set and replace $searching with $_POST['searching']
EDIT: Replace $PHP_SELF with $_SERVER['PHP_SELF'] , this could help you out.

Improve my SQL database form PHP code

Can someone have a look at my code Ive finally got working after 2 days and lots of help from here - thank you!
There are a few tweaks i would like to do on it -
for the transaction ID, if i search for any letter in the transaction id, i am shown records - I only want it to show me a record if the FULL transaction ID has been entered and matches the record in the database. Transaction id example: 87K07228GD157974M
if you want to retrieve your code, you must type in your name, email and transaction date, this works perfect BUT the time is also included with the date but i don't want anyone to have to enter the time as well ONLY the date i.e.....
you currently have to enter: 2013-03-07 01:39:23 - but i want to enter in the format of DD/MM/YY - is this possible?
I also don't know if the code is secure also, any advice would be appreciated.
Thanks,
here is the code:
findme.html
<html>
<head>
<title>Search</title>
</head>
<body bgcolor=#ffffff>
<h2>Search Transaction ID</h2>
<form name="search" method="post" action="findme.php">
Seach for: <input type="text" name="find" />
<input type="submit" name="search" value="Search" />
</form>
OR
<h2>Search Name, E-Mail & Transaction Date</h2>
<form name="search" method="post" action="findme1.php">
Full Name (on paypal account) <input type="text" name="name" /> <br><br>
Paypal E-Mail Address <input type="text" name="email" /> <br><br>
Transaction Date - DD/MM/YY <input type="text" name="date" />
<input type="submit" name="search" value="Search" /><br><br>
If searching via Name, E-Mail & Transaction date, all fields must be completed to obtain your code.
</form>
</body>
</html>
findme.php
<html>
<head><title>Searching for a student...</title>
</head>
<body bgcolor=#ffffff>
<?php
echo "<h2>Search Results:</h2><p>";
//If they did not enter a search term we give them an error
if ($find == "")
{
echo "<p>You forgot to enter a search term!!!";
exit;
}
// Otherwise we connect to our Database
mysql_connect("location.com", "ipn", "password!") or die(mysql_error());
mysql_select_db("ipn") or die(mysql_error());
// We perform a bit of filtering
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
//Now we search for our search term, in the field the user specified
$iname = mysql_query("SELECT * FROM ibn_table WHERE itransaction_id LIKE '%$find%'");
//And we display the results
while($result = mysql_fetch_array( $iname ))
{
echo "<b>Name: </b>";
echo $result['iname'];
echo " ";
echo "<br>";
echo "<b>E-mail: </b>";
echo $result['iemail'];
echo "<br>";
echo "<b>Transaction Date: </b>";
echo $result['itransaction_date'];
echo "<br>";
//And we remind them what they searched for
echo "<b>Search Term </b>(Transaction ID): </b> " .$find;
//}
echo "<br>";
echo "<br>";
echo "<b>Login Code: </b>";
echo $result['ipaymentstatus'];
echo "<br>";
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($iname);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your search, please make sure the correct details have been entered...<br><br>";
}
?>
</body>
</html>
findme1.php
<html>
<head><title>Searching for a student...</title>
</head>
<body bgcolor=#ffffff>
<?php
echo "<h2>Search Results:</h2><p>";
//If they did not enter a search term we give them an error
if ($name == "")
if ($email == "")
{
echo "<p>Please enter Full Name, E-Mail Address & Transaction Date EXACTLY how they appear on your PayPal Account...";
exit;
}
// Otherwise we connect to our Database
mysql_connect("location.com", "ipn", "password") or die(mysql_error());
mysql_select_db("ipn") or die(mysql_error());
// We perform a bit of filtering
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
//Now we search for our search term, in the field the user specified
$name = mysql_query("SELECT * FROM ibn_table WHERE iemail = '$email' AND iname = '$name' AND itransaction_date = '$date'");
//And we display the results
while($result = mysql_fetch_array( $name ))
{
echo "<b>Name: </b>";
echo $result['iname'];
echo " ";
echo "<br>";
echo "<b>E-mail: </b>";
echo $result['iemail'];
echo "<br>";
echo "<b>Transaction Date: </b>";
echo $result['itransaction_date'];
echo "<br>";
//And we remind them what they searched for
echo "<b>Search Term </b>(Transaction ID): " .$name;
//}
echo "<br>";
echo "<br>";
echo "<b>Login Code: </b>";
echo $result['ipaymentstatus'];
echo "<br>";
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($name);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your search, please make sure the correct details have been entered...<br><br>";
}
?>
</body>
</html>
Fields in my database are:
iname
iemail
itransaction_id
ipaymentstatus
itransaction_date
Thanks!
As stated in comment for transaction ID you have :
$iname = mysql_query("SELECT * FROM ibn_table WHERE itransaction_id LIKE '%$find%'");
what LIKE with %$find% does is match any part from transaction ID with $find that is why you get results with single letter. Change that to :
$iname = mysql_query("SELECT * FROM ibn_table WHERE itransaction_id = '$find'");
for date issue you can decide what to take from user like you stated date then for example :
if you take :
$date = "12-11-2012"; //(dd-mm-yyyy)
$split = explode("-", $date);
then you can use this to generate SQL date/time format :
$sql_date = date("Y-m-d h:i:s", mktime(0, 0, 0, (int) $split[1], (int) $split[0], (int) $split[2]))
and in sql query :
transaction_date LIKE '$sql_date%'
And at last don't use mysql_* it is deprecated. Instead use mysqli.

How to create a semantic search

I want to create a search box where instead of using a WHERE cluse in the query to match the exact phrase within a field, I want the search box to be able to perform a semantic search so that when the user enters in part of a phrase, it displays suitable results where it is able to match the meaning of a phrase. Exactly how Google works when you try and search through Google. Is this possible to achieve and does anyone have any ideas?
Below is the code I am currently using to be able to use the database to see if a row matches the exact phrase entered within the search box:
<?php
//connected to DB
foreach (array('questioncontent') as $varname) {
$questioncontent = (isset($_POST[$varname])) ? $_POST[$varname] : '';
}
?>
<p>Search for a previous question by entering in a phrase in the search box below and submitting the phrase</p>
<form action="previousquestions.php" method="post" id="modalform">
<p>Search: <input type="text" name="questioncontent" value="<?php echo $questioncontent; ?>" /></p>
<p><input id="searchquestion" name="searchQuestion" type="submit" value="Search" /></p>
</form>
<?php
if (isset($_POST['searchQuestion'])) {
$questionquery = "SELECT QuestionContent FROM Question
WHERE(QuestionContent = '".mysql_real_escape_string($questioncontent)."')";
$questionnum = mysql_num_rows($questionresult = mysql_query($questionquery));
if($questionnum !=0){
$output = "";
while ($questionrow = mysql_fetch_array($questionresult)) {
$output .= "
<table>
<tr>
<td>{$questionrow['QuestionContent']}</td>
</tr>";
}
$output .= " </table>";
echo $output;
}
}

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.

Search wont show on same page

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).

Categories