Can't get query to work - php

I have a database containing 3 tables (member, boat, boatType) and in the method below two of them is affected. What I want is to list all boats that's registered on a member, but there's a problem with the code (at least with the SQL, but I suspect that's not all).
Thanks in advance.
boatHandler.php:
public function GetMembersBoats($memberId) {
$query = "SELECT b.boatId, b.length, bt.type
FROM boat AS b
INNER JOIN member AS m
ON b.memberId = m.memberId
WHERE m.memberId = ?
INNER JOIN boatType AS bt
ON b.boatTypeId = bt.boatTypeId
GROUP BY b.boatId";
$stmt = $this->m_db->Prepare($query);
$stmt->bind_param('i', $memberId);
$boats = $this->m_db->GetBoats($stmt);
}
database.php:
public function GetBoats($stmt) {
$boats = array(
0 => array(),
1 => array(),
2 => array()
);
$stmt->execute();
$stmt->bind_result($boatId, $length, $type);
while ($stmt->fetch()) {
array_push($boats[0], $boatId);
array_push($boats[1], $length);
array_push($boats[2], $type);
}
$stmt->Close();
return $boats;
}
Affected tables:
boat: boatId, boatTypeId, length, memberId
boatType: boatTypeId, type

The WHERE clause has to be listed after the table references. You have to move the WHERE m.memberId = ? to the end of the table references after the FROM and JOINs like so:
SELECT b.boatId, b.length, bt.type
FROM boat AS b
INNER JOIN member AS m
ON b.memberId = m.memberId
INNER JOIN boatType AS bt
ON b.boatTypeId = bt.boatTypeId
WHERE m.memberId = ?
GROUP BY b.boatId

as you in on clause, simply replace 'where' by 'and':
SELECT b.boatId, b.length, bt.type
FROM boat AS b
INNER JOIN member AS m
ON b.memberId = m.memberId
AND m.memberId = ?
INNER JOIN boatType AS bt
ON b.boatTypeId = bt.boatTypeId
GROUP BY b.boatId

Related

What am I doing wrong in this query?

There are three tables,
storing user details
storing groups details
storing user and group ids.
I need to check if a user is already a member of one group. I'm using this query to achieve that:
SELECT u.id, g.id
FROM users u, groups g
INNER JOIN user_groups ug
ON ug.user_id = u.id AND ug.group_id = g.id
WHERE ug.user_id = ? AND ug.group_id = ?
but this is throwing me an error:
Call to a member function bind_param() on boolean in
I have checked if i have misspelled some word in my query and everything is okay.
EDIT:
Here is a function:
public function isUserMember($user_id, $group_id) {
$stmt = $this->conn->prepare("
SELECT u.id, g.id from users u, groups g
INNER JOIN user_groups ug
ON ug.user_id = u.id AND ug.group_id = g.id
WHERE ug.user_id = ? AND ug.group_id = ?");
$stmt->bind_param("ii", $user_id, $group_id); // here i'm getting an error
$stmt->execute();
$stmt->store_result();
$num_rows = $stmt->num_rows;
$stmt->close();
return $num_rows > 0;
}
Try following changes
removed unnecessary join with user table because if you have user_id and group_id you don't need to join it with user
SELECT ug.id, g.id
from user_groups ug
inner join groups g
on ug.group_id = g.id
WHERE ug.user_id = ? AND ug.group_id = ?
Your specific issue Error statement is:
Call to a member function bind_param() on boolean in
at:
$stmt->bind_param("ii", $user_id, $group_id);
What this means is that there is no function bind_param() on boolean (true or false) , so this means your $stmt is a boolean, meaning the statement defining line has returned FALSE.
so:
$stmt = $this->conn->prepare("
SELECT u.id, g.id from users u, groups g
INNER JOIN user_groups ug
ON ug.user_id = u.id AND ug.group_id = g.id
WHERE ug.user_id = ? AND ug.group_id = ?");
This is where the problem is. Others in comments have stated that your SQL query is incorrect, which would result in a boolean fail, however, if it is not your SQL query itself that is failing, then you would need to establish that the $this->conn value has been successfully generated and that it is a valid object entity.
Try to output an error log something like:
if(!$stmt = $this->conn->prepare($sql)){
$errorDump = '
Error 1 '.date("r").' :
';
$errorDump .= $this->conn->error;
$errorDump .= "\n\nBacktrace:\n".print_r(debug_backtrace(),TRUE);
$errorDump .= "
SQL: ".$sql;
error_log($errorDump);
unset($errorDump);
return false;
}
....
//carry on with the query as it's ok
The above is a bit quick and dirty but when your $stmt returns false this error report will tell you why. You can then use that error information to solve your Query or your PHP variable structure.

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."'";

how can i pass this query to my controller in codeigniter and to use this in my foreach in view

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
}
?>

Doctrine 2 ResultSetMapping Many-To-Many example

I'm trying to use ResultSetMappingBuilder to get data from Native query.
$sql = "SELECT e.start_date FROM se_events e
LEFT JOIN se_event_tags tg ON e.id = tg.event_id
LEFT JOIN se_event_type t ON tg.event_type_id = t.id
WHERE t.id = :id";
I have no idea how to build ResultSetMappingBuilder.
public function createResultSetMapping() {
$rsm = new \Doctrine\ORM\Query\ResultSetMappingBuilder($this->getEntityManager());
$rsm->addRootEntityFromClassMetadata('Event', 'e');
return $rsm;
}
Thanks for help in advance.
So I've used row SQL:
$sql = "SELECT e.start_date FROM se_events e
LEFT JOIN se_event_tags tg ON e.id = tg.event_id
LEFT JOIN se_event_type t ON tg.event_type_id = t.id
WHERE t.id = $id";
$stmt = $this->getEntityManager()->getConnection()->prepare($sql);
$stmt->execute();
return $stmt->fetchAll();

PDO query returns 0 when it should return rows

I'm using PHP PDO to run queries. I have the following function:
protected function isStoreRegistered($name, $street1 ,$city, $country_id, $id) {
if($id == '0') {
$sql = " SELECT a.name, b.street1, b.city, c.id
FROM tablea a
LEFT JOIN tableb b ON a.fk_addressID = b.id
LEFT JOIN tablec c ON b.fk_countryID = c.id
WHERE a.name = '$name'
AND b.street1 = '$street1'
AND b.city = '$city'
AND b.fk_countryID = '$country_id'";
$result = $this->db->exec($sql);
} else {
// some other query
}
return $result;
}
The query sent to MySQL looks like this:
SELECT a.name, b.street1, b.city, c.id
FROM sl_store a
LEFT JOIN sl_address b ON a.fk_addressID = b.id
LEFT JOIN sl_country c ON b.fk_countryID = c.id
WHERE a.name = 'test store'
AND b.street1 = 'Weselsgate 2'
AND b.city = 'Oslo'
AND b.fk_countryID = 'NO'
Runnign this query in Toad, returns 1 row.
But if I do a print_r(result), it outputs 0 (zero)
How can I find out what is wrong here?
From the docs:
PDO::exec() does not return results from a SELECT statement.
And since youre not modifying anything (no insert, delete, or update) there are no rows affected, which is what PDO::exec does return.
If you want the data use a prepared statement or PDO::query. If you want the number of rows the use a count in your select.
As mentioned previously and in the manual, PDO::exec() does not return results from a SELECT statement. Instead you should try the following (note the parameter binding):
protected function isStoreRegistered($name, $street1 ,$city, $country_id, $id) {
if ($id == '0') {
$sql = " SELECT a.name, b.street1, b.city, c.id
FROM tablea a
LEFT JOIN tableb b ON a.fk_addressID = b.id
LEFT JOIN tablec c ON b.fk_countryID = c.id
WHERE a.name = :name
AND b.street1 = :street
AND b.city = :city
AND b.fk_countryID = :country";
$stmt = $this->db->prepare( $sql );
$vars = array(
'name' => $name,
'street' => $street1,
'city' => $city,
'country' => $country_id,
);
$result = $stmt->execute( $vars );
} else {
// some other query
}
return $result;
exec is returning the number of rows affected by the statement,
in your case, is zero because you are doing a select
docs:- http://php.net/manual/en/pdo.exec.php
your sql is not using PDO in proper manner,
is vulnerable for SQL injection,
spent some reading on the parameters binding

Categories