Left join using PDO - php

I am using the following PDO query:
<?php
$cadena = $_SESSION[Region];
// We Will prepare SQL Query
$STM = $dbh->prepare("SELECT `id_mesero`, `nombre_mesero`,`alias_mesero`, `rest_mesero` FROM tbmeseros WHERE cadena_mesero='$cadena'");
// For Executing prepared statement we will use below function
$STM->execute();
// we will fetch records like this and use foreach loop to show multiple Results
$STMrecords = $STM->fetchAll();
foreach($STMrecords as $row)
{
The value from the 'rest_mesero' field is the index from the table 'tbrestaurantes'.
I would need to join some fields values from 'tbrestaurantes' to the PDO query, but I don't know how to do it using PDO.
Any help is welcome.
UPDATED QUESTION TEXT
This is my proposal for the query :
$dbh->prepare("SELECT * FROM tbmeseros LEFT JOIN tbrestaurantes ON tbmeseros.rest_mesero = tbrestaurantes.id_restaurante WHERE tbmeseros.cad_mesero = ?");
But is show an error:
Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[HY093]: Invalid parameter number: no parameters were bound in /.../AdminMeseros.php on line 80
Line 80 is
$STM->execute();
This is my updated query:
<?php
$cadena = $_SESSION[Region];
$STM =$dbh->prepare("SELECT * FROM tbmeseros LEFT JOIN tbrestaurantes ON tbmeseros.rest_mesero = tbrestaurantes.id_restaurante WHERE tbmeseros.cad_mesero = ?");
$STM->bindParam(1, $cadena);
// For Executing prepared statement we will use below function
$STM->execute(array($cadena));
// we will fetch records like this and use foreach loop to show multiple Results
$STMrecords = $STM->fetchAll();
foreach($STMrecords as $row)
{
And here table's screenshots:
For tbmeseros:
For tbrestaurantes:
The value of $cadena is 'HQ3'.

When you put a parameter in the SQL, you need to supply the value for the parameter. There are two ways to do that:
1) Call bindParam():
$STM->bindParam(1, $cadana);
2) Provide the values when calling execute():
$STM->execute(array($cadana));

You need to fill the ? in the query:
$q = $dbh->prepare("SELECT * FROM tbmeseros LEFT JOIN tbrestaurantes ON tbmeseros.rest_mesero = tbrestaurantes.id_restaurante WHERE tbmeseros.cad_mesero = ?");
$q->bindValue( 1, 'x' );
$q->execute();
print_r( $q->fetchAll( PDO::FETCH_ASSOC );
In prepare you can use '?' and then bindValue to attach an escaped value to the query. Your query doesn't appear to have this and that is the cause of the error.

Related

PDO prepared statement bind parameters once for different queries

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

store sql statement in MySQL then run it

Is it possible to store the following SQL statement in MySQL then run it in a prepared statement?
Mysql table:
Table name: mystatements
Columns:id, statements
The following syntax is stored in the statements field:
SELECT id, AES_DECRYPT(secret,'$key') as txtsecret
FROM TABLE_1
Now in php:
first: I do a select query to get my statement
$stmt = $mysqli->prepare("SELECT statements FROM mystatements limit 1");
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$statement.=$row['txtstatement'];
}
second: using the variable ($statement) from the the query above and add it to query below to run the in the prepared statement:
$key='password123';
$stmt = $mysqli->prepare($statement);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['txtsecret'];
}
Also my stored syntax contains AES_DECRYPT(secret,'$key') just to complicate things. is what i'm trying to achieve possible? have I gone about this completely the wrong way?
Ok..
$key='password123';
$sql = str_replace('$key', $key, $statement); //replace $key to correct value
$stmt = $mysqli->prepare($sql);
Result:
SELECT id, AES_DECRYPT(secret,'$key') as txtsecret FROM TABLE_1
to
SELECT id, AES_DECRYPT(secret,'password123') as txtsecret FROM TABLE_1

MSSQL php pdo pagination, some thing wrong on bindParam

Working fine with MsSQL:
$ppage = 15;
$poset = 0;
$stmt = "SELECT * FROM tbl ORDER BY ID OFFSET {:$poset } ROWS FETCH NEXT {:ppage } ROWS ONLY";
$stmt = $this->conn->prepare($stmt);
$stmt->execute();
return $row = $stmt->fetchAll();
Not working fine with MsSQL:
$ppage = 15;
$poset = 0;
$stmt = "SELECT * FROM tbl ORDER BY ID OFFSET :poffset ROWS FETCH NEXT :perpage ROWS ONLY";
$stmt = $this->conn->prepare($stmt);
$stmt->bindParam(':poffset', $poset);
$stmt->bindParam(':perpage', $ppage);
$stmt->execute();
return $row = $stmt->fetchAll();
the query is fine with I use to run with variables actual data it works but it's not working when I set the variable by bindParam, when am I missing.
thanks in advance.
Try using bindValue instead:
$stmt = $this->conn->prepare($stmt);
$stmt->bindValue(':poffset', $poset, PDO::PARAM_INT);
$stmt->bindValue(':perpage', $ppage, PDO::PARAM_INT);
$stmt->execute();
Rather than using the bindParam() function, inside of the parameters of the execute() function, add an array containing the values.
Something like this:
$stmt = $this->conn->prepare($stmt);
$stmt->execute(array(':poffset' => $poset, ':perpage' => $ppage)); // using an array rather than the bindValue function.
Use it as you would normally with the bindParam function, but substitute the commas for =>.
This way of doing things will save you having to call the bindParam() function for each value & will still protect against SQL Injection.

MySQL WHERE IN () + AND , PDO returns only one row

following query returns all wanted results if entered in phpmyadmin:
SELECT postid, voting
FROM postvotes
WHERE userid = 1
AND postid IN
(1007,1011,1012,1013,1014,
1015,1016,1017,1018,1019,1020,1021,1023,1025,1026,
1027,1028,1029,1030,1031)
But PDO fails to fetchAll(). It just returns the first match like fetch().
What's wrong?
PHP Code:
private function userPostVotings( $postIDs ) {
// $postIDs contains a string like 1,2,3,4,5,6,7...
// generated through implode(',', idArray)
try {
$userPostVote = $this->_db->prepare('SELECT postid, voting
FROM postvotes
WHERE userid = ?
AND postid IN ( ? )');
$userPostVote->setFetchMode(\PDO::FETCH_ASSOC);
$userPostVote->execute( array( $this->_requester['id'], $postIDs ) );
while ( $res = $userPostVote->fetch() ) {
var_dump( $res );
}
} catch (\PDOException $p) {}
}
If I echo out the query used in this method and fire it through phpmyadmin I get the correct number of results. However PDO gives just the first. No matter if a loop with fetch() or fetchAll().
You cannot bind array in prepared statements in PDO.
Reference:
Can I bind an array to an IN() condition?
it is not PDO's fetchAll() of course, but your query.
Which is not
IN (1007,1011,1012,1013,1014)
but
IN ('1007,1011,1012,1013,1014')
and of course it will find only first value as this string will be cast to the first number
One have to create a query with placeholders representing every array member, and then bind this array values for execution:
$ids = array(1,2,3);
$stm = $pdo->prepare("SELECT * FROM t WHERE id IN (?,?,?)");
$stm->execute($ids);
To make this query more flexible, it's better to create a string with ?s dynamically:
$ids = array(1,2,3);
$in = str_repeat('?,', count($arr) - 1) . '?';
$sql = "SELECT * FROM table WHERE column IN ($in)";
$stm = $db->prepare($sql);
$stm->execute($ids);
$data = $stm->fetchAll();

Multiple prepared statements (SELECT)

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.

Categories