am trying to create a search engine to enable users data search. I tried using like in the sql query and it works. Now i want to use mysql fulltext index as in the code below but its not displaying any data when search. my table is created as myislam with fulltext index enabled. below is the code
<?php
include('searchajax_db.php');
if($_POST) {
$q=mysql_real_escape_string($_POST['search']);
$sql_res=mysql_query("select * from articles WHERE MATCH(title,body) AGAINST ('$q')
order BY MATCH(title,body) AGAINST ('$q')");
//$sql_res=mysql_query("select id,title,body from articles where title like '%$q%' or body like '%$q%' ");
//
if($sql_res === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row=mysql_fetch_array($sql_res)) {
$ut=$row['title'];
$ub=$row['body'];
$b_ust=''.$q.'';
$b_emb=''.$q.'';
$final_u = str_ireplace($q, $b_ust, $ut);
$final_e = str_ireplace($q, $b_emb, $ub);
?>
<div class="show" align="left">
<?php echo '<a data-role="button" data-transition="fade" data-icon="arrow-r" data-iconpos="right" data-inline="true" href=profile.php?id='.htmlentities($row["id"], ENT_QUOTES, "UTF-8") .' title="Click to Find ">'.'<font color=orange></font>'.''
?>
<?php echo '<font color=greenyellow>' ?>
<span class="name"><?php echo htmlentities($final_u, ENT_QUOTES, "UTF-8"); ?></span> <br/>
<?php echo htmlentities($final_e, ENT_QUOTES, "UTF-8"); ?><br/>
<?php echo '</font>' ?>
</div>
<?php }} ?>
You don't need to use MATCH everywhere. The WHERE condition is where you determine which rows are retrieved from the table. Right after SELECT is where you choose which columns from those rows are displayed. ORDER BY determines which column and direction the rows are sorted by.
This example would probably be sufficient:
SELECT title, body FROM articles WHERE MATCH(title,body) AGAINST ('$q') ORDER BY title ASC
I also will note that you should use prepared statements with PDO or MySQLi as it is better protection than using mysql_real_escape_string.
Related
I want to output data from a query result. the query uses a print_r(json_encode($regions)) in another php page but it is not outputting anything. I have no errors in php, am I doing something wrong in mysqli code that it is not echoing anything?
//connecting to database
<?php
require_once('DbConnection.php');
//querying the database
$region_id = isset( $_GET['region_id'] )? $_GET['region_id']: false;
$sql=mysqli_query($connection,"SELECT sales.region_id, sales.image_name, sales.price, sales.location, sales.Terms, sales.Contacts
FROM sales INNER JOIN region ON sales.region_id=region.region_id where region_id = $region_id") or die(mysqli_error($connection));
$result = mysqli_query($connection,"SELECT sales.region_id, sales.image_name, sales.price, sales.location, sales.Terms, sales.Contacts FROM sales INNER JOIN region ON sales.region_id=region.region_id where region_id = $region_id");
while ($row = mysql_fetch_assoc($sql)) {
?>
<div class="col-md-4">
<div class="thumbnail">
<a href="<?php echo "http://" . $_SERVER['SERVER_NAME'] ?>/photo/imageuploads/<?php echo $row["image_name"]; ?>">
<img src="<?php echo "http://" . $_SERVER['SERVER_NAME'] ?>/photo/imageuploads/<?php echo $row["image_name"]; ?>" alt="Lights" style="width:100%">
<div class="caption">
Image Name:<?php echo $row["image_name"]; ?>
Price:<?php echo $row["price"]; ?>
Location`enter code here`:<?php echo $row["location"]; ?>
Terms:<?php echo $row["Terms"]; ?>
Contacts:<?php echo $row["Contacts"]; ?>
</div>
</a>
</div>
</div>
<?php
}
?>
In your SQL, your where clause refers to region_id, which in this case is defined in two tables (sales and region), if you need both of these tables, then you need to qualify which table you want to use the region_id from
$sql=mysqli_query($connection,"SELECT sales.region_id, sales.image_name,
sales.price, sales.location, sales.Terms, sales.Contacts
FROM sales
INNER JOIN region ON sales.region_id=region.region_id
where region.region_id = $region_id") or die(mysqli_error($connection));
but as you don't use any columns from region in your result, you could just drop the join...
$sql=mysqli_query($connection,"SELECT sales.region_id, sales.image_name,
sales.price, sales.location, sales.Terms, sales.Contacts
FROM sales
where region_id = $region_id") or die(mysqli_error($connection));
Also as Barmar says, remove the second execution of the query otherwise this may fail and stop the script as well.
Also where you check if $_GET['region_id'], this should be more a case of if it isn't set, then don't do anything. Just setting it to false will cause more problems.
I am a hobbyist programmer and stuck with php and sql
I have a website where I hope to allow different users to list their domains and websites for sale. I have an SQL database with the fields: id, domain and price. Now I added a column of data where "namer" is the field name.
I am trying to extract the field "namer" so it appears on the website but it won't work.
The problem starts at // PROBLEM AREA in the code and after that div it's okay.
<div class="domain_list_item_main_linear" style="font-family: 'Open Sans', Arial; width:98%;">
<div style="width:33%;float:left;">
<a href="<?php /*?><?php echo ConfigPeer::GetValue('website_folder'); ?>
<?php echo $domain->getCleanName(); ?><?php */?>https://www.afternic.com/domain/<?php echo urlencode($domain); ?>" class="moLPdomain" target="_blank">
<?php echo html_entity_decode($domain->getDivTipNameLinear(), ENT_QUOTES); ?></a>
<?php if(!$domain->getIsSold()): ?>
</div>
<div class="moLPprice" style="width:22%;float:left;margin-left:0px;">
<?php
// PROBLEM AREA
$eventid = $_GET['id'];
$namer = $_GET['namer'];
$result = mysql_query("SELECT $namer FROM `domain` WHERE `id` = '$eventid' ");
$row = mysql_fetch_array($result);
echo $row[$namer];
?> </div>
The problem is where you are using $namer.
The section after SELECT should contain the name of a column which contains the data you are trying to extract. Looking at your code, $namer isn't the name of the column, but some data that you are trying to match.
So the structure of the SQL should be like this:
SELECT column_name FROM table_name WHERE a_column_name = a_val;
I suggest you take a look at SQL SELECT statements, w3school's is a good place to start:
http://www.w3schools.com/php/php_mysql_select.asp
Edit:
You're SQL should look like this:
SELECT namer FROM domain WHERE id = $eventid;
If you want to get the 'namer' of the domain with that ID.
You're variable $namer must be storing any of the following words for your query to run:
id
domain
price
Hi i have written this code in order to get the news id from url and display the news result from this id which is stored in mysql. I dont know what i am doing wrong. But i am getting any output. I have also test my query which is running fine in mysql.I am doing small misatke which is not able to identif may be syntax or quotation somewhere. Thanks.
Here is my Url:
http://autodo/admin/news.php?id=2043
Here is my code:
<?php
$ID=$_GET['id'];
$sql=" SELECT DISTINCT ad_news.datum, ad_news_texte.text, ad_news_texte.headline, ad_news_texte.id
FROM autodo.ad_news_texte, autodo.ad_news
WHERE ad_news_texte.id =".$ID."
GROUP BY ad_news_texte.text, ad_news_texte.headline, ad_news_texte.id";
echo $sql_select=mysql_query($sql);
if($row = mysql_fetch_assoc($sql_select)){
$news_id= $row['id'];
$news_datum= $row['datum'];
$news_text= $row['text'];
$news_headline= $row['headline'];
?>
<div class="welcome-rahmen lng toggleNews" id="<?= $news_id ?> ">
<p class="welcome-breadcrump"><?= $news_datum ?></p>
<p class="welcome-subheadline"><?= $news_headline ?></p>
<div class="newsText">
<?= $news_text ?>
</div>
</div>
<? } ?>
You should concatenate $ID and sql string by .
For example:
$sql=" SELECT DISTINCT ad_news.datum, ad_news_texte.text, ad_news_texte.headline, ad_news_texte.id
FROM autodo.ad_news_texte, autodo.ad_news
WHERE ad_news_texte.id =".$ID."
GROUP BY ad_news_texte.text, ad_news_texte.headline, ad_news_texte.id";
You have used <?= echo - <?= alone is the same as <?php echo Additionally, as another pointed out you are missing several ; at the end of lines.
Regardless, I would encourage you to use prepared statements or otherwise sanitize the data you are pulling from the query string as your query as written is vulnerable to SQL injection.
first change quote to variable in where of query like
WHERE ad_news_texte.id ='$ID'
then no use of echo in
<?= echo $news_datum ?> try in all of your code <?= $news_datum ?>
so your whole code will be
<?php
$ID=$_GET['id'];
$sql="SELECT DISTINCT ad_news.datum, ad_news_texte.text, ad_news_texte.headline, ad_news_texte.id FROM autodo.ad_news_texte, autodo.ad_news WHERE ad_news_texte.id ='$ID' GROUP BY ad_news_texte.text, ad_news_texte.headline, ad_news_texte.id";
$sql_select=mysql_query($sql);
$checkrow = mysql_num_rows($sql_select);
if($checkrow > 0) {
if($row = mysql_fetch_assoc($sql_select)){
$news_id= $row['id'];
$news_datum= $row['datum'];
$news_text= $row['text'];
$news_headline= $row['headline'];
?>
<div class="welcome-rahmen lng toggleNews" id="<?= $news_id ?> ">
<p class="welcome-breadcrump"><?= $news_datum ?></p>
<p class="welcome-subheadline"><?= $news_headline ?></p>
<div class="newsText">
<?= $news_text ?><?php }
}
else {
echo 'query does not return any rows';
}?>
Some mistakes,
You mixing shorthand and echo for printing output.
Missing ; semi-colon at end of echo statment.
Syntax error in query
Firstly turn on your errors adding ini_set("display_errors",1); on top of your file.
Use below statemnt for everywhere you output the variable,
<?php echo $news_id; ?>
Or,
<?= $news_id ?>
Query should be,
$sql=" SELECT DISTINCT ad_news.datum, ad_news_texte.text, ad_news_texte.headline, ad_news_texte.id
FROM autodo.ad_news_texte, autodo.ad_news
WHERE ad_news_texte.id = '$ID'
GROUP BY ad_news_texte.text, ad_news_texte.headline, ad_news_texte.id";
Waring: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
I have a typical SQL query that returns results like this:
$result_acc_man = "SELECT * FROM mgap_management WHERE account_manager_id = '" . $_SESSION['account_manager_id'] . "' ORDER BY mgap_sales_pres";
$stmt = $pdo->prepare($result_acc_man);
$stmt->execute();
while($row_acc_man = $stmt->fetch(PDO::FETCH_ASSOC))
{
$salespres = $row_acc_man['mgap_sales_pres'];
$regvp = $row_acc_man['mgap_regional_vp'];
$areasales = $row_acc_man['mgap_area_sales_manager']
?>
<p class="asminfo"><span>Your ASM: <?php echo $areasales;?></span></p>
<p class="asminfo"><span >Your Regional VP: <?php echo $regvp; ?></span></p>
<p class="asminfo"><span >Your Sales President: <?php echo $salespres; ?></span></p>
<?php
}
?>
here are the column headers
<div id="viewheadaccept">
<span class="namecustaccept1">ACCOUNT NAME </span>
<span class="custaccept">ACCOUNT TYPE</span>
<span class="recoverycustaccept">OPPORTUNITY SIZE</span>
</div>
I need to add the ability to click on the column names and sort the data. Is there an easier way to accomplish this other than creating multiple linked pages with different queries that contain the sort?
Thanks!
You could provide a parameter to replace mgap_sales_pres. So send a orderBy parameter via the url stirng.
You would need to escape the variable for security. Normally this wouldn't be recommended, but since prepared statements can't inject variables into the ORDER BY clause, it's the only option for now.
For example mysql_real_escape_char($_GET['orderBy'])
Or if you are really paranoid you could use a switch case statement to check for a validate column name.
i'm working on adding filters to my database but i have no knowledge and google didnt really help so i appreciate all the advice =)
I would like to add filters like name and price and arrange by asc and desc order.
my db has 4 columns, id(int15) , brand/model(varchar50), picture(longblob), price (varchar50).
Any advice on how to approach this(best if have some examples as i'm a beginner)?
Currently below i created the form asc and desc below but i have no idea on how to integrating to my php code. I've set the form name as "results"
What i currently have is
index.php
<form action="search.php" type="text" method="POST">
Name: <input type ="text" name="search_name" size='30' />
<input type="submit" value="Search">
<br><br>
<b>Arrange Price by :</b>
<select name="results">
<option value="">Select...</option>
<option value="asc">Ascending</option>
<option value="desc">Descending</option>
</select>
<?php
if (isset($_POST['search_name'])) {
$search_name = $_POST['search_name'];
if (!empty($search_name)){
if (strlen($search_name)>=3) {
$query = "SELECT * FROM `shoes` WHERE `brand/model` LIKE '".mysql_real_escape_string($search_name)."%' ORDER BY `price` ASC";
$query_run = mysql_query($query);
$query_num_rows = mysql_num_rows($query_run);
if ($query_num_rows>=1) {
echo $query_num_rows.' Results found:<br>';
while ($query_row = mysql_fetch_array($query_run)) {
$picture = $query_row['picture'];
echo "</br>";
echo $query_row ['brand/model'];
echo str_repeat(' ', 15); // adds 5 spaces
echo $query_row ['price'];
echo "</br>";
echo "</br>";
//header("content-type: image/jpeg");
echo "<img src='image.php?id=".$query_row['id']."' width='300' height='200' />";
echo "</br>";
}
} else {
echo 'No Results Found.';
}
} else {
echo 'Text field must be more than 3 characters.';
}
} else {
echo 'Text Field Cannot be Empty!';
}
}
?>
Try using this code,
Changes what I have done are, created anchor's of your field name as table header
by default the headers are in ASC order, if we click it, it changes to DESC order
the sql query then uses the field name in GET to order the records
the search term is also then saved in the GET request so that we can persist it ahead
as search term is sometimes received in GET and sometimes in POST, have used REQUEST here, to get data
if (!empty($search_name)){
if (strlen($search_name)>=3) {
if(empty($_REQUEST['searchTrm']))
$_REQUEST['searchTrm'] = 'price';
if(empty($_REQUEST['order']))
$_REQUEST['order'] = 'ASC';
$query = "SELECT * FROM `shoes` WHERE `brand/model` LIKE '".mysql_real_escape_string($search_name)."%' ORDER BY ".$_REQUEST['searchTrm']." ".$_REQUEST['order'];
$query_run = mysql_query($query);
$query_num_rows = mysql_num_rows($query_run);
if ($query_num_rows>=1) {
echo $query_num_rows.' Results found:<br>';
?>
<table border=1>
<tr>
<td>
<?php
//use your sql field name as searchTrm value
if($_REQUEST['searchTrm'] == 'brand/model' && $_REQUEST['order'] == 'DESC') { ?>
<a href='?searchTrm=brand/model&order=ASC&search_name=<?php echo $_REQUEST['search_name']?>' title = 'ASC'>Brand Name</a>
<?php } else { ?>
<a href='?searchTrm=brand/model&order=DESC&search_name=<?php echo $_REQUEST['search_name']?>' title = 'DESC'>Brand Name</a>
<?php } ?>
</td>
<td>
<?php if($_REQUEST['searchTrm'] == 'price' && $_REQUEST['order'] == 'DESC') { ?>
<a href='?searchTrm=price&order=ASC&search_name=<?php echo $_REQUEST['search_name']?>' title = 'ASC'>Price</a>
<?php } else { ?>
<a href='?searchTrm=price&order=DESC&search_name=<?php echo $_REQUEST['search_name']?>' title = 'DESC'>Price</a>
<?php } ?>
</td>
<td>Image</td>
</tr>
<?php
while ($query_row = mysql_fetch_array($query_run)) {
$picture = $query_row['picture'];
?>
<tr>
<td><?php echo $query_row['brand/model'];?></td>
<td><?php echo $query_row['price'];?></td>
<td><img src='image.php?id=<?php echo $query_row['id'];?>' width='300' height='200' /></td>
</tr>
<?php
}
?> </table> <?php
} else {
echo 'No Results Found.';
}
} else {
echo 'Text field must be more than 3 characters.';
}
} else {
echo 'Text Field Cannot be Empty!';
}
}
Use of POST is fine, so long as you are sanitizing your input to prevent against SQL injections. To further protect yourself, you can use prepared statements. Also, I see you are using the mysql_* API. I highly recommend you switch to MySQLi or PDO instead. I'll place emphasis on MySQLi in this case since it looks as if you are using MySQL (although PDO will work for MySQL as well).
For the searching component:
Fields are best searched if they have been indexed. The database will use this behind the scenes to get at your data quicker. However, using the LIKE % <your search string> % with the wildcards (%) like you are will negate any index you have placed on a column. This is because using a wildcard on the left hand side of a search doesn't allow the MySQL to make use of the index. (Long story short, it simply can't figure out if text matches unless it scans the entire table.) What it sounds like you need is a FULLTEXT index which you can run queries using the MATCH...AGAINST syntax. You can use LIKE on an indexed column if you want, but drop the left hand wildcard, e.g.: SELECT * FROM ...... LIKE 'your search value'% .....
So from here I would suggest you look into the following concepts/topics:
Prepared statements in PHP using MySQLi (or PDO)
Column indexes (specifically FULLTEXT indexes for searching purposes)
Fulltext searching for MyISAM tables (MySQL < 5.6) or Fulltext searching for InnoDB (MySQL 5.6+)
Internal "scoring" for FULLTEXT and how to use it
Boolean and natural language searching.
Adding a search filter like you want is a nice feature, but it takes a little more than what you are trying to do. (And trust me, Google will provide you plenty of information and these subjects. It is a matter of practicing and getting use to using the newer features of MySQL.)
• Use PDO or Mysqli prepared statement .
• I'll use regex to filter the inputs (remove all non-words,numbers and some chars) .
example: $string = preg_replace('~[^\w\s-_\.,]~','',$string);
• I'll use full text search .