I cant seem to work out how to search (and display) multiple words that are in my database. This is an image of the database column
There all separate locations: Africa | Wales, UK | Stockholm, Sweden and I want to search for locations that are the same and display them, the following code works if there is one word in the column but not if there are multiple.
<?php
$sessionid = $_SESSION['id'];
$sql = "SELECT * FROM users WHERE id = '$sessionid';";
$rsults = mysqli_query($conn, $sql);
$resultsCheck = mysqli_num_rows($rsults);
if ($resultsCheck > 0) {
while ($row = mysqli_fetch_assoc($rsults)){
$follow = $row['follow'];
$loc = $row['places'];
}
}
$sql = "SELECT * FROM posts WHERE ext LIKE '$loc' OR username LIKE '$follow' ORDER BY `a_date` DESC LIMIT 4";
$rsults = mysqli_query($conn, $sql);
$resultsCheck = mysqli_num_rows($rsults);
if ($resultsCheck > 0) {
while ($row = mysqli_fetch_assoc($rsults)){
echo '<div class="posts">';
echo '<img class="img"src='.$row['img'].' width="1500px">';
echo '</div>';
echo '<div class="contain">';
echo '<div class="over">';
echo '<div class="username2">';
echo '<img src="focus.png" width="25px" height="25px" style="padding-right: 10px;">'.''.$row['username'].''.'<img src="loc.png" width="25px" height="25px" style="padding-right: 5px; padding-left: 10px;">'.''.$row['ext'].'';
echo '</div>';
echo '<div class="content">';
echo $row['content'];
echo '</div>';
echo '</div>';
}
}
?>
Also I know this is open to sql injection, it's just a proof of concept. Thanks for the help!!
like operator in mysql comes with wild card e.g. '%', '_' etc.
you can use mysql query like this
$sql = "SELECT * FROM posts WHERE ext LIKE '%$loc%' OR username LIKE '$follow' ORDER BY `a_date` DESC LIMIT 4";
for example if $loc = 'canada', it will return all the rows which have 'canada' in thier column whether the column contains 'canada, abc' or 'abc, canada'
When using LIKE you should add '%' sign at start and/or at end of LIKE parameter so it won't search for identical term but one starting or ending with the string you provided. Something like:
$sql = "SELECT * FROM posts WHERE ext LIKE '%$loc%' OR username LIKE '$follow' ORDER BY `a_date` DESC LIMIT 4";
So it will find location that contains your search criteria and not just those identical to it. '%' is replacing any number of characters here.
This goes if you have one search term and you have multiple terms in database column. But if you have multiple search terms you will have to generate your query dynamically, adding one "OR ext LIKE '%$loc%'" for every term.
Use an "%" sign when using the LIKE functionality.
$sql = "SELECT * FROM posts WHERE ext LIKE '%$loc%' OR username LIKE '$follow' ORDER BY `a_date` DESC LIMIT 4";
This would allow you to search through the content of a field.
Related
On my site, I have 4 radio selectors to add a filter to my search script. If a filter is selected, it should run the search script on only the column which the filter is set to, otherwise if the filter is set to all or not set, it should search all columns. However, when I set my filter to search only one column (the all option works), the query returns an empty result. I have tested the query and it works fine.
I have posted the code for the whole script, however the code block in question is marked with comments. The $filter and $search variables both come through correctly. I have tested this from within the script.
<?php
include ('connect.php');
if(isset($_POST['search'])) {
$search = $_POST['search'];
if(isset($_POST['filter'])) {
$filter = $_POST['filter'];
if($_POST['filter'] == "all") {
echo "Searching all";
$query = mysqli_query($con, "SELECT DISTINCT model, image, brand, id FROM cranes WHERE (model LIKE '%$search%' OR brand LIKE '%$search%' OR type LIKE '%$search%')");
}
else {
//Code block in question starts
echo "Searching filtered selection only";
$query = mysqli_query($con, "SELECT DISTINCT model, image, brand, id FROM cranes WHERE '$filter' LIKE '%$search%'") or die(mysqli_error($con));
//Code block in question ends
}
}
else {
echo "Searching all";
$query = mysqli_query($con, "SELECT DISTINCT model, image, brand, id FROM cranes WHERE (model LIKE '%$search%' OR brand LIKE '%$search%' OR type LIKE '%$search%')");
}
}
else {
$query = mysqli_query($con, "SELECT DISTINCT model, image, brand, id FROM cranes");
}
while ($row = mysqli_fetch_array($query)) {
echo "<div class='crane'><a href='#!edit' id='" . $row['id'] . "'><img src='images/" . $row['image'] . "' /><p class='craneName'>" . $row['brand'] . ' ' . $row['model'] . "</p></a></div>";
}
?>
$query = mysqli_query($con, "SELECT DISTINCT model, image, brand, id FROM cranes
WHERE '$filter' LIKE '%$search%'") or die(mysqli_error($con));
You’ve put the column name you are passing in $filter in single quotes here, which makes it a mere text literal instead of a column name.
So remove the single quotes … and after that, go read up on SQL injection, but quickly.
I am putting a system together and I would like to get the amount of rows of users that doesn't include the session['id'] user so I can show the link a bit like facebooks.
Example: You and x.. others likes this
Obviously just using the standard num rows grabs all the records from the database but I'd like to exclude the session.
$likes = mysqli_query($mysqli, "
SELECT feedback_streamid,feedback_userid,feedback_rating FROM streamdata_feedback
WHERE feedback_streamid=".$streamitem_data['streamitem_id']."
AND feedback_rating=1 ORDER BY feedback_id LIMIT 10")
or die("SELECT Error: ".mysqli_error($mysqli));
$numRowslikes = mysqli_num_rows($likes);
while ($row = mysqli_fetch_array($likes)) {
$likesmemberid = rawfeeds_user_core::getuser($row['feedback_userid']);
$user1_id = $_SESSION['id'];
$user2_id = $row['feedback_userid'];
if ($user2_id == $_SESSION['id']) {
echo '<div class="like_name"><b>You and '.$numRowslikes.' Others likes this </b> ';
} else {
echo '<a title="'.$likesmemberid['fullname'].' Likes This" href="profile.php?username='.$likesmemberid['username'].'"> <img border=\'0\' src=\'../userimages/ cropped'.$row['feedback_userid'].'.jpg\' onerror="this.src=\'userimages/no_profile_img.jpeg\'" width=\'20\' ></a> ';
}
}
It sounds like you could just change your query to exclude the current user's ID, then use num_rows() as normal.
WHERE feedback_userid NOT IN ('whatever_id_here')
I need to do a MySQL query to search for an inexact match / match containing the submitted value.
The following is an example of what is in my database:
id img
1 1001_ABC_01.jpg
2 1001_ABC_02.jpg
3 1002_ABC_01.jpg
4 1002_ABC_02.jpg
5 1002_ABC_03.jpg
6 1002_ABC_04.jpg
7 1002_ABC_05.jpg
8 1003_ABC_01.jpg
9 1003_ABC_02.jpg
10 1003_ABC_03.jpg
I need the query to search for the first part of the filename (1002) and and assign each returned result in the img field a different variable. The maximum amount of variables would be 5.
For example, if I search 1002, it should assign the following variables:
<?php
$img1 = '1002_ABC_01.jpg';
$img2 = '1002_ABC_02.jpg';
$img3 = '1002_ABC_03.jpg';
$img4 = '1002_ABC_04.jpg';
$img5 = '1002_ABC_05.jpg';
?>
so that way I can echo each filename result individually.
Again, the maximum amount of variables here will be 5, so if more than 5 results are returned, only the first 5 will be assigned variables.
Please let me know if this is possible and how to write a PHP script to do it.
SELECT img FROM <table_name> WHERE img LIKE '%search%' ORDER BY ID DESC LIMIT 5;
You could substring function, if the first four integers are fixed like this:
select substring(img,1,4) from <table_name> where img = 'search' order by ID DESC limit 5;
I hope this will help you. Always try to use latest apis and function like MySqli try to avoid mysql_* functions because they are depreciated and MySqli is also faster then mysql_ functions
$img = '1002'; // For example
$connection = new Mysqli(host, user, password, database);
$sql = "SELECT img FROM <table_name> WHERE img LIKE '$img%' LIMIT 5";
if($connection->query($sql)){
$counter = 1;
while ($row = $connection->fetch_object()){
${'img'.$counter} = $row->img;
$counter++;
}
}
$query = "SELECT * FROM my_table WHERE img_name LIKE '%1002%' LIMIT 5";
foreach ( $fetched_row as $value ) {
echo $value [ 'img_name' ]; // or whatever you want to do
}
Something like that.
Use this query
SELECT img as IMG
FROM my_table
WHERE img LIKE '1002%'
order by id desc
LIMIT 5
<?php
$query="SELECT id,img as image FROM image_table
where img like '%$keyword%' limit 5";
$res=mysql_query($query) or die(mysql_error());
while ($img = mysql_fetch_array($res)) {
echo $img['image'];
}
?>
$con = new Mysqli(host, user, password, database);
$result = $con->query("SELECT * FROM table WHERE image LIKE %$search% ORDER BY id DESC LIMIT 5");
if($result){
while ($row = $con->fetch_object()){
$img_arr[] = $row;
}
}
I hope this will help you.
$queryStr = "SELECT img FROM table_name WHERE search_str LIKE '1002%'";
$query = mysql_query($queryStr);
while($row = mysql_fetch_assoc($query)){
$imageArray[] = $row;
}
// Print the array
echo '<pre>';
print_r($imageArray);
echo '</pre>';
// How to use the array
foreach($imageArray as $key=>$val){
echo 'File Name: '.$val;
echo '<br />';
echo '<img src="'.$val.'" />';
echo '<hr />';
}
// Now show first five result
// Alternet: You can use LIMIT and order by with mysql
// With php
for($i=0;$i<5;$i++){
echo 'File Name: '.$imageArray[$i];
echo '<br />';
echo '<img src="'.$imageArray[$i].'" />';
echo '<hr />';
}
To search for a partial match you can use the LIKE operator in SQL. In this case you could write:
$sql = "SELECT img FROM tablename WHERE img like '1002%'";
How to perform this query and obtain the results in PHP depends on the database API you are using: old MySQL? MySQLi? PDO? Also, 1002 is probably user input, in which case you have to protect your program against SQL injection attacks.
As to the second part, are you sure you want different variable names and not an array? Arrays are much easier to use. You can get different variable names if you first accumulate the data in an array and then use extract:
$result = array();
$counter = 1;
$rs = mysql_query($sql); // using old mysql API
while ($row = mysql_fetch_array($rs)) {
$result["img".$counter] = $row[0];
$counter = $counter + 1;
}
extract($result);
// now $img1, $img2, $img3, ... are defined
your code will look like this:
$input = '1002'; // For example
$query = "SELECT id, img FROM table_blah WHERE img LIKE '$input%' LIMIT 5";
This query is basically selecting id, and img from the table table_blah, and img must be the same as 1002, and % meaning absolutely anything from there on. Limited to 5 results.
Then:
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
// Code for each result here.
// id = $row['id']
// img = $row['img']
}
$query = "SELECT * FROM img_table WHERE img_name regexp concat('1002', '%')"
$results = mysql_query($query);
then $results is an array of img strings
I don't know how to make the search through another table. how should i do that?
the table name is comments and i want to search for all the post stored in the column name kom
Another thing is that i cant get the pagination start working...
I started the pagination within an else statment because i only need it when i get more than 1 result.
I can get the page links showing and limit the search posting showing but when i click on one off the links i cant get to the next page
Heres the code
<?php
$search = $_POST["search"];
$field = $_POST["field"];
if($_POST["submit"] && $search)
{
echo "<div id='result'>";
echo "<h2>Resultat</h2>";
$search = strtoupper($search);
$search = strip_tags($search);
$search = trim($search);
$query = "SELECT * FROM blogTable WHERE title LIKE '%$search%'
UNION
SELECT * FROM blogTable WHERE post LIKE '%$search%'";
$result = mysql_query($query, $conn) or die(mysql_error());
$matches = mysql_num_rows($result);
if($matches == 0)
//code if serch didnt result any results
else if($matches == 1)
//code if the matches only 1
else
{
$per_page = 4;
$pages = ceil($matches / $per_page);
$page = (isset($_GET['page'])) ? (int)$_GET['page']: 1;
$start = ($page - 1) * $per_page;
$query2 = "SELECT * FROM blogTable WHERE title LIKE '%$search%'
UNION
SELECT * FROM blogTable WHERE post LIKE '%$search%' LIMIT $start, $per_page";
$result2 = mysql_query($query2, $conn) or die(mysql_error());
echo "<font size='-1'>Sökningen $search gav $matches resultat</font><br/>";
while ($r2 = mysql_fetch_array($result2))
{
$id = $r["id"];
$title = $r["title"];
$post = $r["post"];
$time = $r["time"];
echo "<br/><strong><a href='comment.php?id=$id'>$title</a></strong><br/>";
echo "<font size='-1'>".substr($post, 0, 60)."</font><br/>";
echo "<font size='-1'>".substr($post, 60, 70)."</font><br/>";
echo "<font size='-3'>$time</font><br/>";
}
//theese are showin but cannot click of any of them
if($pages >= 1 && $page <= $pages)
{
for($nr = 1; $nr <= $pages; $nr++)
{
if($nr == $page)
echo "<a href='?page=".$nr."' style='font-size:20px;'>$nr</a>";
else
echo "<a href='?page=".$nr."' style='font-size:15px;'>$nr</a> ";
}
}
}
}
?>
Is there a specific reason you are using a UNION?
If not, you can change:
$query = "SELECT * FROM blogTable WHERE title LIKE '%$search%'
UNION
SELECT * FROM blogTable WHERE post LIKE '%$search%'";
to:
$query = "SELECT * FROM blogTable WHERE (title LIKE '%$search%') OR (post LIKE '%$search%')";
Anyway, I would never execute the same query twice, just get the first x results if no start parameter was given (for example a page number in the query string) and calculate the start point when a start parameter was given.
And if you want the total, use a COUNT(*) query or change your query:
$query = "SELECT SQL_CALC_FOUND_ROWS * FROM blogTable WHERE (title LIKE '%$search%') OR (post LIKE '%$search%')";
One thing that catches the eye is that the code you show is vulnerable to SQL injection.
Get rid of the strip_tags() (if it's for security, in which case it's useless) and do a mysql_real_escape_string() on every value you use in the search queries, or check whether the value is actually a number when using int columns.
Another thing is that the <font> tag is outmoded. The cool CSS way of styling text is having an external CSS stylesheet, and defining in it something like
span.small { font-size: 12px; color: green }
and then using it in the HTML like so:
<span class="small">Text goes here</span>
that said, this probably belongs on CodeReview.SE....
First, I always recommend to use GET method and not POST method for searches and filters, next, maybe this pagination php class can help you.
I have a PHP search suggestion script which gets results from a MySQL database and then pushes them to the page with jQuery. In my database I have a field for the rank of each result but I want to make this work in my PHP code. I want the results with the highest number in their rank field to be displayed higher.
My PHP code is:
<p id="searchresults"><?php
$db=new mysqli('localhost','username','password','database');
if(isset($_POST['queryString'])){
$queryString=$db->real_escape_string($_POST['queryString']);
if(strlen($queryString)>0){
$query = $db->query("SELECT * FROM search WHERE name LIKE '%" . $queryString . "%' LIMIT 10");
if($query){
while ($result = $query ->fetch_object()){
echo '<a href="/search/'.$result->name.'/1/">';
$name=$result->name;
echo ''.$name.'';
}
}
}
}
?></p>
I hope you can understand what I am trying to describe.
Thanks in advance, Callum
You can just added 'ORDER BY rank DESC' in you sql query
$query = $db->query("SELECT * FROM search WHERE name LIKE '%" . $queryString . "%' ORDER BY rank DESC LIMIT 10");
You can go on mysql help for SELECT