I have two MySQL questions.
$query = " SELECT
stationname
FROM
stations
WHERE
stationname >= '". mysql_real_escape_string($_GET['letter']) ."'
ORDER BY
stationname
";
Here is the first query. In the URL is a parameter set $_GET['letter'] containing an Alphabetic character. I'm trying to select all the rows where stationname starts with $_GET['letter']. So i found this solution in an other Stackoverflow topic, but it doesn't seem to work, i get all my rows, and not just that single one. edit : seems it checks for all the characters in stationname, and not just the starting letter, how can i get that?
$query = " SELECT
stationname
FROM
stations
WHERE
stationname
LIKE
'". mysql_real_escape_string($_POST['search']) ."'
";
Second and final question. I want to make a search engine for my website, selecting all the rows where stationname contains $_POST['search']. But when i have 2 rows, one for example called cheese and the other one called cheese2, and i search for cheese, only cheese get selected, and when i search for cheese2, only cheese2 will get selected. Is there any way to select both cheese and cheese2?
LIKE supports wildcards. % means any number of characters (including zero), and _ means any one character`
stationname LIKE 'cheese%'
This would match cheese and cheese2.
You can use the % for the first issue too.
stationname LIKE 'a%'
This will find all words that start with 'a'.
I'm trying to select all the rows where stationname starts with $_GET['letter']
MySQL has a LEFT function which seems to be what you're looking for. So basically we extract the first letter of the stationname and compare it agains your letter:
where left(stationname, 1) = '" . mysql_real_escape_string($_GET['letter']) . "'";
Is there any way to select both cheese and cheese2?
Well here the solution is a little smelly, as you should check whether cheese is contained in cheese2 and also whether cheese2 is contained in cheese. Try this:
where stationname like '%" . mysql_real_escape_string($_POST['search']) .
"%' OR '" . mysql_real_escape_string($_POST['search']) .
"' like concat('%', stationname, '%')";
for second.
$query = " SELECT
stationname
FROM
stations
WHERE
stationname
LIKE
'". mysql_real_escape_string($_POST['search']) ."%'
";
The text wildcard in MySQL is %, so for your first query you would probably want:
$query = " SELECT
stationname
FROM
stations
WHERE
stationname LIKE '". mysql_real_escape_string($_GET['letter']) ."%'
ORDER BY
stationname
";
And for your second query:
$query = " SELECT
stationname
FROM
stations
WHERE
stationname
LIKE
'%". mysql_real_escape_string($_POST['search']) ."%'
";
FOR Tel Number
5 finds that the first character
$Sql="SELECT * FROM customers WHERE TEL REGEXP '^[5]' LIMIT 0,500";
Related
I want to fetching Records On the Basis Of Entered Keywords in the Search Bar.
Suppose I have Below 3 Records in My SQL Table's Column
Beautiful Small Kid.
Beautiful Rabbit in the Zoo.
Natural Water.
Now, If the Search Query contains Beautiful, It will Return First 2 Records.
If the Search Query contains Beautiful (anything), It will Return Nothing.
I want those First 2 Records to be Displayed in this case too, Because It has the same word beautiful like in above searched Query.
Right Now, I am Using
SELECT * FROM table WHERE name LIKE '%value%' ORDER BY id ASC
Is there any Other Query or Method to Achieve Such Sort Of Results ?
SELECT * FROM table WHERE (name LIKE '%value1%') OR (name LIKE '%value2%') ORDER BY id ASC
etc
So, you would have to split up your search string into separate words.
$str = yourinput;
$strarray = (explode(" ",$str));
$query = "SELECT * FROM table WHERE ";
Foreach($strarray as $key=>$value){
If($key > 0){
$query = $query . "OR";
}
$query = $query . " (name LIKE '%" . $value . "%') ";
}
$query = $query . "ORDER BY id ASC";
I have a question for my search bar:
In Account Management, I have list of accounts
And this is the Account table:
*AccountID (Example: 1)
*AccountName (Example: Test)
(...)
Now, When I type Test, or 1, I find my result.
My problem is how to search by typing one of character name, this is the characters table:
*CharacterName (Example: Charac)
*AccountID (1 [the same accountID])
I've tried INNER JOIN but it's not working, and i think it isn't the correct method, this is my SQL code
$sql = "SELECT * FROM account INNER JOIN characterrecord ON characterrecord.AccountId = account.AccountId WHERE account.AccountId LIKE '%" . $name . "%' OR account.Name LIKE '%" . $name ."%' OR characterrecord.Name LIKE '%" . $name ."%' GROUP BY account.accountid LIMIT ".$_GET['page'].",".$page_accountnumber;
$req = mysql_query($sql) or die('Erreur SQL !<br />'.$sql.'<br />'.mysql_error());
while ($acc = mysql_fetch_array($req)) {
....
What I want:
If I type Charac or char ... I must see 1/Test (Character account infos).
Sorry for my bad english, I'm french, and thank you so much!
Since the tables share certain field names, it may be necessary to specify or alias the fields in the SELECT clause to ensure whatever framework you are handling them with is capable of distinguishing them.
The Script:
<?php
include("connect.php");
?>
<?php
echo "<h1>The Hashtag: </h1>";
if(isset($_GET['hashtag'])){
echo $_GET['hashtag'];
}
// Select the ID of the given hashtag from the "hashtags" table.
$tqs = "SELECT `id` FROM `hashtags` WHERE `hashtag` = '" . $_GET['hashtag'] . "'";
$tqr = mysqli_query($dbc, $tqs) or die(mysqli_error($dbc));
$row = mysqli_fetch_assoc($tqr);
// This prints e.g.:
// 100
echo "<br/><br/>";
print_r($row['id']);
// Select the threads from the "thread" table which contains the hashtag ID number.
$tqs_two = "SELECT * FROM `thread` WHERE `hashtag_id` IN ('" . $row['id'] . "')";
$tqr_two = mysqli_query($dbc, $tqs_two) or die(mysqli_error($dbc));
$row_two = mysqli_fetch_assoc($tqr_two);
echo "<br/><br/>";
print_r($row_two);
?>
The script should select the rows by that ID number of the hashtag. It should look in the "hashtag_id" column of the table and see if that ID number can be found there, if it can be found there, then it should select that row.
The ID numbers are inside that "hashtag_id" column separated by commas.
Example:
98, 99, 100
Basically, is there a way to do a SQL query to see if the column "contains" that ID number or may have to something else here?
Any suggestions are appreciated.
As Jay says, you can use "contains". You'll need to be cautious though; if you are looking for a hashtag_id of "9", your query needs to avoid returning "19", "99", "93", etc. To that end, you have rely on the exact formatting of the data in that hashtag_id field. If your numbers are really separated by commas and spaces, you can easily find exact matches that ARE NOT AT THE BEGINNING OR END of the query by doing "hashtag_id LIKE '%, 9,'". That won't, however, find any at the beginning or the end of the hashtag_id field. To catch those, you ALSO need "hashtag_id LIKE '9, %'" and "hashtag_id LIKE '%, 9'".
So, to catch all three possibilities:
SELECT * FROM `thread` WHERE `hashtag_id` LIKE '9,%' or `hashtag_id` LIKE '%, 9,%' or `hashtag_id` LIKE '%, 9';
To do contains you would use LIKE -
$tqs_two = "SELECT * FROM `thread` WHERE `hashtag_id` LIKE '%" . $row['id'] . "%'";
I am making an autocomplete form and requesting names from my database. This is the table in my database
user_id | firstname | lastname
I can get the data for a "searchterm" using this
$query = "SELECT user_id, firstname, lastname FROM users WHERE firstname like :searchterm ";
But I want to expand it so I could also search both firstname and lastname at the same time, for example, to search for "John D...". I think there is a way to join the two columns and then make a search. Can someone explain it?. I am just starting with this mysql thing.
When you've got spaces in your search term, you'll often need to split the string into sections before you put it into your query. Use AND if you want to match all inputted search terms, or OR if you want to match any. Example:
Search: john james smith
<?php
$search = "john james smith";
$bits = explode(" ", $search);
foreach($bits as $key => $bit) {
$bits[$key] = '(`field1` LIKE "' . $bit . '" AND `field2` LIKE "' . $bit . '")';
}
$sql = implode(' OR ', $bits);
// (`field1` LIKE "john" AND `field2` LIKE "john") OR (`field1` LIKE "james" AND `field2` LIKE "james") OR (`field1` LIKE "smith" AND `field2` LIKE "smith")
?>
Demo: https://eval.in/66808
Looks like you're using PDO (which is good), so you'll just need to put your binding parameters into that string instead, then concatenate it on at the end of your current SQL query into the WHERE clause.
I currently use a mysql statement like the one below to search post titles.
select * from table where title like %search_term%
But problem is, if the title were like: Acme launches 5 pound burger and a user searched for Acme, it'll return a result. But if a user searched for Acme burger or Acme 5 pound, it'll return nothing.
Is there a way to get it to return results when a users searches for more than one word? Is LIKE the correct thing to use here or is there something else that can be used?
You could use a REGEXP to match any of the words in your search string:
select *
from tbl
where
title REGEXP CONCAT('[[:<:]](', REPLACE('Acme burger', ' ', '|'), ')[[:>:]]')
Please notice that this will not be very efficient. See fiddle here.
If you need to match every word in your string, you could use a query like this:
select *
from tbl
where
title REGEXP CONCAT('[[:<:]]', REPLACE('Acme burger', ' ', '[[:>:]].*[[:<:]]'), '[[:>:]]')
Fiddle here. But words have to be in the correct order (es. 'Acme burger' will match, 'burger Acme' won't). There's a REGEXP to match every word in any order, but it is not supported by MySql, unless you install an UDF that supports Perl regexp.
To search for a string against a text collection use MATCH() and AGAINST()
SELECT * FROM table WHERE MATCH(title) AGAINST('+Acme burger*')
or why not RLIKE
SELECT * FROM table WHERE TITLE RLIKE 'Acme|burger'
or LIKE searching an array, to have a compilation of $keys
$keys=array('Acme','burger','pound');
$mysql = array('0');
foreach($keys as $key){
$mysql[] = 'title LIKE %'.$key.'%'
}
SELECT * FROM table WHERE '.implode(" OR ", $mysql)
What you need to do is construct a SQL such that, for example:
select * from table where title like "%Acme%" and title like "%burger%"
In short: split the string and create one like for each part.
It might also work with replacing spaces with %, but I'm not sure about that.
The best thing is thing use perform union operation by splitting your search string based on whitespaces,
FOR Acme 5 pound,
SELECT * FROM TABLE WHERE TITLE LIKE '%ACME 5 POUND%'
UNION
SELECT * FROM TABLE WHERE TITLE LIKE '%ACME%'
UNION
SELECT * FROM TABLE WHERE TITLE LIKE '%5%'
UNION
SELECT * FROM TABLE WHERE TITLE LIKE '%POUND%'
Find out a way to give the first query a priority. Or pass the above one as four separate queries with some priority. I think you are using front end tp pass query to data bases, so it should be easy for you.
<?php
$search_term = 'test1 test2 test3';
$keywords = explode(" ", preg_replace("/\s+/", " ", $search_term));
foreach($keywords as $keyword){
$wherelike[] = "title LIKE '%$keyword%' ";
}
$where = implode(" and ", $wherelike);
$query = "select * from table where $where";
echo $query;
//select * from table where title LIKE '%test1%' and title LIKE '%test2%' and title LIKE '%test3%'