Not sure how I am getting the undefined index error when my SELECT already gets the column that I want.
I have three tables:
clinics_branch.add.php
<?php
session_start();
require_once('clinics_branch_list.vc.php');
?>
<?php echo $lstBranch['usrmerchant']; ?>
the undefined index is in the echo usrmerchant
clinics_branch_list.vc.php
require_once($routePath . "_mc/Merchant.mc.php");
$mcMerchant = new Merchant_MC();
$lstBranch = $mcMerchant->SelectMainBranch_ByMerchantBranch($db, $merchantid);
Merchant.mc.php
Class Merchant_MC {
public function SelectMainBranch_ByMerchantBranch($db, $merchantid) {
$stmt = $db->prepare(
" SELECT mb.merchantid, m.usrmerchant
FROM `merchant_branch` mb
LEFT JOIN `merchant` m ON mb.merchantid = m.merchantid
WHERE mb.merchantid = $merchantid "
);
$stmt->bindValue(':merchantid', $merchantid, PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $row;
}
}
here's the output of my select, as you can see there is content so the SQL is working
any help is appreciated, the full error is:
Notice: Undefined index: usrmerchant in clinics_branch_add.php
UPDATE:
changing my SQL line to WHERE mb.merchantid = :merchantid still shows the same error.
UPDATE:
switching to innjer join does not work either
SELECT mb.merchantid, m.usrmerchant
FROM merchant_branch mb
INNER JOIN merchant m
ON mb.merchantid = m.merchantid
WHERE mb.merchantid = :merchantid
You're doing a fetchAll, so $lstBranch will actually be an array of rows looking something like this:
array(0 => array('merchantid' => 30, 'usrmerchant' => 'dermadent'))
and you will need to access the usrmerchant value as
$lstBranch[0]['usrmerchant'];
Change
SELECT mb.merchantid, m.usrmerchant
FROM `merchant_branch` mb
LEFT JOIN `merchant` m ON mb.merchantid = m.merchantid
WHERE mb.merchantid = $merchantid "
To
SELECT mb.merchantid, m.usrmerchant
FROM merchant_branch mb
INNER JOIN marchant m
ON mb.merchantid = m.merchantid
WHERE mb.merchantid = :merchantid
Related
I have the code like this
$phql = "SELECT COUNT(a.id) FROM UserParkingIn a JOIN UserVehicle b ON a.userVehicleId = b.id WHERE b.vehicleTypeId = 1";
$result = $this->modelsManager->executeQuery($phql);
echo $result;
in UserParkingIn Table I have example id = 10, userVehicleId = 2
in UserVehicle Table I have example id =10, userVehicleId = 2, vehicleTypeId = 1
It return empty, but when I execute this query in phpMyAdmin I use this sql logic it return right number.
SELECT COUNT(a.id) FROM user_parking_in a JOIN user_vehicle b ON a.userVehicleId = b.id WHERE b.vehicleTypeId=1;
and it return number 7
Can someone explain why this return error?
Thank you.
I found the solution that id I used to count must set an alias to be like quota like this.
$query = $this->modelsManager->createQuery("SELECT COUNT(a.id) as quota FROM UserParkingIn a JOIN UserVehicle b ON a.userVehicleId = b.id WHERE a.ospoId = '$ospoId' ");
$records = $query->execute();
foreach($records as $record){
$parkingUsed = $record->quota;
}
and now it is working.
I am trying to run 2 SQL Select queries to retrieve data from 2 different tables and then echo the fields from both tables. The code I am trying doesn't seem to work, any help would be appreciated.
$ModelID = $_GET['model_id'];
$result = mysqli_query($con, "SELECT RegNumber, Colour FROM Car WHERE ModelID = '$ModelID'
UNION ALL
SELECT CarModel, CarMake, CostPerDay FROM Model WHERE ModelID = '$ModelID'");
while($row = $result->fetch_assoc())
{
echo $row["CarModel"];
echo $row["CarMake"];
echo $row["CostPerDay"];
echo $row["RegNumber"];
echo " - " .$row["Colour"];
}
You can change request :
SELECT c.RegNumber, c.Colour , m.CarModel, m.CarMake, m.CostPerDay FROM Car c INNER JOIN Model m ON m.ModelID=c.ModelID WHERE c.ModelID = '$ModelID'
try with LEFT JOIN
$result = mysqli_query($con,
"SELECT c.RegNumber, c.Colour, m.CarModel, m.CarMake, m.CostPerDay
FROM Car AS c
LEFT JOIN Model as m ON c.ModelID = m.ModelID
WHERE c.ModelID = '".$ModelID."'"
);
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;
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 have a query like this:
$query = "SELECT a.sender_id,
a.recipient_id,
a.form_id, due_date,
a.completed,
f.name,
p.priority,
u.first_name,
u.last_name,
SUM(a.completed) as completed_sum
FROM form_assignments a
JOIN forms f ON (form_id = f.id)
JOIN users u ON (sender_id = u.id)
JOIN priorities p ON (priority_id = p.id)
WHERE recipient_id = '{$_SESSION['user_id']}'
ORDER BY due_date ASC";
And a while loop like this:
$assignment_count = (mysqli_num_rows($result));
$assignments_row = array();
while ($row = mysqli_fetch_array($result)) {
$sender = $row['first_name'] . ' ' . $row['last_name'];
$form_id = $row['form_id'];
$form_name = $row['name'];
$priority = $row['priority'];
$due_date = date('m/d/Y', strtotime($row['due_date']));
$completed = $row['completed'];
$not_done = $assignment_count - $row['completed_sum'];
}
And it's only returning one row. It seems my SUM(a.completed) as completed_sum is causing the issues because the query worked fine before I added it, but I want to add up all the values in completed to use in my $not_done variable.
Can anyone help clarify what I'm doing wrong?
When you use an aggregate function like SUM, all the results will be aggregated into one row unless you use a GROUP BY clause to segregate them. But it looks to me like you don't need a SUM in the first place. Your loop is subtracting this value from a total, so you just need the value from each row -- when you subtract them all you'll have subtracted the total. So just select a.completed rather than SUM(a.completed).
For $not_done, you need to initialize it before the loop:
$not_done = $assignment_count;
Then during the loop you should do a running subtraction:
$not_done -= $row['completed'];
Try this query :
SELECT
a.sender_id,
a.recipient_id,
a.form_id,
a.due_date,
a.completed,
f.name,
p.priority,
u.first_name,
u.last_name,
b.completed as completed_sum
FROM
form_assignments AS a
LEFT JOIN (
SELECT form_id,SUM(completed) FROM form_assignments GROUP BY form_id
) AS b ON (a.form_id = b.form_id)
LEFT JOIN forms AS f ON (form_id = f.id)
LEFT JOIN users AS u ON (sender_id = u.id)
LEFT JOIN priorities AS p ON (priority_id = p.id)
WHERE
recipient_id = '{$_SESSION['user_id']}'
ORDER BY due_date ASC