PHP search box issuse - php

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.

Related

Autocomplete 2 queries

I'm using autocomplete for my panel and get stuck with queries. I'm getting products from prestashop database and do the following (example with 1 query):
$return_arr = array();
if ($ps_DB_con) {
$ac_term = "%".$_GET['term']."%";
$query = "SELECT ps_product.id_product
AS id_product, ps_product.id_manufacturer
AS producent_id, ps_manufacturer.name
AS producent, ps_product_shop.price
AS cena, ps_product_shop.active
FROM ps_product
LEFT JOIN ps_product_shop ON ps_product.id_product=ps_product_shop.id_product
LEFT JOIN ps_manufacturer ON ps_product.id_manufacturer=ps_manufacturer.id_manufacturer
WHERE ps_product.id_product LIKE :term";
$result = $ps_DB_con->prepare($query);
$result->bindValue(":term",$ac_term);
$result->execute();
/* Retrieve and store in array the results of the query.*/
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$return_arr[] = array('id_product' => $row['id_product'], 'producent' => $row['producent'], 'label' => "{$row['id_product']}");
}
echo json_encode($return_arr);
I would like to put 2nd query to this and join results to return_arr[] in while loop.
Select ps_feature_value_lang.value as szerokosc from ps_feature_value_lang
left join ps_feature_product on ps_feature_value_lang.id_feature_value= ps_feature_product.id_feature_value
left join ps_feature_lang on ps_feature_product.id_feature=ps_feature_lang.id_feature
where ps_feature_product.id_product LIKE :term and ps_feature_product.id_feature='17'
Select ps_feature_value_lang.value as profil from ps_feature_value_lang
left join ps_feature_product on ps_feature_value_lang.id_feature_value= ps_feature_product.id_feature_value
left join ps_feature_lang on ps_feature_product.id_feature=ps_feature_lang.id_feature
where ps_feature_product.id_product LIKE :term and ps_feature_product.id_feature=18
How can I join those queries into one?

Removing redundant SQL queries (in PHP) by using JOIN

I am trying to clean up my SQL queries and use JOIN in just ONE where I once used TWO queries.
Here is former code (in PHP):
$cat = "books"; // as a test
$query = "SELECT category, cat_id FROM master_cat WHERE category = '{$cat}'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$cat_id = $row['cat_id'];
}
$sql = mysql_query("SELECT item, spam, cat_id FROM items WHERE cat_id = ' " . $cat_id . "' ORDER BY TRIM(LEADING 'The ' FROM item) ASC;");
while ($row = mysql_fetch_assoc($sql))
if ($row['spam'] < 2)
$output[] = $row;
print(json_encode($output)); // added!
I am trying to just remove the top query and use a JOIN. The updated SQL statement is this:
EDIT: I made a mistake in original question. Basically user input gives us $cat = "something". There is "something" in master_cat table with a cat_id. That cat_id is also in the items table. That is where I need the tables to connect -- and the WHERE clause needs to incorporate "$cat"
UPDATED QUERY:
$result = mysql_query("SELECT i.item, i.spam, mc.cat_id AS Category
FROM items as i
INNER JOIN master_cat as mc
ON i.cat_id = mc.cat_id
WHERE i.cat_id = '{$cat}'
ORDER BY TRIM(LEADING 'The ' FROM i.item) ASC;");
then:
while ($row = mysql_fetch_assoc($result))
if ($row['spam'] < 2)
$output[] = $row;
I receive this in the browser:
null.
Can someone guide me on how to properly use JOIN which I know will REALLY clean things up here and make more efficient coding. I just watched a tutorials but still am not quite getting it.
HERE IS FINAL CODE THAT WORKS
$cat = $_POST['category']; // yes, yes, injection. this is just the short version.
$result = mysql_query("SELECT i.item, i.cat_id, i.spam, mc.cat_id, mc.category, TRIM(LEADING 'The ' FROM i.item) as CleanItem
FROM items as i
INNER JOIN master_cat as mc
ON i.cat_id = mc.cat_id
WHERE mc.category = '{$cat}'
ORDER BY CleanItem ASC;");
while ($row = mysql_fetch_assoc($result))
if ($row['spam'] < 2)
$output[] = $row;
You have reference the items table by its full name in the WHERE clause, you should be using the alias you created (i).
You also have an ambiguous column reference item in your ORDER BY clause.
Try changing the last two lines to:
WHERE i.cat_id = '{$cat_id}'
ORDER BY TRIM(LEADING 'The ' FROM i.item) ASC
You should also inspect mysql_error() to get a string description of the error, which would have pointed you straight to the problem.
$sql = "SELECT i.item, i.spam, mc.cat_id AS Category
FROM items as i
INNER JOIN master_cat as mc
ON i.cat_id = mc.category
WHERE items.cat_id = '{$cat_id}'
ORDER BY TRIM(LEADING 'The ' FROM item) ASC";
Since you aliased it you have to keep it as aliased: fix the second to last line:
WHERE i.cat_id = '{$cat_id}'
Try this one:
$sql = "SELECT i.item, i.spam, mc.cat_id AS Category
FROM items as i
INNER JOIN master_cat as mc ON i.cat_id = mc.cat_id
WHERE i.cat_id = '{$cat_id}'
ORDER BY TRIM(LEADING 'The ' FROM item) ASC";
If you alias items as i, you should use i everywhere else. Besides, mc.category does not seem to exist so I replaced it with mc.cat_id. What does mysql_error say?
You are probably getting false as your response to the initial query and not a result set
You should join on i.cat_id = mc.cat_id
You should also probably perform your i.item cleaning (i.e. removing 'The ') in the select statement (even as a seperate field if you need to keep i.item intact) and then order by that field.
You should reference i.cat_id = '{$cat_id]}', not items.cat_id

Join MySQL Table then filter result as column name

here is my code i am using to fetch mysql result from 4 different tables
SELECT DISTINCT c.title as CourseTitle, t.title as TopicTitle, l.title as LessonTitle, r.title as ResourceTitle, r.location, r.type, r.duration
FROM j17_lessons l, j17_topics t, j17_courses c, j17_resources r
WHERE
CONCAT(c.title, t.title, l.title, r.title, r.type, r.location) LIKE '%Fatih%'
AND c.id = t.course_id
AND l.topic_id = t.id
AND r.lesson_id = l.id
ORDER BY c.title, t.id, l.id, r.id;
Here is screen shot of my fetch result
http://i40.tinypic.com/2v1w0ib.png
Now what i need is to create a HTML Tables for each 'CourseTitle' in database.
Using SQL statement and PHP Code i can get result for first query but i need a second query to split table foreach 'CourseTitle'
/* connect to the db */
$connection = mysql_connect('localhost','root','123');
mysql_select_db('alhudapk',$connection);
/* show tables */
$result = mysql_query('SELECT DISTINCT c.title as CourseTitle, t.title as TopicTitle, l.title as LessonTitle, r.title as ResourceTitle, r.location, r.type, r.duration
FROM j17_lessons l, j17_topics t, j17_courses c, j17_resources r
WHERE
CONCAT(c.title, t.title, l.title, r.title, r.type, r.location) LIKE '%Taleem%'
AND c.id = t.course_id
AND l.topic_id = t.id
AND r.lesson_id = l.id
ORDER BY c.title, t.id, l.id, r.id',$connection) or die('cannot show tables');
while($tableName = mysql_fetch_row($result)) {
$table = $tableName[0];
echo '<h3>',$table,'</h3>';
$result2 = mysql_query('SELECT '.$table . 'AS' .$table);
if(mysql_num_rows($result2)) {
Please guide me to build a correct and better code
What I would do is put the database results into a big array structure with the data arranged in the same sort of order it should be printed out. This makes maintaining the code a bit easier.
// run the query as you did in the question
$courses = array();
// use mysql_fetch_assoc as it makes the code clearer
while($row = mysql_fetch_assoc($result)) {
$ct = $row['CourseTitle'];
// Found a new Course Title? If so create an array to put the data rows in
if(!isset($courses[$ct]))
$courses[$ct] = array();
// add this row to the end of its course array
$courses[$ct][] = $row;
}
// now print the results out
foreach($courses as $title =>$course) {
echo "<h3>$title</h3>";
echo "<table>";
foreach($course as $line) {
echo "<tr><td>" . $line['TopicTitle'] . "</td><td>"
. $line['LessonTitle'] . "</td></tr>";
echo "</table>";
}
The code above is only printing out the first 2 columns
, but if you can get it to work you should be able to add the rest quite easily.
add:
GROUP BY c.title
to the end of your SQL statement.

PHP MYSQL query - Strip away columns from response

Is it possible to strip away columns from the response I get in a query where I join 3 tables and need more or less all columns for the query itself so that some columns aren't visible in the response?
This is the query I have:
$sth = mysql_query("
SELECT
tbl_subApp2Tag.*,
tbl_subApp.*,
tbl_tag.*
ISNULL(tbl_userDeviceNOTTag.userDevice_id) AS selected
FROM tbl_subApp2Tag
LEFT JOIN tbl_subApp
ON tbl_subApp.id = tbl_subApp2Tag.subApp_id
AND tbl_subApp.subApp_id = '".$sub."'
LEFT JOIN tbl_tag
ON tbl_tag.id = tbl_subApp2Tag.tag_id
LEFT JOIN tbl_userDeviceNOTTag
ON tbl_userDeviceNOTTag.tag_id = tbl_tag.id
AND tbl_userDeviceNOTTag.userDevice_id = '".$user."'
WHERE tbl_subApp2Tag.subApp_id = tbl_subApp.id
ORDER BY tbl_tag.name ASC ");
if(!$sth) echo "Error in query: ".mysql_error();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
You do not need to include columns in the result table, just because they are referenced elsewhere in the query. Just select the columns that you need.

add value to result from mysql query that will be JSON encoded in PHP?

I would like to add a value to each row that I get from my query depending on if a row exist in another table. Is there a smart way to achieve this?
This is the code I have:
$sth = mysql_query("SELECT tbl_subApp2Tag.*, tbl_tag.* FROM tbl_subApp2Tag LEFT JOIN tbl_tag ON tbl_subApp2Tag.tag_id = tbl_tag.id WHERE tbl_subApp2Tag.subApp_id = '".$sub."' ORDER BY tbl_tag.name ASC");
if(!$sth) echo "Error in query: ".mysql_error();
while($r = mysql_fetch_assoc($sth)) {
$query = "SELECT * FROM tbl_userDevice2Tag WHERE tag_id='".$r['id']."' AND userDevice_id='".$user."'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result)) {
$r['relation'] = true;
$rows[] = $r; //Add 'relation' => true to this row
} else {
$r['relation'] = false;
$rows[] = $r; //Add 'relation' => false to this row
}
}
print json_encode($rows);
Where the //Add ... is, is where I would like to insert the extra value. Any suggestions of how I can do this?
I'm still a beginner in PHP so if there are anything else that I have missed please tell me.
EDIT: Second query was from the wrong table. This is the correct one.
Edited Edited below query to reflect new information because I don't like leaving things half-done.
$sth = mysql_query("
SELECT
tbl_subApp2Tag.*,
tbl_tag.*,
ISNULL(tbl_userDevice2Tag.userDevice_id) AS relation
FROM tbl_subApp2Tag
LEFT JOIN tbl_tag
ON tbl_tag.id = tbl_subApp2Tag.tag_id
LEFT JOIN tbl_userDevice2Tag
ON tbl_userDevice2Tag.tag_id = tbl_tag.id
AND tbl_userDevice2Tag.userDevice_id = '".$user."'
WHERE tbl_subApp2Tag.subApp_id = '".$sub."'
ORDER BY tbl_tag.name ASC
");
Though the above feels like the LEFT JOIN on tbl_tag is the wrong way around, but it's hard to tell as you are vague on your eventual aim. For example, if I was to assume the following
Tags will always exist
subApp2Tag will always exist
You want to know if a record in tbl_userDevice2Tag matches the above
Then I would do the following instead. The INNER JOIN means that it won't worry about records in tbl_tag that are not on the requested subApp_id which in turn will limit the other joins.
$sth = mysql_query("
SELECT
tbl_subApp2Tag.*,
tbl_tag.*,
ISNULL(tbl_userDevice2Tag.userDevice_id) AS relation
FROM tbl_tag
INNER JOIN tbl_subApp2Tag
ON tbl_subApp2Tag.tag_id = tbl_tag.id
AND tbl_subApp2Tag.subApp_id = '".$sub."'
LEFT JOIN tbl_userDevice2Tag
ON tbl_userDevice2Tag.tag_id = tbl_tag.id
AND tbl_userDevice2Tag.userDevice_id = '".$user."'
ORDER BY tbl_tag.name ASC
");
you have to do all the job in a single query.
Why can't you just $r['append'] = "value"; before adding $r to the array?

Categories