I am having an issue with an sql query. Basically I have this method:
public function loadByDirectoryContact($directoryContact,$type='')
{
global $db;
$t = 'directoryprogramme';
$query = 'SELECT c.* FROM `'.$t.'` c ';
$query .= 'WHERE `c`.`presenters` = '.$directoryContact->getId().' ';
$query .= 'OR `c`.`staff` = '.$directoryContact->getId().' ';
if($type!=""){
$query .=" AND c.type='".$type."' ";
}
$query .= QueryBuilder::orderBy('name','asc');
echo $query; die();
$db->query($query,$t);
while($db->next($t))
{
$node = new Programme();
$node->setId($db->get('id',$t));
$node->setName($db->get('name',$t));
$node->setBroadcastTime($db->get('broadcast_time',$t));
$node->setDescription($db->get('description',$t));
$node->setDays($db->get('days',$t));
$node->setSubjects($db->get('subjects', $t));
$node->setStaff($db->get('staff',$t));
$node->setPresenters($db->get('presenters',$t));
$directoryCompany = new DirectoryCompany($db->get('directorycompany_id',$t));
$node->setDirectoryCompany($directoryCompany);
$node->setContributors($directoryContact);
$node->setType($db->get('type',$t));
$this->nodes->add($node);
}
}
It creates a query like this:
SELECT c.*
FROM `directoryprogramme` c
WHERE `c`.`presenters` = 1234
OR `c`.`staff` = 1234
ORDER BY `name` ASC
The problem is that the presenters column stores comma seperated values so in reality it looks like this
presenters
1234,7738,5097,5100
and so for any query where the c.presenters equals any value that is not first in this column it returns no results. I am wondering if there is a way I can query so that it checks the entire String?
You can use the function FIND_IN_SET to find your value in the list:
SELECT c.*
FROM `directoryprogramme` c
WHERE FIND_IN_SET('1234',`c`.`presenters`) > 0
OR `c`.`staff` = 1234
ORDER BY `name` ASC
Remark
Consider normalizing your table design, if you can. This means a separate table for the presenters ids with one row per id.
You can also try:
SELECT c.* FROM `directoryprogramme` c WHERE `c`.`presenters` LIKE '%1234%' OR `c`.`staff` = 1234 ORDER BY `name` ASC
I believe the presenters column is in varchar.
Related
orderfood
orderfood_id food_id total_amount
foodcancel
foodcancel_id food_id status
$query = $this->db->query("SELECT * FROM order_food of LEFT JOIN `foodcancel` fc ON of.food_id = fc.food_id WHERE of.orderfood_id = '" . (int)$orderfood_id . "'");
$order_foods = $query->rows;
above is my query, what i wanted is that if there food_id inside foodcancel table , exclude it from rows, possbile to do it ?
For exclude the existing values you could try checking null for corresponding matching value
SELECT *
FROM order_food of
LEFT JOIN foodcancel fc ON of.food_id = fc.food_id
and of.food_id = your_value
WHERE fc.orderfood_id is null
anyway you should not php var in your sql code because in this way you are are risk for sqlinjection for avoid this you should take a look at prepared statement and binding param
It's very possible to do. In my logic. first, you must get all food_id on food_cancel table. Then save it into variabel and use it when you show orderFood table with adding NOT IN condition.
I've write code for you,
<?php
// Get Food Id From Cancel
$orderCancel = mysqli_query($mysqli, "SELECT * FROM `foodcancel`");
$cancelId = "";
while ($cancel = mysqli_fetch_array($orderCancel)) {
$cancelId .= $cancel["food_id"].",";
};
$cancelId = substr($cancelId, 0, -1);
// Put Food Id on Cancel Table into NOT IN Condition Database
$orderFood = mysqli_query($mysqli, "SELECT * FROM `orderfood` WHERE food_id NOT IN ($cancelId)");
while ($order = mysqli_fetch_assoc($orderFood)) {
$food[] = $order;
};
echo json_encode($food);
?>
I have this php script called title, where it is supposed to list movie details of those movies with the title matching the inputed substring. The expected output is supposed to be like in the link/picture below. I have trouble with concatenating the genres of each movies since one movie can have many genres. I have tried using the concat(), array_to_string() but still fails.
mkSQL() constructs "safe" SQL query strings by taking a query template
string and filling in printf-like slots in the template with values
supplied in subsequent arguments. The function takes a variable number
of arguments; the first is always a query template string, with the
following arguments corresponding exactly to the slots in the
template. E.g.
$id = 3012345;
$q1 = mkSQL("select * from R where id = %d",$id);
would create the query strings:
$q1: "select * from R where id = 12345"
Below are the codes, any helps and tips will be greatly appreciated, thanks!
This is the Genre Table Schema
CREATE TABLE Genre (
movie_id integer REFERENCES Movie(id),
genre GenreType,
primary key (movie_id,genre));
#!/usr/bin/php
<?php
// include the common PHP code file
require("a2.php");
$db = pg_connect("dbname=mydb");
// Check arguments
if (count($argv) < 2) exit("$usage\n");
// Get the return results
$val = $argv[1];
$q = "select m.title, m.year, m.content_rating, r.imdb_score, array_to_string(array(select g.genre FROM Genre g where g.movie_id = m.id),',')
-- concat(select g.genre FROM Genre g where g.movie_id = m.id
from Movie m JOIN Rating r ON r.movie_id = m.id
where m.title ilike %p
order by m.year, r.imdb_score desc, m.title asc";
$r = pg_query($db, mkSQL($q, $val));
// Iterate through the results and print
$i = 1;
while ($t = pg_fetch_array($r)) {
echo "$i. $t[0] ($t[1], $t[2], $t[3]) [$t[4]]\n";
$i++;
}
?>
The expected output is supposed to be in this format
Change your query like,
SELECT CONCAT(m.title, ' (', m.year, ', ', m.content_rating, ',', r.imdb_score, ') [', (SELECT array_to_string(array_agg(g.genre), ',') FROM Genre g WHERE g.movie_id = m.id), ']') movie_title
FROM Movie m JOIN Rating r ON r.movie_id = m.id
WHERE m.title ilike %p
ORDER BY m.year, r.imdb_score desc, m.title ASC
Here, I have concat all columns into one and given it an alias movie_title. You will get the movie name as per your specified format.
For achieving this, you can use the group_concat function in your mysql script.
This will concatenate your respective column via comma(,).
I need to check if my comma separated value exists in Database. And my database also storing in comma separated.
My string is saved as "1,2,3,4,5" in database.
My search string is $bloggerscat = "2,5"
I have tried
(B.category_id LIKE ('%,$bloggerscat') OR B.category_id LIKE ('%$bloggerscat,%') OR B.category_id = '".$bloggerscat."')
Not getting proper result. Please help me.
Advanced thanks...
You can do something like this,
$bloggerscat = '2,5'; // Your input here (string)
$set = explode(',',$bloggerscat); // get the numbers in $set array
$query = 'SELECT * FROM `table` WHERE '; // construct query
foreach ($set as $search)
{
$query .= "FIND_IN_SET($search, column_name) OR "; // append every time for set
}
$query = rtrim($query, ' OR'); // remove last OR
echo $query; // test
Will produce
SELECT * FROM `table` WHERE FIND_IN_SET(2, column_name) OR FIND_IN_SET(5, column_name)
Will give you results from column column_name where comma separated sets have value either 2 or 5.
You have to store the string as ",1,2,3,4,5," in database
then try this code
$currStr = "2,5";
$explCurrStr = explode(",",$currStr);
foreach($explCurrStr as $key=>$all){
if($key==0){
$sql.=" B.category_id LIKE ('%,".$all.",') ";
}else{
$sql.=" OR B.category_id LIKE ('%,".$all.",') ";
}
}
Hi am currently stuck here, been doing research on how to write a mysql statement for a flexible search for products and order them by relevance on a project am working on have seen a few but wasn't helpful please i need help on how to make it work, my current method doesn't work, here it is.
User types in search field and submits "iPad 3rd Generation".
My script breaks the string into words like so.
$termsExploded = array_unique(explode(' ', $term));
No i use php to create an sql query based on the number of words found.
$i = 0;
foreach ($termsExploded as $word) {
if (strlen($word)>1) {
if ($i == 0) {
$where_query = $where_query." name LIKE '%".$word."%'";
}
else{
$where_query = $where_query." OR name LIKE '%".$word."%'";
}
$i++;
}
}
The where query variable now looks like this.
name Like '%ipad%' Or name Like '%3rd%' Or name Like '%Generation%'
Now search for the products ids like so.
$IDs = "SELECT DISTINCT id FROM store_items WHERE".$where_query;
I now create a second where query based on the IDs returned like so
$where_query_s = null;
$i = 0;
foreach ($IDs as $result) {
$returnID = $result->id;
if ($i == 0) {
$where_query_s = $where_query_s." id = ".$returnID."";
}
else{
$where_query_s = $where_query_s." OR id = ".$returnID."";
}
$i++;
};
Now i select the products again based on the distinct IDs returned like so
$items = "SELECT * FROM store_items WHERE".$where_query_s;
Now this works to get the products but how can i sort it based on best match?
Assuming you want to order by the number of matches then build up another string as follows:-
ORDER BY IF(name Like '%ipad%', 1, 0) + IF(name Like '%3rd%', 1, 0) + IF(name Like '%Generation%', 1, 0) DESC
But this will be slow, and takes no account of indexing to improve performance nor of plural / singular (ie, it someone searches for 'flies' it won't rank 'fly' properly).
To put that more into code:-
$where_query = array();
$order_query = array();
foreach ($termsExploded as $word)
{
if (strlen($word)>1)
{
$where_query[] = " name LIKE '%".$word."%'"
$order_query[] = " IF(name Like '%".$word."%', 1, 0)"
}
}
$IDs = "SELECT DISTINCT id FROM store_items WHERE ".implode(' OR ', $where_query)." ORDER BY ".implode(' + ', $order_query)." DESC";
Arrange for your query to look like this:
select field1, field2, etc, count(*) records
from store_items
where blah blah blah
group by field1, field2, etc
order by records desc
If the table is MyISAM based or if it is InnoDB and the version is Mysql 5.6 or greater, then you can use full text search (see http://dev.mysql.com/doc/refman/5.6/en/fulltext-search.html)
effectively you want a query similar to
SELECT * FROM store_items WHERE MATCH (name) AGAINST ('iPad 3rd Generation')
ORDER BY MATCH (name) AGAINST ('iPad 3rd Generation')
I have 2 tables, the unique id's in each table are the same in both tables.
How do I go about joining the data from both tables together in php?
When I normally pull data I do it like this:
$get_board_array = mysql_query("SELECT * FROM posts WHERE user_id_to = '$id' ");
while($posts = mysql_fetch_array($get_board_array))
{
$post_id = $get_post['post_id'];
$html_output .= "<p>".$post_id."</p>";
}
As for pulling the data from separate tables and not getting it all mixed up, I was thinking of doing something like this:
$get_arrayA = mysql_query("SELECT * FROM tableA WHERE age = '36' ");
while($dataA = mysql_fetch_array($get_arrayA))
{
$dataA_id = $dataA['id'];
$dataA_firstName = $dataA['FirstName'];
foreach($dataA_id)
{
$get_arrayB = mysql_query("SELECT * FROM tableB where id='".$dataA_id."'");
while($dataB = mysql_fetch_array($get_arrayB))
{
$dataB_lastName = $dataB['LastName'];
$html_output .= "<p>".$dataA_firstName.$dataB_lastName"</p>";
echo $html_output;
}
}
}
Or would this be just too weird of a thing?
I know how to do it within SQL using inner join but how do I do something like that in PHP and output html?
It is because of you misguide use of wildcard (*) characters. STOP THAT !! This is what happens when arrogant php developers imagine that they do not need to learn SQL. If you need something , then select it.
SELECT
foo.foo_id,
foo.data as paramX ,
bar.type,
bar.something_else
FROM foo
INNER JOIN bar USING (foo_id)
WHERE
foo.state = 'open'
AND bar.type = 3
This (I'm just guessing the schema and your needs) could be a better query for your situation:
SELECT a.id,a.FirstName,b.LastName
FROM tableA a
JOIN tableB b ON b.id = a.id
WHERE a.age = '36'