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

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.

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.

php mysql select something and get columns from other tables

I'm using prepared statements and I need to "select" other table, apart from these two, to get data but I get this:
Fatal error: Call to a member function bind_param() on a non-object in C:\xampp\htdocs\views\user\referral.php on line 16
If I add in SELECT table1.* , table.* , "theothertable.*"
$stmt = $mysqli->prepare("SELECT friends.*, rc_usuario.* // or just *
FROM friends
INNER JOIN rc_usuario ON rc_usuario.id = friends.friendID
WHERE friends.userID = ?");
$stmt->bind_param('s', $connectedUserID);
This is working fine, I get what i need, but I also need to get data from another table and I can't make other select because i need it all in a while to print all the data together.
The question is, can I SELECT something like that from 2 tables and also get data from other table/s?
Thank YOU!
EDIT: Add the new statement:
if ($stmt = $mysqli->prepare("SELECT friends.*, members.*, account_type.*
FROM friends
INNER JOIN members ON members.id = friends.friendID
INNER JOIN account_type ON account_type.name = members.acc_type
WHERE friends.userID = ? AND members.acc_type = ?")) {
$stmt->bind_param('is', $connectedUserID, $connectedAcc_type);
$stmt->execute();
} else echo $mysqli->error;
You can join more tables by using another INNER JOIN, like as follows;
INNER JOIN rc_usuario ON rc_usuario.id = friends.friendID
INNER JOIN rc_another ON rc_another.col = friends.coljoin
Just make sure you select all the columns you want in the joined table.
It might also help to run your prepare statement in an if, like this;
if($stmt = $mysqli->prepare("SELECT ...")) { // ... where the rest of your query is
$stmt->bind_param('s', $connectedUserID);
$stmt->execute();
}
else {
echo $mysqli->error;
}
which will give you an idea of any problems with the SQL syntax.
Hope this helps.

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();

combining two mysql queries in php

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 );

inner join wont work with mysqli prepared statement in php

I can't seem to get this statement or statements alike to work with prepared queries, the code works just fine below:
$DBH = getDBH();
$stmt = $DBH->prepare("SELECT a.id, a.title, a.photo FROM tag t INNER JOIN tag_reference atx ON t.tag_id = atx.tag_id
INNER JOIN articles a
ON atx.article_id = a.id
WHERE t.tag_name = 'example'");
$stmt->execute();
$stmt->bind_result($id,$title,$photo);
$stmt->fetch();
but when I change t.tag_name = '?' it gives me an error that the amount of parameters do not match. This is the statement that does not work.
$DBH = getDBH();
$stmt = $DBH->prepare("SELECT a.id, a.title, a.photo FROM tag t INNER JOIN tag_reference atx ON t.tag_id = atx.tag_id
INNER JOIN articles a
ON atx.article_id = a.id
WHERE t.tag_name = '?'");
$stmt->bind_param('s',$example);
$stmt->execute();
$stmt->bind_result($id,$title,$photo);
$stmt->fetch();
Can anyone please help?
The placeholder ? does not work if enclosed in single quotes. In this case the SQL tokenizer will catch it as literal string.
Change it to:
WHERE t.tag_name = ? ");
When using placeholders, do you need to use quotes? Most placeholder languages I've used don't.
WHERE t.tag_name = ?"

Categories