What am I doing wrong in this query? - php

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.

Related

Why does my PHP MYSQL Query not work with SUM?

I don't get it.
This PHP - MYSQL query does work:
$sql = mysqli_prepare($conn, 'SELECT O.*
FROM OFFER O
LEFT JOIN EVENT E ON E.OFFER_ID = O.KEY_ID
LEFT JOIN BOOKING B ON B.EVENT_ID = E.KEY_ID
WHERE O.KEY_ID = ? ');
$sql->bind_param('i', $keyId);
With SUM statement it doesn't work:
$sql = mysqli_prepare($conn, 'SELECT O.*,
SUM(CASE WHEN B.KEY_ID IS NULL THEN 0 ELSE 1 END) AS BOOKING_COUNT
FROM OFFER O
LEFT JOIN EVENT E ON E.OFFER_ID = O.KEY_ID
LEFT JOIN BOOKING B ON B.EVENT_ID = E.KEY_ID
WHERE O.KEY_ID = ? ');
$sql->bind_param('i', $keyId);
Error message:
Uncaught Error: Call to a member function bind_param() on boolean in ..snippet-ops.php(361) : eval()'d code:107
The query works in phpmyadmin though.Does anyone know why?
EDIT: SOLVED: The accepted Answer contains the solution in the comments (turning on report and a GROUP BY solved the issue.
EDIT2: When downgrading a question it would be good to know why otherwise the downgrade is useless.
Try surrounding your query string with double quotes instead of single quotes. Beware, that prepare might return false instead of a statement object. You should check this and react accordingly. Also make sure to close your statement after you're done with it.
Here (not tested):
<?php
$sql = "
SELECT O.*, SUM(CASE WHEN B.KEY_ID IS NULL THEN 0 ELSE 1 END) AS BOOKING_COUNT
FROM OFFER O
LEFT JOIN EVENT E ON E.OFFER_ID = O.KEY_ID
LEFT JOIN BOOKING B ON B.EVENT_ID = E.KEY_ID
WHERE O.KEY_ID = ?
GROUP BY O.KEY_ID";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("i", $keyId);
$stmt->execute();
// do stuff with $stmt
$stmt->close();
} else {
echo $stmt->error;
}
?>
UPDATE: As can be seen in the comments, it was necessary to group by the column O.KEY_ID, or the prepare would return false.

Select and unlink file on 3 tables

Please help me to check my query. I have search a lot and I have'nt try to select 3 tables before.
I think I got it right but I dont know why there's nothing happen.
public function delSection($delete_id)
{
$stmt = $this->conn->prepare("SELECT * FROM tbl_section
JOIN tbl_login ON (tbl_login.sec_id = tbl_section.sec_id)
JOIN tbl_content ON (tbl_content.sec_id = tbl_section.sec_id)
WHERE tbl_section.sec_id=:del_id");
$stmt->execute(array(":del_id"=>$delete_id));
while($linkRow=$stmt->fetch(PDO::FETCH_ASSOC))
{
unlink(__DIR__."/Admin/cover_images/".$linkRow['sec_cover']);
unlink(__DIR__."/Admin/Files/".$linkRow['sec_id']."/".$linkRow['file_name']);
rmdir(__DIR__."/Admin/Files/".$linkRow['sec_id']);
}
$stmt2 = $this->conn->prepare("DELETE tbl_section, tbl_login, tbl_content FROM tbl_section
JOIN tbl_login ON (tbl_login.sec_id = tbl_section.sec_id)
JOIN tbl_content ON (tbl_content.sec_id = tbl_section.sec_id)
WHERE tbl_section.sec_id=:del_id");
$stmt2->bindparam(":del_id",$delete_id);
$stmt2->execute();
return true;
}
What I am trying to do is to select * from 3 tables and fetch their data with fk sec_id
here's the manual running of query
link:
Code:
Done With LEFT OUTER JOIN QUERY
$stmt = $this->conn->prepare("SELECT * FROM tbl_section
LEFT OUTER JOIN tbl_login ON (tbl_login.sec_id = tbl_section.sec_id)
LEFT OUTER JOIN tbl_content ON (tbl_content.sec_id = tbl_section.sec_id)
WHERE tbl_section.sec_id=:unlink_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
}
?>

PHP / PDO : query request works, prepared request doesn't

I would like to user prepared request with PDO but it doesn't seem to return any result while the query request do return some.
Here, there are my two requests :
Prepared request :
$req = $this->bdd->prepare('SELECT u.id, u.username, hm.desc, s.name AS shop, hm.amount, hm.date FROM history_members AS hm LEFT JOIN users AS u ON u.id = hm.user_id LEFT JOIN shops AS s ON s.id = hm.shop_id WHERE hm.user_id = :id');
$req->bindValue(':id', $id, PDO::PARAM_INT);
$data = $req->fetchAll(PDO::FETCH_ASSOC);
$req->closeCursor();
Query request :
$req = $this->bdd->query('SELECT u.id, u.username, hm.desc, s.name AS shop, hm.amount, hm.date FROM history_members AS hm LEFT JOIN users AS u ON u.id = hm.user_id LEFT JOIN shops AS s ON s.id = hm.shop_id WHERE hm.user_id = '.$id);
$data = $req->fetchAll(PDO::FETCH_ASSOC);
$req->closeCursor();
What am I doing wrong with the prepared request ?
you did not execute your query.
First execute query then fetch the result.

Can't get query to work

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

Categories