clickable results in php - php

Trying to display results that are clickable.
<form method="post" action="AF9.php">
<input type="submit" name="submit" value=" search ">
<input type="text" name="search" />
</form>
and here is partially the AF9.php file:
<?php
$connection = #new mysqli(HOSTNAME, MYSQLUSER, MYSQLPASS, MYSQLDB);
if ($connection->connect_error) {
die('Connect Error: ' . $connection->connect_error);
}
else {
$search=$_POST["search"];
$query="SELECT *, FROM comments AS c JOIN namestable2 AS w ON c.w1 = w.w1
WHERE name like '%$search%'
ORDER BY name DESC";
$connection->query("SET NAMES utf8");
$result_obj = '';
$result_obj = $connection->query($query);
while($result = $result_obj->fetch_array(MYSQLI_ASSOC)) {
$items[] = $result;
}
foreach ($items as $item) {
echo(''.$item['word'].'');
}?>
however when I click on the result, it says "Undefined index: search". Please help

Hardcoded links that end with "?key=value" like "?search=xyz" will pass via the GET stream, not the POST. Try changing this:
$search=$_POST["search"];
to this:
$search=$_GET["search"];

Are you sure you meant to do $search=$_POST["search"];?
If you're sending it in the URL, you'll need to do $search=$_GET["search"]; instead.

Your link is a $_GET not $_POST change
$search=$_POST["search"];
to
$search = $_GET['search'];

Related

foreach() Invalid argument supplied

I have this code that works for my friend but when I run it, it gave this Warning: Invalid argument supplied for foreach() in C:\wamp64\www\DVD_show.php on line 10
What is the problem?
'''
<?php
try {
/*** connect to SQLite database ***/
$dbh = new PDO("sqlite:dvd.db");
//echo("ok");
if(isset($_GET['name'])){
$name=$_GET['name'];
$sql = "SELECT * FROM DVD where name='".$name."'";
}else $sql = "SELECT * FROM DVD";
foreach ($dbh->query($sql) as $row)
{
print 'dvds[index++]="#'.$row['name'] ."#".$row['director']. "#". $row['price']."#".$row['stock'].'#";<br>';
//dvds[index++]="#Life is Beautiful#dvd1#10.5#10#history#Roberto Benigni#";
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
<form action="http://127.0.0.1/DVD_show.php" method="get">
<p>Please input DVD name: <input type="text" name="name" /></p>
<p><input type="submit" /></p>
</form>
'''
$dbh->query($sql) will return you Statement. You should use fetch or fetchAll to get the results. While fetch will return only one - so not iterable, you should use fetchAll, which always returns array.
The dbh-> query is wrong at this place as it only returns a statment but not something you can use with foreach
You first need to use the fetch() or fetchAll() methods
Please see changed code.
NOTE: If you have a HIGH number of results it is not recommended to use fetchAll as it loads the wohle dataset . then better use fetch() and while like shown in the example ar the link below.
<?php
try {
/*** connect to SQLite database ***/
$dbh = new PDO("sqlite:dvd.db");
//echo("ok");
if(isset($_GET['name'])){
$name=$_GET['name'];
$sql = "SELECT * FROM DVD where name='".$name."'";
}else $sql = "SELECT * FROM DVD";
//change this
$data = $dbh->query($sql) ->fetchAll();
foreach ($data as $row)
//changes end
{
print 'dvds[index++]="#'.$row['name'] ."#".$row['director']. "#". $row['price']."#".$row['stock'].'#";<br>';
//dvds[index++]="#Life is Beautiful#dvd1#10.5#10#history#Roberto Benigni#";
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
<form action="http://127.0.0.1/DVD_show.php" method="get">
<p>Please input DVD name: <input type="text" name="name" /></p>
<p><input type="submit" /></p>
</form>
'''
please see:
https://phpdelusions.net/pdo_examples/select

Search function with php

I've got my code which is searching my database and table for a certain condition but when I search it doesn't return any result. I've looked at a few tutorials and cant find the issue. Any help is appreciated. I know the code is outdated and I should be using mysqli. I will be changing this when the issue is rectified.
<?php
$output = NULL;
if(isset($_POST['submit'])){
mysql_connect("localhost", "root", "") or die (mysql_error());
mysql_select_db("first_db") or die("can not connect");
$search = $mysql->real_escape_string($_POST['search']);
$resultSet = $mysql->query("SELECT * FROM voulunteer WHERE Name LIKE '%search%'");
if($resultSet->num_rows > 0){
while($rows = $resultSet->fetch_assoc())
{
$StaffStatus = $rows['StaffStatus'];
$name = $rows['Name'];
$output = "Staff Status: $StaffStatus<br/>name: $Name<br/><br/>";
}
}else{
$output = "No results";
}
}
?>
<form method-"POST">
<input type="TEXT" name"search" />
<input type="SUBMIT" name="submit" value="Search" />
</form>
Your query is written wrong
instead of
$resultSet = $mysql->query("SELECT * FROM voulunteer WHERE Name = LIKE '%search&'");
try this
$resultSet = $mysql->query("SELECT * FROM voulunteer WHERE Name LIKE '%search%'");
edit: added nogad's comment about changing the & to %
Try the query in phpmyadmin first. If there's an error in the query it will tell you

php/mysql search function issue

I feel like I just need another set of eyes on this. There is of course something in the database to search, however nothing is displayed. Is there something wrong with the syntax or logic. This is all in one file index.php
<form action = "index.php" method = "post">
Search: <input type="text" name="value" placeholder="Is it part of the FWO?"></input>
<input type=submit name = "search" value="Search">
</form>
New Entry
<br>
<p>Search Results</p>
<hr />
<?php
error_reporting(E_ALL);
$title = $_POST['value'];
echo "You have searched: " .$title;
echo "<br>";
$con = mysql_connect("localhost", "user", "pass") or die ('Could not connect, this is the error: ' . mysql_error());
mysql_select_db("db") or die ('Sorry could not access database at this time. This is the error: ' . mysql_error());
$clean = msql_real_escape_string($_GET['value']);
echo "Another test ". $clean;
$run = mysql_query("SELECT * FROM db WHERE name = '$clean'") or die(mysql_error());
if(mysql_num_rows($run) >= 1){
echo "found entry";
while($i = mysql_fetch_array($run)){
echo $i['creator'];
}
}
else {
echo "No entries found";
}
mysql_close($con);
?>
</body>
</html>
Your form is using post method and you are trying get a value by $_GET
instead of this:
$clean = msql_real_escape_string($_GET['value']);
Use this:
$clean = msql_real_escape_string($_POST['value']);
Or
$clean = msql_real_escape_string($title);
To search inside mysql you should use LIKE. and if you want to search anywhere in the string you should encapsulate with %. for example:
$run = mysql_query("SELECT * FROM db WHERE name LIKE '%$clean%'") or die(mysql_error());
for more info: http://dev.mysql.com/doc/refman/5.7/en/string-comparison-functions.html

filling in form fields from previous database entry - php

I am trying to create a form where everything is filled out from the user's previous entry. Its suppose to work by the user selecting the "update" link. However the form is not being filled at all.
I've been trying to figure this out for 2 days now but i cant seem to figure it out. Some help would be greatly appreciated, thanks!
up.php
<form method="POST" action="up1.php">
<?php
$connection = mysql_connect("xxxxx","xxxxx","xxxxx")
or die("Could not make connection.");
$db = mysql_select_db("xxxxx")
or die("Could not select database.");
$sql1 = "SELECT * FROM emp ORDER BY primeID DESC ";
$sql_result = mysql_query($sql1) or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_array($sql_result))
{
$prime = $row["primeID"];
}
?>
Update
</form>
up1.php
<form action="up2.php" method="post">
<?
$connection = mysql_connect("xxxxx","xxxxx","xxxxx")
or die("Could not make connection.");
$db = mysql_select_db("xxxxx")
or die("Could not select database.");
$sql1 = "SELECT * FROM emp WHERE primeID = '$up22'";
$sql_result = mysql_query($sql1)
or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_array($sql_result))
{
$prime = $row["primeID"];
$a1 = $row["country"];
$a2 = $row["job"];
$a3 = $row["pos_type"];
$a4 = $row["location"];
$a5 = $row["des"];
$a6 = $row["des_mess"];
$a7 = $row["blurb"];
$a8 = $row["restitle"];
$a9 = $row["res"];
$a10 = $row["knowtitle"];
$a11 = $row["know"];
$a12 = $row["mis"];
$a13 = $row["mis_des"];
}
?>
<input name="aa1" value="<? echo $a1; ?>" type="text" id="textfield" size="60">
<input name="a1" type="text" value="<? echo $a2; ?>" id="textfield" size="60">
<input name="a2" type="text" value="<? echo $a3; ?>" id="a2" size="60">
<input name="a4" type="text" value="<? echo $a5; ?>" id="a4" size="60">
</form>
Based upon the limited information I could get out of your post I think I found the problem:
Starting with up.php
Update
Actually sends a "GET request" (Loading the page with a query string). We need to rebuild that:
<a href="JavaScript: void(0)" onclick="this.parentElement.submit()" >Update</a>
Now this link is going to send the form. However we need to send the value $prime. Let's use a hidden input inside the form.
<input type="hidden" name="up22" value="<? echo $prime; ?>" />
Now when the user clicks the link it posts the form and loads up1.php with the post var up22.
Changes to up1.php
$sql1 = "SELECT * FROM emp WHERE primeID = '".$_POST['up22']".'";
PDO
To update your code even further: PDO is a safer way to do queries. mysql queries are deprecated. They shouldn't be used anymore.
Replace your database calls with the following code:
function openDBConnection()
{
$name = "xxxxxx";
$pw = "xxxxxx";
$server = "xxxxxxx";
$dbConn = new PDO("mysql:host=$server;dbname=xxx", $name, $pw, , array( PDO::ATTR_PERSISTENT => false));
}
catch( PDOException $Exception )
{
echo "120001 Unable to connect to database.";
}
return $dbConn;
}
function doPDOQuery($sql, $type, $var = array())
{
$db = openDBConnection();
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
if ($type == "prepare")
{
$queryArray = $var;
$sth = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute($queryArray);
}
else if ($type == "query")
{
$sth = $db->query($sql);
}
else
{
echo "Supplied type is not valid.";
exit;
}
if (!$sth)
{
$error = $db->errorInfo();
echo $error;
exit;
}
return $sth;
}
These functions you can use to make PDO queries to the database. The first function opens a database connection, while the second functions actually performs the query. You do not need to call the first function. It's called in the second one.
Example based upon your code:
$sql1 = "SELECT * FROM emp WHERE primeID = :id";
$sql_result = doPDOQuery($sql1, 'prepare', array(":id" => $_POST['up22']));
while ($row = $sql_result->fetchAll() )
{
//loop through the results.
}
PDO works as follows: instead of passing php variables into the SQL string (and risking SQL-injection), PDO passes the SQL string and variables to the database and let's the database's driver build the query string.
PDO variables can be declared by name or by index:
By name: use : to declare a named variable. SELECT * FROM TABLE WHERE id = :id. Each key must be unique.
By index: use ? to declare an indexed variable. SELECT * FROM TABLE WHERE id = ?
An array containing the variables needs to be passed to PDO.
named array:
array(":id" => 1);
indexed array:
array(1);
With named arrays you don't have to worry about the order of the variables.
http://php.net/manual/en/book.pdo.php

Search Script for PHP website with MySQL Database

I have a PHP website to display products. I need to introduce a 'Search' feature whereby a keyword or phrase can be found among number of products.
I went through number of existing scripts and wrote/modified one for me which though able to connect to database, doesn't return any value. The debug mode throws a warning " mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given ". Seems I am not collecting the query value correctly. The PHP Manuals says that mysqli_query() returns FALSE on failure and for successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object and for other successful queries mysqli_query() will return TRUE ".
Any suggestions?
<form name="search" method="post" action="search.php">
<input type="text" name="searchterm" />
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="submit" value="Search" />
</form>
<?php
$searchterm=trim($_POST['searchterm']);
$searching = $_POST['searching'];
$search = $_POST['search'];
//This is only displayed if they have submitted the form
if ($searching =="yes")
{
echo 'Results';
//If they forget to enter a search term display an error
if (!$searchterm)
{
echo 'You forgot to enter a search term';
exit;
}
//Filter the user input
if (!get_magic_quotes_gpc())
$searchterm = addslashes($searchterm);
// Now connect to Database
# $db = mysqli_connect('localhost','username','password','database' );
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to the database. Please try again later.';
exit;
}
else {
echo "Database connection successful."; //Check to see whether we have connected to database at all!
}
//Query the database
$query = "SELECT * FROM wp_posts WHERE post_title LIKE '%$searchterm%' OR post_excerpt LIKE '%$searchterm%' OR post_content LIKE '%$searchterm%'";
$result = mysqli_query($db, $query);
if (!$result)
echo "No result found";
$num_results = mysqli_num_rows($result);
echo "<p>Number of match found: ".$num_results."</p>";
foreach ($result as $searchResult) {
print_r($searchResult);
}
echo "You searched for $searchterm";
$result->free();
$db->close();
}
To do your literal search as you have it, you would need to change the code '%{searchterm}%' to '%$searchterm%', since the brackets aren't needed and you were searching for the phrase "{searchterm}." Outside of that you might want to take a look at FULLTEXT search capabilities since you're doing a literal search in your current method.
To make the output look like Google's output you would simply code a wrapper for each search result and style them with CSS and HTML.
I think it should be something like '%$searchterm%', not '%{searchterm}%' in your query. You are not searching for your variable $searchterm in your example.
Google's display uses LIMIT in the query so it only displays a certain amount of results at a time (known as pagination).
This is tested and works. You will need to change 1) db connection info in the search engine class. 2) If you want it to be on separate pages, you will have to split it up. If not, copy this whole code to one page and it will work on that one page.
<?php
class DBEngine
{
protected $con;
// Create a default database element
public function __construct($host = '',$db = '',$user = '',$pass = '')
{
try {
$this->con = new PDO("mysql:host=$host;dbname=$db",$user,$pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
}
catch (Exception $e) {
return 0;
}
}
// Simple fetch and return method
public function Fetch($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
if($query->rowCount() > 0) {
$rows = $query->fetchAll();
}
return (isset($rows) && $rows !== 0 && !empty($rows))? $rows: 0;
}
// Simple write to db method
public function Write($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
}
}
class SearchEngine
{
protected $searchterm;
public function execute($searchword)
{
$this->searchterm = htmlentities(trim($searchword), ENT_QUOTES);
}
public function display()
{ ?>
<h1>Results</h1>
<?php
//If they forget to enter a search term display an error
if(empty($this->searchterm)) { ?>
<h3>Search Empty</h3>
<p>You must fill out search field.</p>
<?php }
else {
$con = new DBEngine('localhost','database','username','password');
$results = $con->Fetch( "SELECT * FROM wp_posts WHERE post_title LIKE '%".$this->searchterm."%' OR post_excerpt LIKE '%".$this->searchterm."%' OR post_content LIKE '%".$this->searchterm."%'");
if($results !== 0 && !empty($results)) { ?>
<p>Number of match found: <?php echo count($results); ?> on search:<br />
<?php echo strip_tags(html_entity_decode($this->searchterm)); ?></p>
<?php
foreach($results as $rows) {
echo '<pre>';
print_r($rows);
echo '</pre>';
}
}
else { ?>
<h3>No results found.</h3>
<?php
}
}
}
}
if(isset($_POST['submit'])) {
$searcher = new SearchEngine();
$searcher->execute($_POST['searchterm']);
$searcher->display();
} ?>
<form name="search" method="post" action="">
<input type="text" name="searchterm" />
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="submit" value="Search" />
</form>

Categories