I'm running the following code in PHP to generate the random list of movies from the database but since value of genere is an array it is just capturing the first value of the array.
How can I modify the query so that I can get all the values of genere in comma separated line.
$q = "SELECT *
FROM
title
INNER JOIN title_genere ON (title.id = title_genere.id_title)
INNER JOIN genere ON (title_genere.id_genere = genere.id)
ORDER BY RAND()
LIMIT 8";
$result = mysql_query($q);
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$title = $row['title'];
$year = $row['year'];
$poster = $row['poster'];
$poster = str_replace("./", "lib/", $poster);
$genere = $row['genere'];
echo "<div id='a'>";
echo "<div id='b'>".$title.'</div>';
echo "<div id='c'>".$year.'</div>';
echo "<div id='d'><a href='select.php?movieid=$id'><img src='$poster' alt='' border='1' align='center' width='214' height='314' /></a></div>";
echo "<div id='e'>".$genere.'</div>';
echo "</div>";
//var_dump($genere);
}
Try this one:
$q = "SELECT
*,
GROUP_CONCAT(CAST(title_genere AS BINARY) SEPARATOR ',') AS generes
FROM
title
INNER JOIN title_genere ON (title.id = title_genere.id_title)
INNER JOIN genere ON (title_genere.id_genere = genere.id)
ORDER BY RAND()
GROUP BY title.id
LIMIT 8";
This should select a comma-separated list on generes into the key generes. For more information see the manual at http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
Don't use GROUP_CONCAT/GROUP BY, it causes overhead.
First, select your 8 random titles (from the titles table only) into an associative array indexed by title id. Let's name it $idx.
Next, prepare the id list, say, as $ids variable.
Then, run the query
SELECT
title_genere.id_title
, genre.genre
FROM
title_genre
INNER JOIN genre ON title_genere.id_genere = genere.id
WHERE
title_genere.id_title IN ($ids)
ORDER BY
genre
and harvest genre values in lists in $idx:
$idx[$row['id_title']]['genres'][] = $row['genre']
Finally, generate HTML from $idx.
Sorted out. I use below code to generate what I want. Thanks everyone for the help
SELECT
title.id,
title.title,
GROUP_CONCAT(genere SEPARATOR ' | ') AS genere,
title.`year`,
title.poster
FROM
title
INNER JOIN title_genere ON (title.id = title_genere.id_title)
INNER JOIN genere ON (title_genere.id_genere = genere.id)
GROUP BY
title.id,
title.title,
title.`year`,
title.poster
ORDER BY
RAND()
LIMIT 8
Related
I have a problem with some php code. So, when I write some text inside search box I should get more results, but I only get 1. This happened to my when I added second query with INNER JOIN. I have no idea why I'm getting only 1 result instead of more, anyone can help?
When I remove second query, it shows me all results.
$STH = $DBH->prepare('SELECT * FROM tv_shows WHERE title like :q ORDER BY title ASC LIMIT 5');
$STH->setFetchMode(PDO::FETCH_OBJ);
$STH->execute(array(
':q' => "%$q%"
));
if($STH->rowCount()) {
while($row = $STH->fetch()) {
$poster = $row->poster;
$mtitle = $row->title;
$mrd = $row->release_date;
$mid = $row->id;
$genres = "";
$STH = $DBH->prepare('SELECT g.title from genres g INNER JOIN tv_show_genres tg ON g.id = tg.genre_id INNER JOIN tv_shows t ON t.id = tg.tv_show_id WHERE t.id = :tid');
$STH->setFetchMode(PDO::FETCH_OBJ);
$STH->execute(array(
':tid' => $mid
));
if($STH->rowCount()) {
while($row = $STH->fetch()) {
$genres .= $row->title.", ";
}
echo
'<li>
<span class="search-poster"><img src="'.$poster.'"></span>
<span class="search-title">'.$mtitle.' ('.$mrd.')</span>
<span class="search-genre">'.substr($genres,0,-2).'</span>
</li>';
}
}
}
You're using the same variable $STH for both queries. So when the outer loop gets back to the
while ($row = $STH->fetch())
line, $STH now refers to the second query. Since you've reached the end of the results from that query, calling fetch() here returns false, so this loop ends as well.
Just use different variable names, e.g. $show_STH and $genre_STH.
However, an even better solution is to use a single query.
SELECT s.poster, s.title AS show_title, s.release_date, g.title AS genre_title
FROM (SELECT *
FROM tv_shows
WHERE title like :q
ORDER BY title ASC
LIMIT 5) AS s
INNER JOIN tv_show_genres tg ON s.id = tg.tv_show_id
INNER JOIN genres g ON tg.genre_id = g.id
ORDER BY s.title
Most of the time when you find yourself performing queries in nested loops like this, you can replace it with a single query that joins the two queries.
I have two tables. Player and Stats. In player is username and id. In stats is honor and id. IDs are same in both tables. One player, one id. I would like to order stats by honor and echo it together with username to the table.
Here is my try, but i can't do anything with order.
Player counter is count of player. +1 reason is that it starts from 2
$getPlayerCounter = mysql_query("SELECT `id` FROM `player`");
$playerCounter = mysql_num_rows($getPlayerCounter);
for ($i = 2; $i <= $playerCounter + 1; $i++) {
$username = mysql_query("SELECT `player`.*, `stats`.* FROM `player` INNER JOIN `stats` ON `player`.`id`=$i AND `stats`.`id`=$i") or die(mysql_error());;
$fetch = mysql_fetch_assoc($username);
echo "<tr>";
echo "<td>".$fetch['username']."</td>";
echo "<td>".$fetch['honor']."</td>";
echo "</tr>";
}
Without using your loop. How about a solution where you query a sorted list already? Kind of like:
SELECT * FROM player p
JOIN stats s on p.id = s.id
ORDER BY s.honor DESC
Where honor is the name of your column for the stats value (hopefully it's a column you can sort like a number).
You will get an array of rows that is ordered by the stats value in descending order (maximum value on top). Now you can just fetch row by row in the order it is in the fetched array.
You walk through the array doing this:
$result = mysql_query(the_query_above);
while ($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row['username']."</td>";
echo "<td>".$row['honor']."</td>";
echo "</tr>";
}
I have my table that one of my column shows empty. It has the column of Id, Date, Cust name, Product + Qty, and amount. But only in Product + Qty shows empty even it has data in database.
PHP code
<?php
include('connect.php');
$start = isset($_GET['d1']) ? $_GET['d1'] : '';
$end = isset($_GET['d2']) ? $_GET['d2'] : '';
if(isset($_GET['submit']) && $_GET['submit']=='Search')
{
$result = mysql_query(
"SELECT
t1.qty,
t2.lastname,
t2.firstname,
t2.date,
t3.name,
t2.reservation_id,
t2.payable FROM prodinventory AS t1
INNER JOIN reservation AS t2
ON t1.confirmation=t2.confirmation
INNER JOIN products AS t3
ON t1.room=t3.id
WHERE str_to_date(t2.date, '%d/%m/%Y') BETWEEN
str_to_date('$start', '%d/%m/%Y') AND
str_to_date('$end', '%d/%m/%Y')
GROUP BY t2.confirmation") or die(mysql_error());
while ($row = mysql_fetch_array($result)){
echo'<tr class="record">';
echo '<td>'.$row['reservation_id'].'</td>';
echo '<td>'.$row['date'].'</td>';
echo '<td>'.$row['firstname'].' '.$row['lastname'].'</td>';
echo '<td><div align="left">';
$rrr=$row['confirmation'];
$results = mysql_query("SELECT * FROM prodinventory where confirmation='$rrr'");
while($row1 = mysql_fetch_array($results))
{
$roomid=$row1['room'];
$resulta = mysql_query("SELECT * FROM products where id='$roomid'");
while($rowa = mysql_fetch_array($resulta))
{
echo $rowa['name'].' x';
}
echo ' '.$row1['qty'].'<br>';
}
echo '<td>'.'PHP ' . number_format(floatval($row['payable']));
}
?>
Hmmmm I have deleted my answer but noone tried so...
I think this echo ' '.$row1['qty'].'<br>'; is the row you asked about. And all this looks like a typo. If this is the case:
You have no confirmation in the SELECT clause (it's used only in JOIN and GROUP BY) and it possible your $rrr to be blank. Echo it to be sure there is a value.
Check does your query works and return results. Echo the query string (or take it from the mysql log file) and test it.
You have SELECT *. Is the field name 'qty' correct in a case-sensivity environment? 'Qty' may be different and the query may work but you don't get the result.
i think that's because you have inner join and maybe the intersection tables have no data
try to do left join first if it works
insure that all of tables have data in it
I have this snippet that shows all taxonomy list in the site, that belongs to a specific vocabulary.
Instead of printing the whole list, how do I just print the terms that belong to the node I'm actually loading?
I have a Drupal 7 installation.
This is how I print the id of the node I´m at: <?php print $node->nid;?>
<?php
$vid = 11; //vocabulary id
$query = "SELECT tid, name, count
FROM (
SELECT td.tid AS tid, name, COUNT(td.tid) AS count
FROM taxonomy_term_data AS td
JOIN taxonomy_index AS tn
ON td.tid = tn.tid
JOIN node AS n
ON n.nid = tn.nid
WHERE td.vid = ". $vid ."
AND n.status = 1
GROUP BY td.tid
ORDER BY count DESC
) AS t
ORDER BY name ASC";
$result = db_query($query);
foreach($result as $term) {
if ($term->count > 0) {
echo l($term->name, "taxonomy/term/$term->tid").' ('.$term->count.')'.'<br/>';
}
}
?>
I would suggest not to run extra query for this.
This information should be available in $node object.
Just print it [print_r($node) ] and see what exactly is the taxonomy object name($node->taxonomy) & how taxonomy information is structured & use that to display category on node page or node teaser.
On other pages, you can use node_load to 1st load the node and then do the same thing.
sumoand's answer is more optimal in this case, however for some sql practicing here's the exact solution the way you imagined:
<?php
$vid = 11; //vocabulary id
$query = "SELECT tid, name, count
FROM (
SELECT td.tid AS tid, name, COUNT(td.tid) AS count
FROM taxonomy_term_data AS td
JOIN taxonomy_index AS tn
ON td.tid = tn.tid
JOIN node AS n
ON n.nid = tn.nid
WHERE td.vid = ". $vid ."
AND n.status = 1
AND n.nid = ".$node->id."
GROUP BY td.tid
ORDER BY count DESC
) AS t
ORDER BY name ASC";
$result = db_query($query);
foreach($result as $term) {
if ($term->count > 0) {
echo l($term->name, "taxonomy/term/$term->tid").' ('.$term->count.')'.'<br/>';
}
}
?>
I have this query which gives me the transactions for a user, and the output is a table with the information. There is this row named basket_value which contains some numbers, and I need to get the sum of those numbers. Could you please help me?
$query3 = 'SELECT users.first_name,users.last_name,users.phone,
retailer.date, SUM(retailer.basket_value),
retailer.time,retailer.location,retailer.type_of_payment
FROM users ,retailer
WHERE users.user_id="'.$id_user.'"
AND users.user_id=retailer.user_id GROUP BY users.user_id';
$result3 = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result3)) {
echo "Total ". $row['user_id']. " = $". $row['SUM(basket_value)'];
echo "<br />";
}
I suppose that also your query have some problem and suppose that you have an id to retrieve users, I would do in that way
$query3 = 'SELECT users.user_id,users.first_name,users.last_name,
users.phone, retailer.date,
SUM(retailer.basket_value) as total_sum,
retailer.time,retailer.location,retailer.type_of_payment
FROM users ,retailer WHERE users.user_id="'.$id_user.'"
AND users.user_id=retailer.user_id
GROUP BY users.user_id,users.first_name,users.last_name,
users.phone, retailer.date,retailer.time,retailer.location,
retailer.type_of_payment '
$result = $mysqli->query($query3);
Now if you want the sum for each user:
while ($row = $result->fetch_row()) {
echo "Player: ".$row['user_id']." total: ".$row['total_sum'];
}
If you want the WHOLE GLOBAL sum, you have to way:
Modify your query in that way:
SELECT SUM(retailer.basket_value) as total_sum
FROM retailer
Sum into while loop like: $total += $row['total_sum'];
You're missing a GROUP BY on your query. You most likely want to add GROUP BY users.user_id
Try this query:
SELECT u.first_name, u.last_name, u.phone, SUM(r.basket_value) as total_sum
FROM users u
JOIN retailers r
ON u.user_id = r.user_id
WHERE u.user_id="'.$id_user.'"
GROUP BY u.user_id
You can omit all other columns in the select list and only have the sum() aggregate run on the set to avoid the GROUP BY clause.
$query3 = 'SELECT SUM(retailer.basket_value) as total_sum
FROM users ,retailer WHERE users.user_id="'.$id_user.'"
AND users.user_id=retailer.user_id';