php problems in search function - php

Im trying to add search function.
i want it to work like that: for exmple if i have 5 field, and user wrote only in 2, the search will be based only on 2 field. I mean it not neccesary to write information in all 5 field, i want search will happen only in filled fields.
And now it works only if i will write something in all fields (for now i have 2). And if i will write only in one field it doesnt show anything.
Code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="container">
<h1>Поиск</h1>
<form action="search_form.php" method="post">
<p>Направление</p>
<input type="text" name="course" />
<p>Форма обучения</p>
<input type="text" name="form" />
<input type="submit" value="Искать">
</form>
<?php
$db = mysql_connect("localhost", "root", "") or die (mysql_error ());
mysql_select_db("university", $db) or die(mysql_error());
$w = array('TRUE');
if (isset($_POST['course']))
{
$course = $_POST['course'];
$w[] = "course='$course'";
}
if (isset($_POST['form']))
{
$form = $_POST['form'];
$w[]= "form='$form'";
}
$where = implode($w, ' AND ');
$query = ('SELECT * FROM news WHERE '.$where);
$result = mysql_query($query,$db);
if($result !== false)
{
$news = mysql_fetch_array($result);
while($news = mysql_fetch_assoc($result)) {?>
<tr>
<td><?=$news['id']?></td>
<td><?=$news['program']?></td>
</tr><?
}
}
else
{
echo 'Sorry, we didn't find anything.';
}?>
</div>
</body>
</html>

You are vulnerable to SQL injection attacks. Learn about and fix that before you do ANYTHING else with this code.
Plus your logic is faulty: mysql_query() returns false on errors. A query which has no results is NOT an error, and still returns a valid query handle. It'll simply have 0 rows on it.
$result = mysql_query($query);
if ($result === false) {
die(mysql_error());
} else if (mysql_num_rows($result) == 0) {
die("No results");
} else {
... display results
}

Related

Display database value in array PHP MYSQLi

I"m attempting to display some data I've sent from ajax to a php file, however for some reason its not displaying it on the page. The way it works it I enter a search term into a input field, and a ajax script post the value to a php script, which return the database value requested back.
error_reporting(E_ALL);
ini_set('display_errors', '1');
if (isset($_POST['name']) === true && empty($_POST['name']) === false) {
//require '../db/connect.php';
$con = mysqli_connect("localhost","root","root","retail_management_db");
$name = mysqli_real_escape_string($con,trim($_POST['name']));
$query = "SELECT `names`.`location` FROM `names` WHERE`names`.`name` = {$name}";
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$loc = $row['location'];
echo $loc;
}//close While loop
} else {
echo $name . "Name not Found";
}
}
html form:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Retail Management Application</title>
</head>
<body>
Name: <input type="text" id="name">
<input type="submit" id="name-submit" value="Grab">
<div id="name-data"></div>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="js/global.js"></script>
</body>
</html>
You're appending a MySQL error result to your query, and you're trying to query a query result, try the following:
$query = "SELECT `names`.`location` FROM `names` WHERE`names`.`name` = '$name'";
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result) > 0) {
Edit:
{$name} that is a string and should be quoted instead.
change it to '$name' in the where clause.
Using:
$result = mysqli_query($con, $query) or die(mysqli_error($con));
will provide you with the reason as to why your query failed.

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>

Set the argument to a function in order to process it

So, I neet to set the argument to a function in order to convert it to a .mp3 file. Using this line : $tts->setText($row['raspuns']); doesn't happen anything but if i write $tts->setText("Hello World!"); it works perfectly, which takes me to the conclusion that i have to find a correct code to make that tts get the text. Can anyone help me please?
<html>
<head>
<title>
Bot
</title>
<link type="text/css" rel="stylesheet" href="main.css" />
</head>
<body>
<form action="bot.php "method="post">
<lable>You:<input type="text" name="intrebare"></lable>
<input type="submit" name="introdu" value="Send">
</form>
</body>
</html>
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("robo") or die(mysql_error());
$intrebare=$_POST['intrebare'];
$query = "SELECT * FROM dialog where intrebare = '$intrebare'";
$result = mysql_query($query) or die(mysql_error());
$row = $result;
?>
<?php
require "tts.php";
$tts = new TextToSpeech();
**$tts->setText($row['raspuns']);**
*//$tts->setText("Hello World!");*
$tts->saveToFile("voice.mp3");
$file='voice.mp3';
?>
<div id="history">
<?php
while (true == ($row = mysql_fetch_array($result))) {
echo "<b>The robot says: </b><br />";
echo $row['raspuns'];
echo "<embed src =\"$file\" hidden=\"true\" autostart=\"true\"></embed>";
}
?>
</div>
Here's the tts.php file:
<?php
class TextToSpeech {
public $mp3data;
function __construct($text="") {
$text = trim($text);
if(!empty($text)) {
$text = urlencode($text);
$this->mp3data = file_get_contents("http://translate.google.com/translate_tts?tl=en&q={$text}");
}
}
function setText($text) {
$text = trim($text);
if(!empty($text)) {
$text = urlencode($text);
$this->mp3data = file_get_contents("http://translate.google.com/translate_tts?tl=en&q={$text}");
return $this->mp3data;
} else { return false; }
}
function saveToFile($filename) {
$filename = trim($filename);
if(!empty($filename)) {
return file_put_contents($filename,$this->mp3data);
} else { return false; }
}
}
?>
You need to fetch the row from your result
If you want your code to work where your tts class calls are, change
$row = $result;
To
$row = mysql_fetch_row($result);
Note you have a code block below that redefines the $row array.
Also note mysql_* functions are deprecated, use PDO or mysqli_ functions instead. Your current code is wide open to sql injects!

If MySQL Result Empty display a confirm box

I'm using some crazy mixture of PHP/JavaScript/HTML/MySQL
$query = "SELECT * FROM faculty WHERE submitted = 0;";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row != NULL) {
// Display a confirm box saying "Not everyone has entered a bid, continue?"
}
// If confirmed yes run more queries
// Else nothing
What is the best way to have this confirm box display, before completing the rest of the queries?
if($row != NULL) {
?>
<script>alert("not everyone has submitted their bid.");</script>
<?php
}
or
<?php
function jsalert($alert_message){
echo "<script type='text/javascript'>alert('".$alert_message."');</script>";
}
if($row!=null){
jsalert("Not everyone has submitted their bid.");
}
?>
You can't do this in 1 continuous block, as all of the PHP will execute before the confirm (due to server vs. client).
You will need to break these into 2 separate steps and have the client mediate between them:
part1.php:
<?php
$query = "SELECT * FROM faculty WHERE submitted = 0;";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if ($row != NULL) { ?>
<form id="confirmed" action="part2.php" method="post">
<noscript>
<label>Not everyone has entered a bid, continue?</label>
<input type="submit" value="Yes">
</noscript>
</form>
<script type="text/javascript">
if (confirm("Not everyone has entered a bid, continue?")) {
document.getElementById('confirmed').submit();
}
</script>
<?
} else {
include_once('part2.php');
}
?>
part2.php:
<?php
// assume confirmed. execute other queries.
?>
$query = "SELECT * FROM faculty WHERE submitted = 0;";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row != NULL) {
// more queries here
} else {
echo "<script>alert('Empty result');</script>";
}
Play with this code and you will get it to work eventually. I know you are not looking for just alertbox , instead you are looking for something like "yes or no" informational box. So check this out.
<?php
?>
<html>
<head>
<script type="text/javascript">
function displayBOX(){
var name=confirm("Not everyone has entered a bid, continue?")
if (name==true){
//document.write("Do your process here..")
window.location="processContinuing.php";
}else{
//document.write("Stop all process...")
window.location="stoppingProcesses.php";
}
}
</script>
</head>
<?php
$query = "SELECT * faculty SET submitted = 0;";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row != NULL) {
echo "<script>displayBox();</script>";
}
?>

Inject dynamically some content on a listbox and get it back with PHP

I've created a webpage which uses JQuery to redirect the content of a form to another webpage using PHP to connect to a database to find some content and put it back on the first page.
Eveything works great (thanks to the help of followers of stack overflow :-) ) but now I'd like the following : I'm asking for the postal code of a city, if I'm lucky this postal code is unique (only one city has it) but it also happens that a postal code is the same for several cities so I'd like in that case to display a listbox for the user to choose his/her city.
Does someone has an idea of how to do this ?
my code :
home.html
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form action="/" id="myform">
<input type="text" name="postal_code" id="postal_code" placeholder="Search..." />
<input type="submit" value="Search" />
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
<script>
$('#myform').submit(function() {
var url = 'target.php';
var postal_code = $('#postal_code').val();
$.post( url, { postal_code: postal_code },
function( data ) {
$( "#result" ).empty().append( data );
}
);
return false;
});
target.php
<?php
try
{
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$bdd = new PDO('mysql:host=localhost;dbname=mydatabase', 'root', '', $pdo_options);
$response = $bdd->prepare('SELECT city FROM city_list where postal_code = ?');
$response->execute(array($_POST['postal_code']));
echo '<ul>';
while ($data = $response->fetch())
{
?>
<br/>The city you entered the postal code is : <?php echo $data['city'];
}
$response->closeCursor();
}
catch (Exception $e)
{
die('Error : ' . $e->getMessage());
}
?>
EDIT:
This is the code ok for my needs. I'd only to make some very minor changes from Jules' code to make it ok (for an unknow reason his answer worked perfectly for him but not for me :-) )
<?php
try {
//Get the postal code:
$postcode = $_POST['code_postal'];
//Make MySQL connection
mysql_connect("localhost", "root", "") or die (mysql_error());
//Select the database
mysql_select_db("site_artisans_amélioré");
//Do your query based on the postcode...
$query = "SELECT ville FROM liste_communes_code_postaux where code_postal = '" . mysql_real_escape_string($postcode) . "'";
//Return the response in a variable
$data = mysql_query($query) or die (mysql_error());
//echo "Num rows: " . mysql_num_rows($data);
//Check how many rows the query returned. If more than 1 that means several cities
//exist for one postcode, so you should show a listbox.
//If not, just return the ville name
if (mysql_num_rows($data) > 1) { ?>
<select name="cities">
<?php while ($row = mysql_fetch_assoc($data)) { ?>
<option value="<?php echo $row['ville']?>"><?php echo $row['ville']?></option>
<?php } ?>
</select>
<?php }
else {
$row = mysql_fetch_assoc($data);
echo $row['ville'];
}
}
catch (Exception $e) {
die("Error : " . $e->getMessage());
}
?>
I am not sure which library you are using for your Database queries, so I'll do it in Pseudo-code and mysql_query..
target.php
<?php
try {
//Get the postal code:
$postcode = $_POST['postal_code'];
//Make MySQL connection
mysql_connect("localhost", "username", "password") or die (mysql_error());
//Select the database
mysql_select_db("mydatabase");
//Do your query based on the postcode...
$query = "SELECT city FROM city_list where postal_code = '" . mysql_real_escape_string($postcode) . "'";
//Return the response in a variable
$data = mysql_query($query);
//Check how many rows the query returned. If more than 1 that means several cities
//exist for one postcode, so you should show a listbox.
//If not, just return the city name
if (mysql_num_rows($data) > 1) { ?>
<select name="cities" multiple="multiple">
<? while ($row = mysql_fetch_assoc($data)) { ?>
<option value="<?=$row['city']?>"><?=$row['city']?></option>
<? } ?>
</select>
<? }
else {
$row = mysql_fetch_assoc($data);
echo $row['city'];
}
}
catch (Exception $e) {
die("Error : " . $e->getMessage());
}
?>
I hope you catch my drift and you can complete it yourself.

Categories