I'm getting an error in my query, and I'm unable to detect the source of the problem.
Here is the query:-
$query = "SELECT useraccount.Username, tariff.Name as tariffs,
sum(energyconsumption.ElecEnergy)
FROM useraccount
INNER JOIN tariff
ON useraccount.tariffs = tariff.id
INNER JOIN energyconsumption
ON energyconsumption.User = useraccount.id
WHERE Date = CURRENT_DATE
GROUP BY useraccount.Username, tariff.Name as tariffs";
Following the query I've code that stores the output in an array:
$result = mysqli_query($conn,$query);
$r = array();
if($result->num_rows){
while($row = mysqli_fetch_array($result)){
array_push($r, array( 'Username' => $row['Username'],
'TariffName' => $row['tariffs'], 'ElecConsump' => $row['ElecEnergy']
));
}
} echo json_encode(array('results' => $r));
Im getting an error in the following line: if($result->num_rows)
This is the output when executing the query:
Notice: Trying to get property of non-object in C:\xampp\htdocs\Project\Client\newone.php on line 22
{"results":[]}
Please note:
This was the output i intially had:
{"results":[{"Username":"absc868","TariffName":"s1","ElecConsump":"2000"},
{"Username":"absc868","TariffName":"s1","ElecConsump":"1900"}]}
But with this new query I have written above, I am trying to produce this output
I am trying to produce the following output:
= {"results":[{"Username":"absc868","TariffName":"s1","ElecConsump":"3900"}
That being, a result set that only has 1 entry, for username, tariff and elecconsump, rather than 2 entries for username, tariff and elecconsump
Thank you once again to all those who have read and contributed to this thread
One problem is the as in the GROUP BY. I would recommend that you use table aliases:
SELECT ua.Username, t.Name as tariffs,
SUM(ec.ElecEnergy) as ElecEnergy
FROM useraccount ua INNER JOIN
tariff t
ON ua.tariffs = t.id INNER JOIN
energyconsumption ec
ON ec.User = ua.id
WHERE Date = CURRENT_DATE
GROUP BY ua.Username, t.Name;
Related
I have some tables for my data cafe. The tables are tb_cafe for main table, tb_fasilitas that has id_cafe from tb_cafe and id_fasilitas from tb_fasilitascafe. Then tb_lokasicafe, tb_menucafe, tb_gallerycafe.
I just wanted to get all data from tb_cafe and facility name, location, menus, and price.
Is it possible to join tb_facilitycafe with tb_facility to get name facility by id_cafe inside join query for another table? Can you show me how to resolve this.
I use it for an API that results in JSON output.
I tried the code like this:
<?php
include_once('koneksi.php');
$sql = "SELECT * FROM tb_cafe AS tc
LEFT JOIN tb_fasilitas_cafe AS tf ON tf.id_cafe=tc.id_cafe
LEFT JOIN tb_gallerycafe AS tg ON tg.id_cafe=tc.id_cafe
LEFT JOIN tb_lokasicafe AS tl ON tl.id_cafe=tc.id_cafe
LEFT JOIN tb_menucafe AS tm ON tm.id_cafe=tc.id_cafe
WHERE state_verifikasi IN (1)";
$r = mysqli_query($con,$sql);
$result = array();
if($r){
while($row = mysqli_fetch_array($r)){
array_push($result,array(
"id_cafe"=>$row['id_cafe'],
"nama_cafe"=>$row['nama_cafe'],
"foto_cafe"=>$row['foto_cafe'],
"alamat_cafe"=>$row['alamat_cafe'],
"deskripsi_cafe"=>$row['deskripsi_cafe'],
"no_telepon"=>$row['no_telepon'],
"jam_operasional_WeekDay"=>$row['jam_operasional_WeekDay'],
"jam_operasional_WeekEnd"=>$row['jam_operasional_WeekEnd'],
"nama_fasilitas"=>$row['nama_fasilitas'],
"foto"=>$row['foto'],
"latitude"=>$row['longitude'],
"longitude"=>$row['longitude'],
"nama_menu"=>$row['nama_menu'],
"harga_menu"=>$row['harga_menu']
));
}
echo json_encode(array('result'=>$result));
mysqli_close($con);
}
?>
I wanted to get a specific result by the id_cafe, but the result I have shows more than 1 result for the same id_cafe. How can I fix it to be 1 result for one id_cafe?
I'm getting started with JOIN and I'm trying to fetch all rows from clasificados and the abrev and nombre column from five of the "JOINED" tables, may be this is not possible but I've being reading about and I thought that it was.
I'm using LIMIT
I'm getting 0 as rowCount. Anyone could guide me please?
$sql2 = "SELECT cl.id AS clasid,
cl.email AS email,
cl.tipo_anuncio AS tipo_anuncio,
cl.reid AS reid,
cl.rcid AS rcid,
cl.img_1 AS img_1,
cl.titulo AS titulo,
cl.precio AS precio,
cl.negociable AS negociable,
cl.estado_art AS estado,
cl.intercambio AS intercambio,
cl.retro AS retro,
cl.id_cat_1 AS id_cat_1,
cl.id_subcat_1 AS id_subcat_1,
cl.id_subcat_2 AS id_subcat_2,
cl.clas_pass AS clasified_key,
cl.user_activo AS user_activo,
cl.approved_pay AS approved,
cl.expiracion AS expiracion,
cl.rep_email_enviado AS rep_email_sent,
eid.abrev AS edm_abrev,
cid.nombre AS cdm_nombre,
negoc.nombre AS neg,
exch.nombre AS exchangable,
estadoTB.nombre AS estado_articulo
FROM clasificados AS cl
JOIN 1_ AS cat_one
ON cat_one.id = cl.id_cat_1
JOIN estados AS eid
ON eid.id = cl.reid
JOIN municipios AS cid
ON cid.id = cl.rcid
JOIN negociable_tb AS negoc
ON negoc.id = cl.negociable
JOIN intercambio_tb AS exch
ON exch.id = cl.intercambio
JOIN estado_articulo_tb AS estadoTB
ON estadoTB.id = cl.estado_art
WHERE cl.user_activo = 1 AND cl.approved_pay = 1 ORDER BY cl.id DESC LIMIT $position, $items_per_group";
My MySQL query is displaying just one row (instead of all of the rows), but when I do a COUNT on the query, it shows the correct number of rows in the query. What seems to be the problem here?
$sql5 = "SELECT m.*, i.*, COUNT(*) AS num, m.id AS m_id FROM members m JOIN roommate_seek i ON m.id = i.member_id
WHERE _school = :school AND i.category = :category";
foreach ($db->query($sql5, array('school' => $_GET['school'], 'category' => $category)) AS $result3)
{
echo "{$result3['m_id']}";
}
You are using an aggregate function (COUNT) without GROUP BY. In that case it is suppose to return exactly one row.
function getAllReferrals(){
$sql = "(SELECT r.referral_date,c.lastname,c.middlename,c.firstname,c.gender,r.presenting_problem,e.employee_nickname
AS nickname FROM CLIENT c INNER JOIN referral1 r ON c.referral_id = r.referral1_id INNER JOIN assign_psychotherapist ap
ON ap.a_referral_id = c.referral_id INNER JOIN employee e ON ap.a_psychotherapist_id = e.empid WHERE r.referral_status ='Assigned'
OR r.referral_status ='Accepted' ORDER BY referral_date DESC ) UNION ALL (SELECT r.referral_date,c.lastname,c.middlename,c.firstname,
c.gender,r.presenting_problem,v.volunteer_nickname AS nickname FROM CLIENT c INNER JOIN referral1 r ON c.referral_id = r.referral1_id
INNER JOIN assignvolunteer av ON av.Vreferralid = c.referral_id INNER JOIN volunteer v ON av.Vvolunteerid = v.volid
WHERE r.referral_status ='Assigned' OR r.referral_status ='Accepted' ORDER BY referral_date DESC )";
$query = $this->db->query($sql);
if ($query->num_rows() > 0){
return $query->result();
}else{
return NULL;
}
}
Message: Invalid argument supplied for foreach() -> having this error
With the given information let me answer the question.
how can i pass this query to my controller in CodeIgniter
Understand that query isn't passed to the controller from the model but what's passed is data. what you have to do is returned the data from model to controller and set the data into the $data variable in the controller which is then passed to the view.
Adding more you are getting above error because there is no data(result array is empty) in the array. Make sure that you query returns array of data as well. Try executing it manually in MySQL and see the result.
Try result_array() which returns the query result as a pure array, or an empty array when no result is produced.
Read more
First try execute your query manuly, and check get any result you can try your program. Invalid argument supplied for foreach() -> having this error this type of error occurred your result array may be empty.
first create a model . and paste this code on model like your model name is ex_model.php
function getAllReferrals(){
$sql = "(SELECT r.referral_date,c.lastname,c.middlename,c.firstname,c.gender,r.presenting_problem,e.employee_nickname
AS nickname FROM CLIENT c INNER JOIN referral1 r ON c.referral_id = r.referral1_id INNER JOIN assign_psychotherapist ap
ON ap.a_referral_id = c.referral_id INNER JOIN employee e ON ap.a_psychotherapist_id = e.empid WHERE r.referral_status ='Assigned'
OR r.referral_status ='Accepted' ORDER BY referral_date DESC ) UNION ALL (SELECT r.referral_date,c.lastname,c.middlename,c.firstname,
c.gender,r.presenting_problem,v.volunteer_nickname AS nickname FROM CLIENT c INNER JOIN referral1 r ON c.referral_id = r.referral1_id
INNER JOIN assignvolunteer av ON av.Vreferralid = c.referral_id INNER JOIN volunteer v ON av.Vvolunteerid = v.volid
WHERE r.referral_status ='Assigned' OR r.referral_status ='Accepted' ORDER BY referral_date DESC )";
$query = $this->db->query($sql);
if ($query->num_rows() > 0){
return $query->result();
}else{
return NULL;
}
and create controller and get add this code like
<?php
public function reffers(){
$this->load->model('ex_model');
$data['refferdata'] = $this->ex_model->getAllReferrals();
$this->load->view('reffer');
}
?>
now create a view name reffer.php and get all data from foreach loop like
<?php
foreach($refferdata as $r)
{
echo $r->r.referral_date.<br>;
echo $r->c.lastname.<br>;
// and so on like this in view
}
?>
I am creating a dashboard to keep me updated on call agent status.an agent will have multiple records in the log. I need to pull the most recent status from the agent log. The only way I have found is to query the agent table to pull the agents with status changes made today and then query the agent log table to pull the most recent status.
is there a way to combine the two queries.? Here are my queries
$sql_get_agents = "SELECT id FROM agent WHERE lastchange LIKE '{$today}%'";
if($dta = mysql_query($sql_get_agents)){
while($agent = mysql_fetch_assoc($dta)){
$curr_agent[] = $agent;
}
foreach($curr_agent as $agents_online){
$get_status_sql = "SELECT a.firstname,a.lastname,al.agentid,al.agent_statusid,s.id as statusid,s.status,MAX(al.datetime) as datetime FROM agent_log al
INNER JOIN agent a ON al.agentid = a.id
INNER JOIN agent_status s ON a.agent_statusid = s.id
WHERE al.agentid = '{$agents_online['id']}'";
if($dta2 = mysql_query($get_status_sql)){
while($agent_status = mysql_fetch_assoc($dta2)){
$curr_status[] = $agent_status;
}
}
}//end for each
return $curr_status;
}//end if
Why don't you join the 2 queries into one adding the WHERE lastchange LIKE '{$today}%' condition in the second query?
Using the IN clause should work :
"SELECT a.firstname,a.lastname,al.agentid,al.agent_statusid,s.id as statusid,s.status,MAX(al.datetime) as datetime FROM agent_log al
INNER JOIN agent a ON al.agentid = a.id
INNER JOIN agent_status s ON a.agent_statusid = s.id
WHERE al.agentid IN (SELECT id FROM agent WHERE lastchange LIKE '{$today}%');
You were close with what you have. This will get rid of the need to do both queries, or query in a loop.
edit: adding example code to loop over the results as well.
edit2: changed query.
$query = "SELECT
a.firstname,
a.lastname,
al.agentid,
al.agent_statusid,
s.id as statusid,
s.status,
MAX(al.datetime) as datetime
FROM agent a
LEFT JOIN agent_log al ON al.agentid = a.id
LEFT JOIN agent_status s ON a.agent_statusid = s.id
WHERE a.lastchange LIKE '{$today}%'";
$status = array();
$results = mysql_query( $query );
while( $agent = mysql_fetch_assoc( $results ) )
$status[] = $agent;
print_r( $status );