I am using zf1. The Modal query is:
$select = $postTable->select()
->setIntegrityCheck(false)
->from('posts')
->joinLeft('users', 'users.id = posts.user_id', array('post_first_name' => 'first_name'))
->where('posts.property_id = ?', $id);
$postTable->fetchAll($select);
I am trying to use prepared statement for this query. I haven't figured out how to convert this into prepared statement so please help me by converting this query into prepared statement.
just use like below
$params = array($property_id);
$sql = "SELECT post_first_name as first_name " .
"FROM posts" .
"left join users on users.id = posts.user_id WHERE posts.property_id = ?";
$stmt = $db->query($sql, $params);
$dealers = $stmt->fetchAll();
above is just procedure code you can set your column name and table name as you require.
Hope this will sure help you.
Related
I am using PDO prepared statements to execute two queries:
SELECT count(*) FROM vocabulary WHERE `type` = :type AND `lesson` = :lesson;
SELECT * FROM vocabulary WHERE `type` = :type AND `lesson` = :lesson limit 100;
The first query to get the count works as expected and i get the row count.
$stmt = $this->connection->prepare($sql);
foreach ($params as $key => $value)
$stmt->bindValue(":" . $key, $value, PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->fetchColumn();
$sql .= " limit $limit;";
$sql = str_replace("count(*)", $columns, $sql);
$stmt = $this->connection->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_CLASS, $class);
But when executing the second query i get:
SQLSTATE[HY093]: Invalid parameter number: no parameters were bound
Therefore, I would like to know, if I have multiple queries where the parameters are exactly the same ,if I need to bind the same parameters again using
foreach ($params as $key => $value)
$stmt->bindValue(":" . $key, $value, PDO::PARAM_STR);
or if there is a way to bind parameters only once.
If I have multiple queries where the parameters are exactly the same, do I need to bind the same parameters again using
Yes, of course.
Parameters are bound to each query, not to PDO or a database globally.
On a side note, with PDO you don't have to bind variables explicitly, so there is a solution to your "problem": just don't bind at all but send your data directly into execute() as it shown in the Dharman's excellent answer
There is no need to modify your SQL like this. Your code basically comes down to this:
$stmt = $this->connection->prepare('SELECT count(*) FROM vocabulary WHERE `type` = :type AND `lesson` = :lesson');
$stmt->execute($params);
$count = $stmt->fetchColumn();
$stmt = $this->connection->prepare('SELECT * FROM vocabulary WHERE `type` = :type AND `lesson` = :lesson limit 100');
$stmt->execute($params);
$result = $stmt->fetchAll(PDO::FETCH_CLASS, $class);
I am using below PHP + MySQL prepare statement to select values from database, passing the variable into the statement using function, however I could not get my wanted result. The problem is I don't know how to using the variable in the prepare statement.
Question:
Could you take a look whether the syntax I am using is correct?
public function getToken($committeeValue){
$stmt = $this->conn->prepare("SELECT u.token FROM users u INNER JOIN committee c ON u.email = c.email WHERE c.'$committeeValue' = 1");
$stmt->execute();
}
Please try the below one.
public function getToken($committeeValue){
$stmt = $this->conn->prepare("SELECT u.token FROM users u INNER JOIN committee c ON u.email = c.email WHERE c.".$committeeValue." = 1");
$stmt->execute();
}
I think you are made a mistake to appending a php variable within the string.Please try this.
You made the mistake of concatenating string in PHP.
So please try this below:
public function getToken($committeeValue){
$committeeValue = trim($committeeValue);
if(!empty($committeeValue)){
$query = "SELECT u.token FROM users u INNER JOIN committee c ON u.email = c.email WHERE c.".$committeeValue." = 1";
$stmt = $this->conn->prepare($query);
$stmt->execute();
}
}
Using var content directly is not safe because it allow to inject SQL statements.
The safe way is, in your case:
public function getToken($committeeValue){
$committeeValue = trim($committeeValue);
if(!empty($committeeValue)){
$query = "SELECT u.token FROM users u INNER JOIN committee c ON u.email = c.email WHERE c.? = 1";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $committeeValue);
$stmt->execute();
}
}
The query will be compiled without the var content so you dont have to worry about SQL injection.
I am converting all my queries from mysql to PDO, and in this process I found a conditional query like a follows
if (isset($parameters['searchTerm'])) {
$where =" And title LIKE '%{$parameters['searchTerm'] }%'";
}
$sql = "Select * from table data Where tableId = 5 {$where} ";
and when I am trying to convert this query in PDO the expected syntax is as follows
if (isset($parameters['searchTerm'])) {
$where =" And title LIKE :searchTerm";
}
$sql = $dbh->prepare("Select * from table data Where tableId = 5 {$where}");
if (isset($parameters['searchTerm'])) {
$sql ->bindParam(':searchTerm', '%{$parameters['searchTerm'] }%');
}
$sql ->execute();
Now as you can See that the if condition if (isset ($parameters ['searchTerm'] )) {...} is repeated twice.
The reason is
I can not prepare the sql query before $where is being set thus $sql variable is initialized after first if statement
I can not bind the parameters until I prepare the sql so it has to be placed after the $sql is being prepared
So there is one if statement before $sql = $dbh->prepare("Select * from table data Where tableId = 5 {$where}"); and one if statement after.
And my question is: Is there a way to remove this redundant if statement or I have to do it this way only.
you can use handy PDO's feature that lets you to send array with parameters straight into execute()
$where = '';
$params = array();
if (isset($parameters['searchTerm'])) {
$where =" And title LIKE :searchTerm";
$params['searchTerm'] = "%$parameters[searchTerm]%";
}
$sql = "Select * from table data Where tableId = 5 $where";
$pdo->prepare($sql)->execute($params);
Note that PHP syntax in your code is also wrong.
Okay so, I don't really know anything about PDO, my friend just asked me to post this here since he's not very good at English. Anyway, this is how he explained it to me:
The code provided is supposed to get a couple of values, save them, and it's supposed to get something out of another table with the help of the values gotten from earlier. The problem according to my friend is that it doesn't get the second value.
Code:
$user_email = $_SESSION['user_email'];
$query = $db->prepare("SELECT username,id,password FROM user WHERE email=:email");
$query->bindParam(':email', $user_email, PDO::PARAM_INT);
$query->execute();
$row = $query->fetch();
$user_username=$row['username'];
$user_group=$row['group'];
$query_group = $db->prepare("SELECT color,name FROM group WHERE id=:id");
$query_group->bindParam(':id', $user_group, PDO::PARAM_INT);
$query_group->execute();
$row = $query_group->fetch();
$group_color=$row['color'];
$group_name=$row['name'];
The word group used as a table name needs to be enclosed in backticks. group is a reserved key word (GROUP BY clause).
SELECT
color,
name
FROM `group`
WHERE id = :id
Using the above would work.
You can shorten the entire code by using a JOIN clause too. As commented above by Prix, the code shall be:
$user_email = $_SESSION['user_email'];
$query = $db->prepare("SELECT
u.username,
u.id,
u.password,
g.color,
g.name
FROM user u
JOIN `group` g
ON g.id = u.id
WHERE u.email = :email");
// I think emails are supposed to be `PDO::PARAM_STR`
$query->bindParam(':email', $user_email, PDO::PARAM_INT);
$query->execute();
$row = $query->fetch();
$user_username = $row['username'];
$group_color = $row['color'];
$group_name = $row['name'];
You don't have group in your select statement .
If you don't use * in your select you must have the field name in your query .
$query = $db->prepare("SELECT username,id,password FROM user WHERE email=:email");
This query gives you only username,id,password back NOT the field group .
so try to use $row['group'] is wrong .
$user_group=$row['group'];
So also put group in your select statement
Place also group in backticks it's a reserved word
$query = $db->prepare("SELECT id, username, password, `group` FROM user WHERE email=:email");
This is also a reason for important variables (e.g for next query) to consider their validity.
if (isset($row['group'])) {
database logic
} else {
error
}
With this simple test you would have found the error itself.
I'm trying to change my SQL queries with prepared statements.
The idea: I'm getting multiple records out of the database with a while loop and then some additional data from the database in the loop.
This is my old SQL code (simplified):
$qry = "SELECT postId,title,userid from post WHERE id='$id'";
$rst01 = mysqli_query($mysqli, $qry01);
// loop trough mutiple results/records
while (list($postId,$title,$userid) = mysqli_fetch_array($rst01)) {
// second query to select additional data
$query05 = "SELECT name FROM users WHERE id='$userid";
$result05 = mysqli_query($mysqli, $query05);
$row05 = mysqli_fetch_array($result05);
$name = $row05[name ];
echo "Name: ".$name;
// do more stuff
// end of while loop
}
Now I want to rewrite this with prepared statements.
My question: is it possible to run a prepared statement in the fetch of another prepared statement ? I still need the name like in the old SQL code I do for the $name.
This is what've written so far.
$stmt0 = $mysqli->stmt_init();
$stmt0->prepare("SELECT postId,title,userid from post WHERE id=?");
$stmt0->bind_param('i', $id);
$stmt0->execute();
$stmt0->bind_result($postId,$title,$userid);
// prepare second statement
$stmt1 = $mysqli->stmt_init();
$stmt1->prepare("SELECT name FROM users WHERE id= ?");
while($stmt0->fetch()) {
$stmt1->bind_param('i', $userid);
$stmt1->execute();
$res1 = $stmt1->get_result();
$row1 = $res1->fetch_assoc();
echo "Name: ".$row1['name'] ;
}
It returns an error for the second statement in the loop:
Warning: mysqli_stmt::bind_param(): invalid object or resource mysqli_stmt in ...
If I use the old method for the loop and just the prepared statement to fetch the $name it works.
You can actually do this with a single JOINed query:
SELECT p.postId, p.title, p.userid, u.name AS username
FROM post p
JOIN users u ON u.id = p.userid
WHERE p.id = ?
In general, if you are running a query in a loop, there is probably a better way of doing it.