This is my SQL query:
SELECT * FROM users,content
LEFT OUTER JOIN articles ON (
content.content_id = articles.content_id
AND content.content_type = 'article' )
LEFT OUTER JOIN projects ON (
content.content_id = projects.content_id
AND content.content_type = 'project' )
LEFT OUTER JOIN videos ON (
content.content_id = articles.content_id
AND content.content_type = 'video' )
WHERE (content.content_id IN (128,414,399,616,259))
AND content.author_id = users.u_id
order by FIELD(content.content_id,128,414,399,616,259)
when I run this on phpmyadmin I'm getting the results correctly but when I fetch the results by doing mysqli_fetch_assoc(), I am getting null values for content_id. Someone please help me with this. Thanks in advance
Edit:
This is my php code
$query = "SELECT *
FROM users,content
LEFT OUTER JOIN articles
ON ( content.content_id = articles.content_id
AND content.content_type = 'article' )
LEFT OUTER JOIN projects
ON ( content.content_id = projects.content_id
AND content.content_type = 'project' )
LEFT OUTER JOIN videos
ON ( content.content_id = articles.content_id
AND content.content_type = 'video' )
WHERE (content.content_id IN (".implode(",",$new_array).")) AND content.author_id = users.u_id order by FIELD(content.content_id,".implode(",",$new_array).")";
$result = mysqli_query($con,$query);
if($result!=null && $result->num_rows>0){
while( $contentrow = $mysqli_fetch_assoc($result){
print_r($contentrow);
}
}
$new_array is the content ids for which I'm querying the database. The printed $contentrow has content_id field as null while I'm getting the correct id values in phpmyadmin.
Related
Here is my mysql_query i want to add this query into my main query but the problem is when im add it to query it show sub query returns more than one row
(
SELECT date(trn_orderheader_approvedby.dtApprovedDate) AS CREATE_DATE
FROM trn_orderheader_approvedby
WHERE trn_orderheader_approvedby.intApproveLevelNo IN('-10')
)
AS Order_COMPLETED_DATE
SELECT
TB1.*, (
SELECT
SUM(TRNS.dblQty *- 1)
FROM
ware_stocktransactions_bulk AS TRNS
WHERE
TRNS.intOrderNo = TB1.`NO`
AND TRNS.intOrderYear = TB1.`YEAR`
AND TRNS.intSalesOrderId = TB1.intSalesOrderId
AND TRNS.intItemId = TB1.ITEM_ID
AND TRNS.intLocationId = TB1.LOCATION_ID
AND TRNS.strType IN ('ISSUE', 'RETSTORES')
) AS QTY,
(
SELECT
SUM(
TRNS.dblQty * TRNS.dblGRNRate * mst_financeexchangerate.dblBuying *- 1
)
FROM
ware_stocktransactions_bulk AS TRNS
LEFT JOIN mst_financeexchangerate ON mst_financeexchangerate.dtmDate = TRNS.dtGRNDate
AND mst_financeexchangerate.intCompanyId = TRNS.intCompanyId
AND mst_financeexchangerate.intCurrencyId = TRNS.intCurrencyId
WHERE
TRNS.intOrderNo = TB1.`NO`
AND TRNS.intOrderYear = TB1.`YEAR`
AND TRNS.intSalesOrderId = TB1.intSalesOrderId
AND TRNS.intItemId = TB1.ITEM_ID
AND TRNS.intLocationId = TB1.LOCATION_ID
AND TRNS.strType IN ('ISSUE', 'RETSTORES')
) AS AMOUNT,
(
SELECT
SUM(
costing_sample_header.INK_COST
)
FROM
costing_sample_header
WHERE
TB1.intSampleNo = costing_sample_header.SAMPLE_NO
AND TB1.intSampleYear = costing_sample_header.SAMPLE_YEAR
AND TB1.intRevisionNo = costing_sample_header.REVISION
AND TB1.strCombo = costing_sample_header.COMBO
AND TB1.strPrintName = costing_sample_header.PRINT
) AS INK_COST,
(
SELECT
SUM(
costing_sample_header.SPECIAL_RM_COST
)
FROM
costing_sample_header
WHERE
TB1.intSampleNo = costing_sample_header.SAMPLE_NO
AND TB1.intSampleYear = costing_sample_header.SAMPLE_YEAR
AND TB1.intRevisionNo = costing_sample_header.REVISION
AND TB1.strCombo = costing_sample_header.COMBO
AND TB1.strPrintName = costing_sample_header.PRINT
) AS RM_COST
FROM
(
SELECT DISTINCT
tempory_rm_moved_orders_summery2.`NO`,
tempory_rm_moved_orders_summery2.`YEAR`,
trn_orderdetails.intSalesOrderId,
trn_orderdetails.strSalesOrderNo,
trn_orderdetails.strGraphicNo,
trn_orderdetails.intSampleNo,
trn_orderdetails.intSampleYear,
trn_orderdetails.intRevisionNo,
trn_orderdetails.strCombo,
trn_orderdetails.strPrintName,
mst_part.strName AS part,
mst_locations.intId AS LOCATION_ID,
mst_locations.strName AS LOCATION,
trn_orderdetails.intQty,
mst_maincategory.strName AS MAIN_CATEGORY,
mst_subcategory.strName AS SUB_CATEGORY,
mst_item.intId AS ITEM_ID,
mst_item.strCode AS ITEM_CODE,
mst_item.strName AS ITEM_NAME,
mst_units.strCode AS UOM,
trn_po_prn_details_sales_order.PRODUCTION_QTY,
/* trn_po_prn_details_sales_order.CONS_PC,
trn_po_prn_details_sales_order.PRODUCTION_QTY,
trn_po_prn_details_sales_order.REQUIRED, sum( ifnull(
ware_stocktransactions_bulk.dblQty *- 1, 0 ) ) AS qty,*/
/*sum( ifnull( ware_stocktransactions_bulk.dblQty * ware_stocktransactions_bulk.dblGRNRate * mst_financeexchangerate.dblBuying *- 1, 0 ) ) AS amount, */
trn_orderdetails.dblPrice,
mst_customer.strName AS CUSTOMER_NAME,
mst_brand.strName AS BRAND_NAME,
trn_orderheader.intStatus,
IF (
trn_orderheader.intStatus = 1,
'Approved',
IF (
trn_orderheader.intStatus = 0,
'Rejected',
IF (
trn_orderheader.intStatus =- 10,
'Completed',
IF (
trn_orderheader.intStatus =- 2,
'Cancel',
IF (
trn_orderheader.intStatus =- 1,
'Revised',
'Pending'
)
)
)
)
) AS STATUS,
trn_orderdetails.dtDeliveryDate,
mst_technique_groups.TECHNIQUE_GROUP_NAME
FROM
ware_stocktransactions_bulk
INNER JOIN tempory_rm_moved_orders_summery2 ON ware_stocktransactions_bulk.intOrderNo = tempory_rm_moved_orders_summery2.`NO`
AND ware_stocktransactions_bulk.intOrderYear = tempory_rm_moved_orders_summery2.`YEAR`
AND date(
ware_stocktransactions_bulk.dtDate
) >= '2017-06-01'
INNER JOIN trn_orderdetails ON ware_stocktransactions_bulk.intOrderNo = trn_orderdetails.intOrderNo
AND ware_stocktransactions_bulk.intOrderYear = trn_orderdetails.intOrderYear
AND ware_stocktransactions_bulk.intSalesOrderId = trn_orderdetails.intSalesOrderId
INNER JOIN mst_part ON trn_orderdetails.intPart = mst_part.intId
INNER JOIN trn_orderheader ON trn_orderdetails.intOrderNo = trn_orderheader.intOrderNo
AND trn_orderdetails.intOrderYear = trn_orderheader.intOrderYear
INNER JOIN mst_item ON ware_stocktransactions_bulk.intItemId = mst_item.intId
INNER JOIN mst_maincategory ON mst_item.intMainCategory = mst_maincategory.intId
INNER JOIN mst_subcategory ON mst_item.intSubCategory = mst_subcategory.intId
INNER JOIN mst_units ON mst_item.intUOM = mst_units.intId
INNER JOIN mst_locations ON ware_stocktransactions_bulk.intLocationId = mst_locations.intId
INNER JOIN mst_customer ON trn_orderheader.intCustomer = mst_customer.intId
INNER JOIN trn_sampleinfomations ON trn_orderdetails.intSampleNo = trn_sampleinfomations.intSampleNo
AND trn_orderdetails.intSampleYear = trn_sampleinfomations.intSampleYear
AND trn_orderdetails.intRevisionNo = trn_sampleinfomations.intRevisionNo
INNER JOIN mst_brand ON trn_sampleinfomations.intBrand = mst_brand.intId
INNER JOIN mst_technique_groups ON trn_orderdetails.TECHNIQUE_GROUP_ID = mst_technique_groups.TECHNIQUE_GROUP_ID
LEFT JOIN trn_po_prn_details_sales_order ON ware_stocktransactions_bulk.intOrderYear = trn_po_prn_details_sales_order.ORDER_NO
AND ware_stocktransactions_bulk.intOrderYear = trn_po_prn_details_sales_order.ORDER_YEAR
AND ware_stocktransactions_bulk.intSalesOrderId = trn_po_prn_details_sales_order.SALES_ORDER
AND ware_stocktransactions_bulk.intItemId = trn_po_prn_details_sales_order.ITEM
WHERE
ware_stocktransactions_bulk.strType IN ('ISSUE', 'RETSTORES')
AND ware_stocktransactions_bulk.intOrderNo > 0
AND trn_po_prn_details_sales_order.ITEM IS NULL
/* GROUP BY ware_stocktransactions_bulk.intLocationId, ware_stocktransactions_bulk.intOrderNo, ware_stocktransactions_bulk.intOrderYear, ware_stocktransactions_bulk.intSalesOrderId, ware_stocktransactions_bulk.intItemId */
) AS TB1here
i found a solution like this
(
SELECT
trn_orderheader_approvedby.dtApprovedDate
FROM
trn_orderheader_approvedby
WHERE
trn_orderheader_approvedby.intApproveLevelNo = "-10"
AND trn_orderdetails.intOrderNo = trn_orderheader_approvedby.intOrderNo
AND trn_orderdetails.intOrderYear = trn_orderheader_approvedby.intYear
ORDER BY
trn_orderheader_approvedby.dtApprovedDate DESC
LIMIT 1
) AS COMPLETED_DATE
i have mysql query
SELECT `users`.`user_id`, `tool`.`name` FROM `users` LEFT JOIN
`project` ON
`users`.`user_id` = `project`.`user_id` LEFT JOIN `tools` ON `users`.'user_id' = `tools`.`user_id` AND `project`.`project_id` = `tools`.`project_id`
Where project_id = value
and user_id = value
and my doctrine query is this
$query = $queryBuilder->select ( array (
'user.userId',
'user.name',
))
->from('Users', 'users')
->leftJoin(user.project, project)
->leftJoin(user.tool, tool)
->where(user.userId = value)
->andWhere(project.projectId = value)
now how would i include the AND project.project_id = tools.`project_id
part to Doctrine query builder
without
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."'";
Okay, I've been tasked with rewriting a small, old PHP app in Codeigniter, and I ran into a bit a road bump. I'm not sure how to go about handling the joins in the query.
FROM(
(
(
(
(mobiledoc.labdata labdata JOIN mobiledoc.items items
ON (labdata.ItemId = items.itemID)
) JOIN mobiledoc.enc enc
ON (labdata.EncounterId = enc.encounterID)
) JOIN mobiledoc.users users_patient
ON (users_patient.uid = enc.patientID)
) JOIN mobiledoc.users users_Provider
ON (users_Provider.uid = enc.doctorID)
) JOIN mobiledoc.facilitygroupmembers facilitygroupmembers
ON (enc.facilityId = facilitygroupmembers.FacilityId)
)
And then after that FROM there are a few more joins, which I think would be fairly easy.
JOIN mobiledoc.facilitygroups facilitygroups ON (facilitygroups.Id = acilitygroupmembers.GroupId)
JOIN mobiledoc.patients patients ON (enc.patientID = patients.pid)
Any help would be greatly appreciated.
UPDATE:
I decided to just put the nested joins inside the for statement, and move on. Here's the original query.
$result = mysql_query("SELECT patients.ControlNO AS PatientID, users_patient.ulname AS patulname,
users_patient.ufname AS patufname, users_patient.uminitial AS patuminitial, users_patient.dob AS
patdob, users_Provider.ulname AS ULname, users_Provider.ufname AS UFname, items.itemName,
labdata.Notes,enc.date, enc.startTime FROM(((((mobiledoc.labdata labdata JOIN mobiledoc.items
items ON (labdata.ItemId = items.itemID)) JOIN mobiledoc.enc enc ON (labdata.EncounterId =
enc.encounterID)) JOIN mobiledoc.users users_patient ON (users_patient.uid = enc.patientID)) JOIN
mobiledoc.users users_Provider ON (users_Provider.uid = enc.doctorID)) JOIN
mobiledoc.facilitygroupmembers facilitygroupmembers ON (enc.facilityId =
facilitygroupmembers.FacilityId)) JOIN mobiledoc.facilitygroups facilitygroups ON
(facilitygroups.Id = facilitygroupmembers.GroupId) JOIN mobiledoc.patients patients ON
(enc.patientID = patients.pid) WHERE (facilitygroups.Name = '". $_POST['facility_id'] . "') AND
(items.itemName LIKE '%X RAY%' OR items.itemName LIKE '%Cast%' OR items.itemName LIKE '%Splint%'
OR items.itemName LIKE '%DEXA%') AND (enc.VisitType NOT IN ('', 'MT', 'TEL')) AND (enc.`date` =
'" . $_POST['txtYear'] . "-" . $_POST['txtMonth'] . "-" . $_POST['txtDay'] ."') ORDER BY
enc.startTime ASC") or die ("could not execute query!");
Here's the new query:
$this->db->select('patients.ControlNO as id');
$this->db->select('users_patient.ulname as lastName');
$this->db->select('users_patient.ufname as firstName');
$this->db->select('users_patient.uminitial as mInitial');
$this->db->select('users_patient.dob as dob');
$this->db->select('users_Provider.ulname as phys_lastName');
$this->db->select('items.itemName');
$this->db->select('labdata.notes');
$this->db->select('enc.date');
$this->db->select('enc.startTime');
$this->db->from('((((mobiledoc.labdata labdata JOIN mobiledoc.items items ON (labdata.ItemId
= items.itemID)) JOIN mobiledoc.enc enc ON (labdata.EncounterId = enc.encounterID)) JOIN
mobiledoc.users users_patient ON (users_patient.uid = enc.patientID)) JOIN mobiledoc.users
users_Provider ON (users_Provider.uid = enc.doctorID)) JOIN mobiledoc.facilitygroupmembers
facilitygroupmembers ON (enc.facilityId = facilitygroupmembers.FacilityId)) JOIN
mobiledoc.facilitygroups facilitygroups ON (facilitygroups.Id = facilitygroupmembers.GroupId)
JOIN mobiledoc.patients patients ON (enc.patientID = patients.pid)');
$this->db->where($where_array);
$this->db->like($like_array);
$this->db->or_like($or_like_array);
$this->db->where_not_in('enc.VisitType', $not_in);
$this->db->order_by('enc.startTime', 'asc');
$this->db->get();
And the output from that query:
SELECT `patients`.`ControlNO` as id, `users_patient`.`ulname` as lastName,
`users_patient`.`ufname` as firstName, `users_patient`.`uminitial` as mInitial,
`users_patient`.`dob` as dob, `users_Provider`.`ulname` as phys_lastName, `items`.`itemName`,
`labdata`.`notes`, `enc`.`date`, `enc`.`startTime` FROM ((((((mobiledoc.labdata labdata JOIN
mobiledoc.items items ON (labdata.ItemId = items.itemID)) JOIN mobiledoc.enc enc ON
(labdata.EncounterId = enc.encounterID)) JOIN mobiledoc.users users_patient ON (users_patient.uid
= enc.patientID)) JOIN mobiledoc.users users_Provider ON (users_Provider.uid = enc.doctorID))
JOIN mobiledoc.facilitygroupmembers facilitygroupmembers ON (enc.facilityId =
facilitygroupmembers.FacilityId)) JOIN mobiledoc.facilitygroups facilitygroups ON
(facilitygroups.Id = facilitygroupmembers.GroupId) JOIN mobiledoc.patients patients ON
(enc.patientID = patients.pid)) WHERE `facilitygroups`.`Name` = 0 AND `enc`.`date` = '12/05/2014'
AND `enc`.`VisitType` NOT IN ('', 'MT', 'TEL') AND `items`.`itemName` LIKE '%X RAY%' OR
`items`.`itemName` LIKE '%DEXA%' OR `0` LIKE '%items.itemName%' ORDER BY `enc`.`startTime` asc
With CI's active record you can easily join tables by using the following format
$qry = $this->db->select('*')
->from('table1')
->where('table1.id', 1)
->join('table2','table2.t_id = table1.id')
->get();
For more information take a look at CI's active record documentation
Also you can specify the join type by adding a third parameter to the join() function
$this->db->join('table3', 'table3.id = table2.t_id', 'left');
SELECT
`blg`.`id` ,
`blg`.`heading` ,
`blg`.`description` ,
`cat`.`name` AS `categoryname` ,
`mem`.`firstname` AS `user` ,
( SELECT COUNT( * ) FROM blog_comments WHERE blog_comments.status = '1' AND blog_comments.blogid = blg.id) AS `commentcount`
FROM `blogs` AS `blg`
INNER JOIN `blog_category` AS `cat` ON blg.category = cat.id
INNER JOIN `members_member` AS `mem` ON blg.user = mem.id
LEFT JOIN `blog_comments` AS `cmt` ON blg.id = cmt.blogid
WHERE ( blg.status = '1' )
GROUP BY blg.id ORDER BY `blg`.`id` ASC
What about something like this:
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select();
$dbExpr = new Zend_Db_Expr("(SELECT COUNT( * ) FROM blog_comments WHERE blog_comments.status = '1' AND blog_comments.blogid = blg.id) AS `commentcount`");
$select->from(
array('blg' => 'blogs'),
array('id', 'heading', 'description', 'name as categoryname', $dbExpr)
)->joinInner(
array('cat' => 'blog_category'),
'blg.category = cat.id',
array()
)->joinInner(
array('mem' => 'members_member'),
'blg.user = mem.id',
array()
)->joinLeft(
array('cmt' => 'blog_comments'),
'blg.id = cmt.blogid',
array()
)->where('blg.status = ?', '1')
->group('blg.id')
->order('blg.id ASC');
echo $select->assemble();
exit;
Output:
SELECT `blg`.`id`, `blg`.`heading`, `blg`.`description`, `blg`.`name` AS `categoryname`,
(SELECT COUNT( * ) FROM blog_comments WHERE blog_comments.status = '1' AND blog_comments.blogid = blg.id) AS `commentcount`
FROM `blogs` AS `blg`
INNER JOIN `blog_category` AS `cat` ON blg.category = cat.id
INNER JOIN `members_member` AS `mem` ON blg.user = mem.id
LEFT JOIN `blog_comments` AS `cmt` ON blg.id = cmt.blogid
WHERE (blg.status = '1')
GROUP BY `blg`.`id`
ORDER BY `blg`.`id` ASC