pdo add value to sql result - mysql

I use code below to get data from database
if( !empty( $books_ids ) )
{
$books_ids_in = implode(',', array_fill(0, count($books_ids), '?'));
$query = "SELECT
b.id,
b.`name`,
b.`year`,
GROUP_CONCAT(DISTINCT a.`name`) AS author_names,
GROUP_CONCAT(DISTINCT s.`name`) AS store_names
FROM
books AS b
LEFT JOIN books_authors AS b_a ON b.id = b_a.book_id
LEFT JOIN authors AS a ON a.id = b_a.author_id
LEFT JOIN books_stores AS b_s ON b.id = b_s.book_id
LEFT JOIN stores AS s ON s.id = b_s.store_id
WHERE
b.id IN (". $books_ids_in .")
GROUP BY b.id
ORDER BY b.id";
$stmt = $conn->prepare($query);
foreach ($books_ids as $k => $id) {
$stmt->bindValue(($k+1), $id);
}
$stmt->execute();
$results = $stmt->fetchAll();
}
and as I use $book id for this purpose, I would like to add some parameter in result to show that, for example, param = "book" for every row. Is there any way to do that?

Just pass it the string and alias it as a column. Though since you know the value passed in in code and display the values though code...... I'm not sure why you need this... as the value is available to you in the code when being displayed.
$query = "SELECT
b.id,
b.`name`,
b.`year`,
GROUP_CONCAT(DISTINCT a.`name`) AS author_names,
GROUP_CONCAT(DISTINCT s.`name`) AS store_names,
'". $param."' as forEveryRow
FROM
books AS b
LEFT JOIN books_authors AS b_a ON b.id = b_a.book_id
LEFT JOIN authors AS a ON a.id = b_a.author_id
LEFT JOIN books_stores AS b_s ON b.id = b_s.book_id
LEFT JOIN stores AS s ON s.id = b_s.store_id
WHERE
b.id IN (". $books_ids_in .")
GROUP BY b.id
ORDER BY b.id";

Related

MySQL JOIN Multiple tables not working

I'm not sure why this isn't working. If I join either table separately, it comes back with the appropriate results, but when I try to join them both, I get 0 results. (car_id and boat_id are both primary keys on their tables.)
$query = "SELECT
*
FROM
posted c
JOIN posted_car e on c.car_id = e.car_id
JOIN posted_boat g on c.boat_id = g.boat_id
WHERE
c.posted = 'posted'
ORDER BY date DESC LIMIT 0, 30";
$resultBoth = mysql_query($query, $db) or die(mysql_error($db));
Might be worth noting that when I do
LEFT JOIN posted_car e on c.car_id = e.car_id
RIGHT JOIN posted_boat g on c.boat_id = g.boat_id
I get results as if I had only joined the posted_boat table. If anyone could point me in the right direction...it would be much appreciated.
you are using JOIN that might be a problem . you should use left outer join to get proper result . check following syntax :
$query = "SELECT *
FROM
posted c
left OUTER JOIN posted_car e on c.car_id = e.car_id
left OUTER JOIN posted_boat g on c.boat_id = g.boat_id
WHERE c.posted = 'posted'
ORDER BY date DESC LIMIT 0, 30";
$resultBoth = mysql_query($query, $db) or die(mysql_error($db));

Custom query results generate code

Simple question. I have the following custom query. How do I make it generate a html list of the array via "echo?"
$q_result = $wpdb->get_col("SELECT DISTINCT {$wpdb->terms}.name FROM {$wpdb->terms}
INNER JOIN {$wpdb->term_taxonomy} ON {$wpdb->term_taxonomy}.term_id = {$wpdb->terms}.term_id
INNER JOIN {$wpdb->term_relationships} ON {$wpdb->term_taxonomy}.term_taxonomy_id = {$wpdb->term_relationships}.term_taxonomy_id
WHERE {$wpdb->term_taxonomy}.taxonomy = 'series' AND {$wpdb->term_relationships}.object_id IN (
SELECT object_id FROM {$wpdb->term_relationships}
INNER JOIN {$wpdb->term_taxonomy} ON {$wpdb->term_taxonomy}.term_taxonomy_id = {$wpdb->term_relationships}.term_taxonomy_id
WHERE {$wpdb->term_taxonomy}.taxonomy = 'media_type' AND {$wpdb->term_taxonomy}.term_id = '16'
ORDER BY {$wpdb->terms}.term_order DESC
) ORDER BY {$wpdb->terms}.term_order ASC");
You can just iterate through the array with a foreach -
foreach( $q_result as $result ){
echo "<a href='/series/".$result."/>".$result."</a>";
}
If you want it to display HTML as well, you will have to echo the proper HTML tags. The above will sort of work for links to the term - the format is TAXONOMY/TERM_SLUG however you are only returning the name, you need to get the name and the slug using get_results() to do it properly.
Reformatted example using table aliases, returning the term and slug:
$sql = <<<SQL
SELECT DISTINCT t.name, t.slug
FROM {$wpdb->terms} t
INNER JOIN {$wpdb->term_taxonomy} tt
ON tt.term_id = t.term_id and tt.taxonomy = 'series'
INNER JOIN {$wpdb->term_relationships} tr
ON tt.term_taxonomy_id = tr.term_taxonomy_id
WHERE tr.object_id IN (
SELECT object_id
FROM {$wpdb->term_relationships} tr2
INNER JOIN {$wpdb->term_taxonomy} tt2
ON tt2.term_taxonomy_id = tr2.term_taxonomy_id AND tt2.taxonomy = 'media_type' AND tt2.term_id = '16'
ORDER BY {$wpdb->terms}.term_order DESC
)
ORDER BY {$wpdb->terms}.term_order ASC
SQL;
$terms = $wpdb->get_results( $sql );
for ( $terms as $term ){
echo "<a href='/series/{$term->slug}/'>{$term->name}</a><br/>";
}

limit results for wpdb query

this code displays the tags from current category only but, it gets all the tags (hundreds) so, i need to limit the number of returned results and make em random.
How to make this query get only 20 results randomly ?
/* Retrieve all tags from posts in selected categories */
$cats = array('beaches','mountains'); // Must be an array even if only one category
$cats_string = "'" . implode($cats,"','") . "'";
$sql = <<<EOSQL
SELECT DISTINCT t.*
FROM $wpdb->posts p
JOIN $wpdb->term_relationships tr ON p.ID = tr.object_id
JOIN $wpdb->term_taxonomy tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id
AND tt.taxonomy = 'post_tag')
JOIN $wpdb->terms t ON tt.term_id = t.term_id
WHERE
p.ID IN (
SELECT p2.ID
FROM $wpdb->posts p2
JOIN $wpdb->term_relationships tr2 ON p2.ID = tr2.object_id
JOIN $wpdb->term_taxonomy tt2 ON (tr2.term_taxonomy_id = tt2.term_taxonomy_id AND tt2.taxonomy = 'category')
JOIN $wpdb->terms t2 ON (tt2.term_id = t2.term_id AND t2.name IN ($cats_string))
WHERE p2.post_type = 'post'
AND p2.post_status = 'publish'
AND p2.post_date <= NOW()
)
EOSQL;
$terms = $wpdb->get_results($sql);
// print_r($terms);
echo "<br />";
foreach ($terms as $term) {
echo "ID:$term->term_id NAME:$term->name SLUG:$term->slug<br />";
}
Thanks
You can try an ORDER BY RAND() LIMIT 20, depending on your table size this can run in decent times. See here some details on when to avoid the order by rand() logic. Like suggested, in the specified post, the other approach is to retrieve all the entries and randomly select 20 entries, in PHP rather then using mysql.

mysql syntax how to add a third table to $query

I have code:
$query = "SELECT a.*, c.name as categoryname, c.id as categoryid
FROM #__table_one as a
LEFT JOIN #__table_two c ON c.id = a.catid";
$query .= " WHERE a.published = 1
AND a.access <= {$aid}
AND a.trash = 0
AND c.published =
AND c.access <= {$aid}
AND c.trash = 0";
I would like to add a third table ('__some_table') for the parts of the query where a.publish, a.access and a.trash. In other words, I want these fields to be retrieved from another table, not "#__table_one", but I do not know how to incorporate the #__some_table into the current query
I imagine the JOIN command can help me, but I do not know how to code mysql
//not tested
$query = "SELECT a.*, c.name as categoryname, c.id as categoryid
FROM #__table_one as a
LEFT JOIN #__table_two c ON c.id = a.catid
LEFT JOIN #__table_three d ON d.id = a.some_id";

Advice on how to complete specific MySQL JOIN

I have a mysql table jobs.
This is the basic structure of jobs.
id
booked_user_id
assigned_user_id
I then also have another table, meta.
Meta has the structure:
id
user_id
first_name
last_name
Here is my php code
$sQuery = "
SELECT SQL_CALC_FOUND_ROWS job_id, job_name, priority_id, meta.first_name, date_booked
FROM jobs
LEFT JOIN (meta) on (meta.user_id = jobs.booked_user_id)
LEFT JOIN (jobs_priorities) on (jobs_priorities.id = jobs.priority_id)
$sWhere
$sOrder
$sLimit
";
$rResult = mysql_query($sQuery);
while ( $aRow = mysql_fetch_assoc( $rResult ) )
{
$sOutput .= '"'.addslashes($aRow['job_id']).'",';
}
How can I join these tables so that both booked_user_id and assigned_user_id can access meta.first_name?
When I try
$sOutput .= '"'.addslashes($aRow['first_name']).'",
nothing happens
Thanks for your advice
Tim
You can join twice:
SELECT j.id, b.first_name, a.first_name
FROM jobs j
JOIN meta b ON j.booked_user_id = b.user_id
JOIN meta a ON j.assigned_user_id = a.user_id
Nathan did the fix, but will apply it to your current SQL so you can understand it more
Lets transform your query into this:
SELECT SQL_CALC_FOUND_ROWS job_id, job_name, priority_id, date_booked
FROM jobs j
LEFT JOIN meta b ON b.user_id = j.booked_user_id
LEFT JOIN meta a ON a.user_id = j.assigned_user_id
LEFT JOIN jobs_priorities jp ON jp.id = j.priority_id
$sWhere
$sOrder
$sLimit
What I did is to use alias to method and join twice the meta, (just like what nathan did), I temporarily removed the first_name field,
Then let's add something on the SELECT so you can display both first_name
SELECT SQL_CALC_FOUND_ROWS job_id, job_name, priority_id, date_booked, b.first_name as booked_first_name, a.first_name as assigned_first_name
FROM jobs j
LEFT JOIN meta b ON b.user_id = j.booked_user_id
LEFT JOIN meta a ON a.user_id = j.assigned_user_id
LEFT JOIN jobs_priorities jp ON jp.id = j.priority_id
$sWhere
$sOrder
$sLimit
Now, we added the column booked_first_name and assigned_first_name, now you can call it on your php code like this:
$aRow['booked_first_name'] or $aRow['assigned_first_name']