Autocomplete 2 queries - php

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?

Related

PHP search box issuse

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.

How to get results from mysqli_fetch_assoc with table aliases

I am pretty new to PHP and don't know how to get results from the mysqli_fetch_assoc() function if my select statement has table joins and those joins are handled with table aliases.
The code looks like following:
$sql = 'SELECT T1.update_text, T1.created_at, T2.username, T3.group_name FROM updates AS T1
INNER JOIN users AS T2 ON T2.user_id = T1.user_id_fk
INNER JOIN groups AS T3 ON T3.group_id = T1.group_id_fk
WHERE T1.user_id_fk = "1"';
And the PHP Code afterwards:
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
printf ("%s (%s)\n",$row["username"],$row["T1.created_at"]);
}
For the "username" row I am not getting an error, but nothing is displayed. For the second one I am getting an Index undefined error. (This is only a snippet of the code)
Change the SQL Query as following,
$sql = 'SELECT T1.update_text as update_text, T1.created_at as created_at, T2.username as username, T3.group_name as group_name FROM updates AS T1
INNER JOIN users AS T2 ON T2.user_id = T1.user_id_fk
INNER JOIN groups AS T3 ON T3.group_id = T1.group_id_fk
WHERE T1.user_id_fk = "1"';
then change the PHP code as following,
$result = $mysqli->query($sql);
if (mysqli_num_rows($result) > 0) {
while($row = $results->fetch_object())
{
echo $row->username.$row->created_at."<br/>";
}
}

Cannot get the proper set of data using PHP and MySQL

I need to fetch data from DB in an array using PHP and MySQL. In my case I am having 1 set of data in the given condition but the same set of data is coming multiple times. I am providing my code below.
$pro_id=$_GET['pro_id'];
$userid=$_GET['user_id'];
$sql="
SELECT s.id,
s.voucher_code,
s.merchant,
s.date,
s.receiver,
s.sender,
s.serial_no,
s.image,
s.expired_date,
s.product_id,
c.status,
c.redeem_status,
sup.supplier_id,
sup.NAME,
a.NAME AS sender_name,
v.discount,
v.discount_type,
v.voucher_amount,
p.product_name AS pro_name
FROM db_send_evoucher_code s
INNER JOIN db_code c
ON s.voucher_code = c.total_voucher_code
INNER JOIN db_supplier sup
ON s.merchant = sup.supplier_id
INNER JOIN medilink_admin a
ON s.sender = a.admin_id
INNER JOIN db_voucher_code v
ON c.voucher_code_id = v.voucher_code_id
INNER JOIN db_product_info p
ON s.product_id = p.pro_id
WHERE s.receiver = '". $userid ."'
and s.product_id = '". $pro_id ."'";
$sqlqry = mysqli_query($con, $sql);
if (mysqli_num_rows($sqlqry) > 0) {
while ($row = mysqli_fetch_array($sqlqry)) {
if ($row['discount_type'] == 'Flat') {
$distype = 1;
}
if ($row['discount_type'] == 'percentage') {
$distype = 2;
}
$data['data'][] = $data['data'][] = array("voucher_code" => $row['voucher_code'], "send_by" => $row['sender_name'], "image" => $row['image'], "expired_date" => $row['expired_date'], "supplier_name" => $row['name'], "sending_date" => $row['date'], "supplier_id" => $row['supplier_id'], "discount" => $row['discount'], "product_id" => $row['product_id'], "product_name" => $row['pro_name'], "redeem_status" => $row['redeem_status'], "voucher_amount" => $row['voucher_amount'], "discount_type" => $distype, "imagepath" => $imagepath);
echo json_encode($data, JSON_UNESCAPED_SLASHES);
}
} else {
$data['data'] = array();
echo json_encode($data);
}
Here in the given condition I have one set of data inside DB but it's coming two times. Here is my output:
{"data":[{"voucher_code":"FIFLTBH8567","send_by":"Medilink","image":"glotnzgrqbyb9_97yw155165stt9_eneoji_l.jpg","expired_date":"22-02-2016","supplier_name":"Eneoji","sending_date":"2016-02-18 16:11:35","supplier_id":"9","discount":"20","product_id":"52","product_name":"Eneoji Fomentation Therapy","redeem_status":"0","voucher_amount":"2000","discount_type":2,"imagepath":"http://li120-173.members.linode.com/crm_beta/upload/"},{"voucher_code":"FIFLTBH8567","send_by":"Medilink","image":"glotnzgrqbyb9_97yw155165stt9_eneoji_l.jpg","expired_date":"22-02-2016","supplier_name":"Eneoji","sending_date":"2016-02-18 16:11:35","supplier_id":"9","discount":"20","product_id":"52","product_name":"Eneoji Fomentation Therapy","redeem_status":"0","voucher_amount":"2000","discount_type":2,"imagepath":"http://li120-173.members.linode.com/crm_beta/upload/"}]}
You should check if there is 2 lines with the same foreign key value in one of the inner joined table.
For ex,if you have 2 rows with total_voucher_code = "FIFLTBH8567" in table db_code, even if the reste of the row is different, you'll get this kind of unexpected result.
Try to write your SELECT statement as below
SELECT DISTINCT s.id,s.voucher_code,s.merchant etc...
Use distinct in your sql, so you don't get any duplicates rows:
$sql="select distinct s.id,s.voucher_code,s.merchant,s.date,s.receiver,s.sender,s.serial_no,s.image,s.expired_date,s.product_id,c.status,c.redeem_status,sup.supplier_id,sup.name,a.name AS sender_name,v.discount,v.discount_type,v.voucher_amount,p.Product_name AS pro_name
from db_send_evoucher_code s
INNER JOIN db_code c ON s.voucher_code=c.total_voucher_code
INNER JOIN db_supplier sup ON s.merchant=sup.supplier_id
INNER JOIN medilink_admin a ON s.sender=a.admin_id
INNER JOIN db_voucher_code v ON c.voucher_code_id=v.voucher_code_id
INNER JOIN db_product_info p ON s.product_id=p.pro_Id
where s.receiver='".$userid ."' and s.product_id='".$pro_id."'";

Setting PHP Query into a nested array

I am trying to use PHP to logically store all of that data in a nested associative arrays, and then whenever I loop through the data or need to reference the data I would refer to the array pointer rather than doing new queries each time.
For example:
My query is
$query = $db->query("
SELECT
c.id campaign_id,
c.campaign_title,
c.start_date campaign_start_date,
c.end_date campaign_end_date,
cat.id category_id,
cat.category_title,
n.id nominee_id,
n.title nominee_title,
u.id voter_id,
u.fullname voter_name
FROM
campaign c
LEFT JOIN categories cat ON cat.campaign_id = c.id
LEFT JOIN category_nominees cn ON cn.category_id = cat.id
LEFT JOIN nominees n ON n.id = cn.nominee_id
LEFT JOIN category_votes cv ON cv.campaign_id = c.id
AND cv.category_id = cat.id
AND cv.nominee_id = n.id
LEFT JOIN users u on u.id = cv.user_id
WHERE
c.active = 1
ORDER BY
u.fullname,
c.campaign_title,
cat.category_order,
cat.category_title,
cn.nominee_order,
n.title
") or die(mysqli_error());
and im trying to set up the nested array like
$array = array() ;
while($row = mysqli_fetch_assoc($query)) {
$array[$row['campaign_id']] = $row['campaign_id'];
$array[$row['campaign_id']]['campaign_title'] = $row['campaign_title'];
$array[$row['campaign_id']]['campaign_start_date'] = $row['campaign_start_date'];
$array[$row['campaign_id']]['campaign_end_date'] = $row['campaign_end_date'];
$array[$row['campaign_id']]['campaign_title'] = $row['campaign_title'];
$array[$row['campaign_id']]['category_id'] = $row['category_id'];
$array[$row['campaign_id']]['category_id']['category_title'] = $row['category_title'];
}
So whenever I point to:
$array[2][3]['category_title']
It would print the category title
Do you have any ideas? I literally been at it for months and can't figure it out.
Use the following:
while ($row = mysqli_fetch_assoc($query)) {
if (!isset($row['campaign_id'])) {
$array[$row['campaign_id']] = $row;
}
if (!isset($array[$row['campaign_id']]['categories'])) {
$array[$row['campaign_id']]['categories'] = array();
}
$array[$row['campaign_id']]['categories'][$row['category_id']] = array('category_id' => $row['category_id'], 'category_title' => $row['category_title']);
}
}
$row is already an associative array, you don't need to assign each element separately. You only need to deal specially with the category information, which has to be put into a nested associative array that I've called categories. So you would access it as
$array[0]['categories'][1]['category_title']
You can loop over all the categories with:
foreach ($array[$campaign]['categories'] as $cat) {
echo "Category ID: {$cat['category_id']} Title: {$cat['category_title']}<br>";
}

Query within a while loop

I have this query call:
$currplayer = 1;
$query = "SELECT f.fk_user_id2, u.username, u.profileimg FROM ".$prefix."_friends f
INNER JOIN ".$prefix."_users u
ON f.fk_user_id2 = u.id
WHERE f.fk_user_id1 = $currplayer ORDER BY u.username ASC";
if ($result = $mysqli->query($query)){
while ($row1 = $result->fetch_assoc()){
$friendid = $row1['fk_user_id2'];
$sql = $mysqli->query("SELECT * FROM ".$prefix."_newversus WHERE fk_player=$currplayer AND fk_opponent=$friendid");
$row = $sql->fetch_assoc();
I am trying to figure out how I get the query within the loop into the first query with inner join, but can't figure this out.
hoping for help and thanks in advance :-)
If i got you corrrectly, you want to remove the query which is running in loop & add it to main query.
Try this:
SELECT f.fk_user_id2, u.username, u.profileimg FROM ".$prefix."_friends f
INNER JOIN ".$prefix."_users u ON f.fk_user_id2 = u.id
INNER JOIN ".$prefix."_newversus n ON f.fk_user_id2 = n.fk_opponent
WHERE f.fk_user_id1 = $currplayer AND
n.fk_player=$currplayer
ORDER BY u.username ASC;

Categories