cannot retrieve data from 2 tables getting no result - php

I have 2 tables:
competition_winners where I am storing people who won competition and table competition where I am storing info about actual competition.
So I am retrieving winners and competition's end date. But the query responsible for date doesn't return anything. I am using Opencart so performing query in model. Here is its code.
public function getWinnersByDate($date) {
$qr = "SELECT competition_id FROM " . DB_PREFIX . "competition_winners";
//$fcid = $qr->row['competition_id'];
$query = "SELECT cometition_id,end_date FROM " . DB_PREFIX . "competition WHERE competition_id = '" .$qr->row['competition_id'] . "'";
return $query->row;
Query works fine in PhpMyadmin. What am I missing or doing wrong?

Instead of running this in two queries You should be using JOIN (search about SQL JOIN on google).
public function getWinnersByDate($date) {
$qr = $this->db->query("
SELECT cw.competition_id, c.end_date
FROM " . DB_PREFIX . "competition_winners cw
LEFT JOIN " . DB_PREFIX . "competition c ON c.competition_id = cw.competition_id
");
return $query->rows;
}
I do not know Your DB structure, but the query above has no sense in it's current state - I believe You want to add some WHERE clause using the provided $date argument and that You want to select more information from competition_winners table, so please, either do it Yourself or provide us with more details on Your problem.

Related

How to fix slow query performance using NOT EXISTS MySQL? CodeIgniter

I am trying to optimize / speed up the performance the loading of my data, is there a way to fix this?
I have 3 tables involved:
tbl_tt_college_studentpersonalinfo - This table displays the name of students, it is join in my query
tbl_tt_college_preenrollment - This table displays the pending status of pre-enrolled students
tbl_tt_college_enlistment - This table will check the existing record the student has.
Here is my Query: - The problem that I am having is the load of data is slow, it may take 30-50 seconds. Is there a way to improve this or make it like a join query?
public function get_enlists()
{
$this->db->join('tbl_tt_college_studentpersonalinfo','tbl_tt_college_preenrollment.studentID = tbl_tt_college_studentpersonalinfo.studentID');
$this->db->where('tbl_tt_college_preenrollment.departmentID', $this->input->post('course'));
$this->db->where('tbl_tt_college_preenrollment.yearLevel', $this->input->post('yearLevel'));
$this->db->where("NOT EXISTS (SELECT tbl_tt_college_enlistment.studentKeyID FROM tbl_tt_college_enlistment WHERE tbl_tt_college_enlistment.studentKeyID = tbl_tt_college_preenrollment.studentKeyID AND schoolYear = '" . $this->session->userdata('currentAcademicYear') . '-' . ($this->session->userdata('currentAcademicYear') + 1) . "' AND semester = '" . $this->session->userdata('currentSemester') . "')");
$query = $this->db->get('tbl_tt_college_preenrollment');
return $query->result_array();
}
Here is the raw query for the reference:
NOT EXISTS (
SELECT studentKeyID FROM tbl_tt_college_enlistment
WHERE tbl_tt_college_studentpersonalinfo.studentKeyID = tbl_tt_college_enlistment.studentKeyID
AND schoolYear = '" . $this->session->userdata('currentAcademicYear') . '-' . ($this->session->userdata('currentAcademicYear') + 1) . "'
AND semester = '" . $this->session->userdata('currentSemester') . "'
)
See if this composite index on tbl_tt_college_enlistment helps:
INDEX(schoolYear, semester, studentKeyID)
If not adequate, please provide SHOW CREATE TABLE and EXPLAIN SELECT ...

Need to add filters to a complex query

i am trying to write a query which will help me recover class, batch, and institution details from db
so far i have managed to make the following work:
SELECT
gallery.path_url AS insimage,
r3.*
FROM
gallery
INNER JOIN (
SELECT
institution.id AS insid,
institution.ProfileImageID,
institution.`name` AS insname,
institution.Locality AS inslocality,
institution.RegistrationFee AS ins_reg_fee,
institution.IsTrail AS ins_is_trail,
institution.LatLong AS latlong,
r2., activity.`name` AS activityname
FROM
institution
INNER JOIN (
SELECT
class., count() AS batch_count,
r1.
FROM
class
INNER JOIN (
SELECT
batch.ID AS batch_id,
batch.ClassID AS class_id,
batch.LevelID AS level_id,
batch.agegroupID AS agegroup_id,
count(*) AS num_batches,
min(Price) AS min_price,
max(Price) AS max_price
FROM
batch,
batchstarttimes
WHERE
batch.ID = batchstarttimes.BatchID
AND batchstarttimes.StartTime BETWEEN '" . $sttime . "'
AND '" . $endtime . "'
GROUP BY
batch.ID
) AS r1
WHERE
r1.class_id = class.ID
GROUP BY
r1.class_id
) AS r2 ON r2.institutionid = institution.id
INNER JOIN activity ON activity.id = r2.activityid
WHERE
activity.`name` LIKE '%" . $searchterm . "%'
AND institution.Locality LIKE '%" . $locality . "%'
AND institution.StatusID = 1
AND level_id = 1
AND agegroup_id = 5
) AS r3 ON r3.ProfileImageID = gallery.ID
I am stuck when i try to add two more filters batch.LevelID and batch.agegroupID
any way i can get help or someone point me to a sql visualizr tool will be helpful.
In your WHERE clause, replace:
AND level_id = 1
AND agegroup_id = 5
with:
AND batch.LevelID = CASE WHEN " . $levelID . " = 0 THEN batch.LevelID ELSE " . $levelID . " END
AND batch.agegroupID = CASE WHEN " . $ageGroupID . " = 0 THEN batch.agegroupID ELSE " . $ageGroupID . " END
The point is to compare batch.LevelID and batch.agegroupID against themselves if you want to ignore them for the filtering (this way they'll always be true) or compare them against $levelID and $ageGroupID values for specific rows.
Also, it's not recommended to use the variables directly in the query, as it's vulnerable to SQL injections attacks. Read about prepared statements here.

Mysql Random Row Query on Inner Join

I have a query and i want random result on advertisement table. Advertise table have own id but when i use RAND(advertise.id) it won't work and i don't know how it will. I am using laravel framework so if possible i can use PHP also to show random advertise result. Here is code can anyone tell me where i use RAND() Mysql function.
SELECT providers.id,
adv__managements.id AS 'adv_id',
adv__managements.images,
adv__managements.categories,
adv__managements.subcategories,
adv__managements.title,
adv__managements.description,
adv__managements.role,
adv__managements.plan_id,
userinformation.user_id,
userinformation.zip_code,
plans.active
FROM userinformation INNER JOIN providers ON userinformation.user_id = providers.user_id
INNER JOIN adv__managements ON adv__managements.range = providers.range
INNER JOIN plans ON plans.user_id = userinformation.user_id
where GetDistance('km'," . doubleval($info->lat) . ", " . doubleval($info->lon) .", " . doubleval(\Auth::user()->userinfo->latitude) . ", " . doubleval(\Auth::user()->userinfo->longitude) . ") < providers.range AND plans.active = 1 LIMIT 3
And can anyone tell how to convert this query into laravel ?

OpenCart JSON Query Database

I create a custom feed for OpenCart.
I am trying to get a list of order details from OpenCart 1.54, however, I cannot find any JSON. Is there a way to return an error message, if the query fails?
Here is the URL to access:
/index.php?route=feed/api&func=getOrderProducts&orderid=1&email=xyz
My plugin files are here:
http://support.cloudcartconnector.com/hc/en-us/articles/202592798-OpenCart
On my test site, this works fine:
public function getOrderProducts($orderid) {
$query = $this->db->query("SELECT op.*, pr.sku, pr.quantity as stock FROM `" . DB_PREFIX . "order_product` op INNER JOIN `product` pr on op.product_id = pr.product_id WHERE op.order_id = '" . $this->db->escape($orderid) . "'");
return $query->rows;
}
I have no order prefix in my database. Here is the response:
[{"order_product_id":"1","order_id":"1","product_id":"43","name":"MacBook","model":"Product 16","quantity":"1","price":"500.0000","total":"500.0000","tax":"89.5000","reward":"600","sku":"macproduct1","stock":"927"}]
On several live sites, the code fails and I receive a blank white page. Here is the route itself:
// example function - getOrders from the database
private function getOrderProducts() {
if($this->request->get['email'] != "info#mysite.com")
{
return "INVALID EMAIL";
}
$this->load->model('feed/api');
return $this->model_feed_api->getOrderProducts($this->request->get['orderid']);
}
My code for getOrders work fine:
public function getOrders($beginDate, $endDate) {
$query = $this->db->query("select o.*, os.* from `" . DB_PREFIX . "order` o LEFT JOIN " . DB_PREFIX . "order_status os ON (o.order_status_id = os.order_status_id) where o.Date_Added >= $beginDate AND o.Date_Added <= $endDate");
return $query->rows;
}
The route for getOrderProducts actually works. If I put in a bad email, it returns INVALID EMAIL. Is there a way to return an exception message?
$this->request->get['orderid']
Maybe it's order_id (note underscore). It's a common name of the order ID value for OpenCart.
Change that code into
$this->request->get['order_id']

MySQL - Datas all included in larger data set

So I have 2 tables:
user_selection (id, user_id, fiche_id)
fiche (id, title, ...)
(fiche = sheet)
I have a research request which gives me some fiche ids
SELECT fiche.*, IF(fiche.fiche_type_id = 2,fiche.instance,fiche_type_texte.type_texte) AS type_texte, IF(fiche.fiche_type_id = 2,CONCAT(fiche.affaire," - ", fiche.titre),fiche.titre) AS titre, IF(fiche.fiche_type_id = 1,fiche.date_publication,fiche.date_texte) AS date_publication
FROM enviroveille_bascule.fiche
LEFT JOIN enviroveille_bascule.fiche_type_texte ON(fiche.fiche_type_texte_id = fiche_type_texte.id)
LEFT JOIN enviroveille_bascule.fiche_x_keyword ON(fiche_x_keyword.fiche_id = fiche.id)
LEFT JOIN enviroveille_bascule.fiche_x_theme ON(fiche_x_theme.fiche_id = fiche.id)
LEFT JOIN enviroveille_bascule.fiche_echeance ON(fiche_echeance.fiche_id = fiche.id)
LEFT JOIN enviroveille_bascule.fiche_x_activite ON(fiche_x_activite.fiche_id = fiche.id) LEFT JOIN enviroveille_bascule.fiche_x_nomenclature ON(fiche_x_nomenclature.fiche_id = fiche.id)
WHERE 1 = 1
AND fiche_echeance.fiche_echeance_type_id IN(2)
GROUP BY fiche.id
I'd like to know if all results from my research query is in the user selection.
So I tried :
// fiche_ids is an array of fiche.id resulting from research request
SELECT COUNT(*) AS nb
FROM " . $this->bdd . $this->table_user_selection . "
WHERE user_id = '" . $user->datas_user['id'] . "'
AND fiche_id IN ('" . implode("','", $fiche_ids) . "')
if($ds['nb'] == count($fiche_ids) && count($fiche_ids) > 0) {
return true;
} else {
return false;
}
That works well
Problem is that I have some research request giving 10K+ results.
And I have to do it several time on the same page, which makes server lags.
Is there a easy way to know if all my results are in my selection?
Note that selection may contain more fiche_id than the research result.
The best would be to be able do this in one SQL request.

Categories