I have a question that I can't find an answer to it.
I want the user to enter words and on every ENTER press I send the word(s) to the server to search
I need my sql to search in 3 tables:
Products table:
PRODUCT NAME, PRODUCT DESCRIPTION, PRODUCT TAGS
User table:
USERNAME, USER EMAIL
user-info table:
ADDRESS, LANGUAGE
Let's say that
$d = array('0'=>'cell phone','1'=>'lightweight','2'=>'brasil','3'=>'nokia');
I need that all the SQL will search for everything everywhere
This is the closest I have arrived, I'm looking in only one table and one coll, I have no idea what to do.
public function getAllByTags($d){
$sql = 'SELECT * FROM '.TBL_WORKS.' WHERE tags ';
for($i = 0; $i < sizeof($d);$i++){
$sql .= 'LIKE \'%'.$d[$i].'%\'';
if(sizeof($d) != 1 && $i != sizeof($d)-1 && $i != sizeof($d)){
$sql .= ' OR ';
}
}
$query = $this->db->query($sql);
foreach($query->result_array() as $row){
$q[] = $row;
}
return $q;
}
I'm sure there's an answer somewhere in google but my English is not that good (i think :/),
Thank you for your help
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE %yourstring
you can do the search above on multiple columns
and if you want to do it on multiple tables you can run 3 subqueries and use union.
see here
Related
In my app, the user can type in an indefinite amount of categories to search by. Once the user hits submit, I am using AJAX to call my PHP script to query my DB and return the results that match what the user defined for the categories.
My category column is separated as so for each row: "blue,red,yellow,green" etc.
I have two questions:
How can I pass an array to MySQL (like so: [blue,yellow,green]) and then search for each term in the categories column? If at-least one category is found, it should return that row.
Can MySQL add weight to a row that has more of the categories that the user typed in, therefor putting it further to the top of the returned results? If MySQL cannot do this, what would be the best way to do this with PHP?
Thanks for taking the time and looking at my issue.
For the part 1 you can use the function below:
<?php
function createquery($dataarray){
$query="select * from table where ";
$loop=1;
foreach($dataarray as $data)
{
$query.="col='$data'";
if(count($dataarray)<$loop-1){
$query.=' or ';
}
$loop++;
}
return $query;
}
?>
This will return the long query.
use this some like this:
mysql_query("select * from table where category in (".implode($yourarray,',').")");
1)
Arrays are not passed to a MySQL database. What's past is a query which is a string that tells the database what action you want to preform. An example would be: SELECT * FROM myTable WHERE id = 1.
Since you are trying to use the values inside your array to search in the database, you could preform a foreach loop to create a valid SQL command with all those columns in PHP, and then send that command / query to the database. For example:
$array = array('blue', 'red', 'yellow', 'green');
$sql = "SELECT ";
foreach ($array as $value)
{
$sql .= $value.", ";
}
$sql .= " FROM myTable WHERE id = 1";
IMPORTANT! It is highly recommended to used prepared statements and binding your parameters in order not to get hacked with sql injection!
2)
You are able to order the results you obtained in whichever way you like. An example of ordering your results would be as follows:
SELECT * FROM myTable WHERE SALARY > 2000 ORDER BY column1, column2 DESC
I'm trying to place one mysql select inside another one and combine the results to be displayed.
this is my code:
$allattrs = "";
$sql69 = "SELECT * FROM product_details";
$query69 = mysqli_query($db_conx, $sql69);
$login_check69 = mysqli_num_rows($query69);
if($login_check69 > 0){
while($row69 = mysqli_fetch_array($query69, MYSQLI_ASSOC)){
$FID = $row69["id"];
$sql2s = "SELECT * FROM ATTRIBUTES WHERE id='$FID'";
$query2s = mysqli_query($db_conx, $sql2s);
$login_check2s = mysqli_num_rows($query2s);
if($login_check2s > 0){
while($row2s = mysqli_fetch_array($query2s, MYSQLI_ASSOC)){
// Get member ID into a session variable
$Sid = $row2s["id"];
$attr = $row2s["attr"];
$allattrs .= ''.$attr.', ';
}
}
$product_list .= '<tr>
<td>'.$allattrs.'</td>
</tr>';
}
}
The problem i'm having is that the $allattrs returns the values but it will put everthing together.
for example:
if one attr column in mysql database has apples, and another one has oranges, when i see the results of $allattrs on my PHP page i see this:
id 1 - apples
id 2 - apples, oranges
id 3 - apples, oranges, apples, oranges
etc etc
this is in fact wrong as each attribute value needs to stay true to their own id and product_details id field!
I'm not sure what I am doing wrong to cause this.
could someone please advise on this issue?
any help would be appreciated.
The right way to write your query is using JOIN, EXISTS, or IN. I think you would find this most natural:
SELECT a.id, GROUP_CONCAT(a.attr) as attrs
FROM ATTRIBUTES a
WHERE a.id IN (SELECT id FROM product_details)
GROUP BY a.id;
This replaces a bunch of your code.
Looks like you are only interested in the the attributes then try this out instead of the first sql:
SELECT * FROM ATTRIBUTES where id IN (SELECT id FROM product_details)
You need to set $allattrs to an empty string inside your first while loop, instead of only once before.
Apart from that, you should look into the following two topics: Normalization and JOINs.
I have a HTML form that people can select some or all off to search a database for member profiles.
Some of the options are:
Male/Female
Age
Location
check boxes like intentions or interests
etc
I need to tailor a MySQL query to meet the selection the member has chosen.
I'm asking because I built a custom search like this before and it turned into a complete mess with multiple queries depending on what was selected.
Would it be best to just build one query and have parts that are added depending on what is selected?
Does anyone have a ruff example?
Database Schema:
I have a number of tables with the related information so I would need to use joins. That said everything works on one primary key PID so it would all join on this.
You could do something like this:
<?php
$whereClause = '';
if($_GET['gender'] == 'male'){
$whereClause .= ' AND gender = "M"';
}
if($_GET['age'] != ''){
$whereClause .= ' AND age = "'.$_GET['age'].'"';
}
?>
I would use an array:
$where = array();
if($_GET["gender"]!=""){
$clean = mysqli_escape_string($db, $_GET["gender"]);
array_push($where, "gender = '$clean'");
}
// etc...
$where = implode(" AND ", $where);
$sql = "SELECT * FROM table WHERE $where";
I have a table called news and with these two snippets of code, I want to create a search engine that scans through the keywords table. With one table connected and running very nicely, it would be cleaner to add an extra table to the query.
My task is to create a search engine that returns rows from the tables. The search engine is based on keywords and is great for specific terming, such as 'New York Times' but if I want to type in news, that's where all the news sites are ordered by id. But sometimes completely different terms that have the keyword 'news' will pop up quite high in the table unlike CNN because of the id. With a new table, it would be a lot easier to organize the tables. That way if a term entered is 'news', sites will be ordered by id and even if they clash on other tables, they are still ordered by id.
Though my query is a bit different than the traditional query, I don't know how to
add a table via a UNION or
with a LEFT JOIN tag of some sort.
My query is below and I would love for someone to explain: a) what's wrong simply b) tell me or paste the code below:
<?php
if( isset($_GET['k']) ){
$k = $_GET['k'];
}else{
$k = '';
}
$k = ( isset($_GET['k']) )? trim($_GET['k']) : '';
$terms = (strlen($k) > 0)? explode(' ', $k) : Array();
/* The code below is from a different part of the script */
$query = " SELECT * FROM scan WHERE ";
$terms = array_map('mysql_real_escape_string', $terms);
$i = 0;
foreach ($terms as $each) {
if ($i++ !== 0){
$query .= " AND ";
}
$query .= "keywords LIKE '%{$each}%'";
}
I don't know exactly what you want to do, but this might help :
$query = " SELECT * FROM scan, news WHERE scan.news_id = news.id AND ";
$terms = array_map('mysql_real_escape_string', $terms);
foreach ($terms as $each) {
$query .= "AND scan.keywords LIKE '%{$each}%'";
}
You make an union between two table by adding a condition in the query and selecting from the two tables. The condition is to ensure that the common column in the two tables are equals.
For a left join, read this http://www.w3schools.com/sql/sql_join_left.asp
I don't really know what you're asking. If you can clarify your question, I will provide an example for you. Thanks.
Let's put an easy example with two tables:
USERS (Id, Name, City)
PLAYERS (Id_Player, Number, Team)
And I have to do a query with a subselect in a loop, where the subselect is always the same, so I would like to divide it into two queries and put the subselect outside the loop.
I explain. What works but it is not optimize:
for($i=0;$i<something;$i++)
{
$res2=mysql_query("SELECT Team from PLAYERS WHERE Number=$i
AND Id_Player IN (SELECT Id FROM USERS WHERE City='London')");
}
What I would like to do but it doesn't work:
$res1=mysql_query("SELECT Id from USERS where City='London'");
for($i=0;$i<something;$i++)
{
$res2=mysql_query("SELECT Team from PLAYERS WHERE Number=$i
AND Id_Player IN **$res1**");
}
Thanks!
Something like this should work.
<?
$sql = "SELECT Team from PLAYERS
JOIN USERS on (Id_player=Id)
WHERE Number BETWEEN $minID AND $maxID
AND City='London'
GROUP BY Team";
$results=mysql_query($sql) or die(mysql_error());
// $results contain all the teams from London
// Use like normal..
echo "<ul>\n";
while($team = mysql_fetch_array($results)){
echo "\t<li>{$team['Team']}</li>\n";
}
echo "</ul>";
Placing SQL quires in loops can be very slow and take up a lot of resources, have a look at using JOIN in you SQL. It's not that difficult and once you've got the hang of it you can write some really fast powerful SQL.
Here is a good tutorial worth having a look at about the different types of JOINs:
http://www.keithjbrown.co.uk/vworks/mysql/mysql_p5.php
SELECT PLAYERS.*, USERS.City FROM PLAYERS, USERS WHERE USERS.City='London' AND PLAYERS.Number = $i
Not the best way to do it; maybe a LEFT JOIN, but it should work. Might have the syntax wrong though.
James
EDIT
WARNING: This is not the most ideal solution. Please give me a more specific query and I can sort out a join query for you.
Taking your comment into account, let's take a look at another example. This will use PHP to make a list we can use with the MySQL IN keyword.
First, make your query:
$res1 = mysql_query("SELECT Id from USERS where City='London'");
Then, loop through your query and put each Id field one after another in a comma seperated list:
$player_ids = "";
while($row = mysql_fetch_array($res1))
{
$player_ids .= $row['Id'] . ",";
}
$player_ids = rtrim($player_ids, ",");
You should now have a list of IDs like this:
12, 14, 6, 4, 3, 15, ...
Now to put it into your second query:
for($i = 0; $i<something; $i++)
{
$res2 = mysql_query("SELECT Team from PLAYERS WHERE Number=$i
AND Id_Player IN $player_ids");
}
The example given here can be improved for it's specific purpose, however I'm trying to keep it as open as possible.
If you want to make a list of strings, not IDs or other numbers, modify the first while loop, replacing the line inside it with
$player_ids .= "'" . $row['Id'] . "',";
If you could give me your actual query you use, I can come up with something better; as I said above, this is a more generic way of doing things, not necessarily the best.
Running query in a loop is not a great idea. Much better would be to get whole table, and then iterate through table in loop.
So query would be something like that:
"SELECT Team from PLAYERS WHERE Number BETWEEN($id, $something)
AND Id_Player IN (SELECT Id FROM USERS WHERE City='London')"
$res1=mysql_query("SELECT Id from USERS where City='London'");
for($i=0;$i<something;$i++)
{
$res2=mysql_query("SELECT Team from PLAYERS WHERE Number=$i
AND Id_Player IN **$res1**");
}
Would work, but mysql_query() returns a RESULT HANDLE. It does not return the id value. Any select query, no matter how many, or few, rows it returns, returns a result statement, not a value. You first have to fetch the row using one of the mysql_fetch...() calls, which returns that row, from which you can then extract the id value. so...
$stmt = mysql_query("select ID ...");
if ($stmt === FALSE) {
die(msyql_error());
}
if ($stmt->num_rows > 0) {
$ids = array();
while($row = mysql_fetch_assoc($stmt)) {
$ids[] = $row['id']
}
$ids = implode(',', $ids)
$stmt = mysql_query("select TEAM from ... where Id_player IN ($ids)");
.... more fetching/processing here ...
}