Is it bad practice to use variable inside pdo query? [closed] - php

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have a PHP PDO query like this:
$update = $pdo->query("UPDATE login_users SET lastactivity = '$lastactivity' WHERE user_id = 1");
I like to do this way because I think my code looks better.
Is it ok to do this way? Or should I do like this:
$params = array(
':id' => $_SESSION['jigowatt']['user_id'],
':lastactivity' => $lastactivity,
);
$update = $pdo->query('UPDATE login_users SET lastactivity = :lastactivity WHERE user_id = :id', $params);

I have a PHP PDO query like this:
By no means you should have code like this.
Or should I do like this
Neither you are bound to write a prepared statements like that. There are other ways. For example, nobody's forcing you to use named placeholders. You can use positional, they are much more concise:
$sql = "UPDATE login_users SET lastactivity = ? WHERE user_id = ?";
$pdo->prepare($sql)->execute([$lastactivity],$_SESSION['jigowatt']['user_id']);

This is example of PDO "query wrapper":
public function sendQuery($queryString, array $queryParams = array())
{
try {
$stmt = $this->_PDO->prepare($queryString);
$stmt->execute($queryParams);
} catch (\PDOException $e) {
if ($this->_PDO->inTransaction()) {
$this->_PDO->rollBack();
}
throw $e; // this line for example only (see comments of this answer)
}
return $stmt;
}
Can be use like this:
$conn = \DBI::getConnection(); // DBI return DBC object
$x = $conn->sendQuery(
'SELECT x FROM tbl WHERE y = :y',
[':y' => $y]
)->fetch(\PDO::FETCH_COLUMN);

Related

Which PDO prepared statement is preferrable, they both work [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
both of these PDO prepared statements work. Which one is preferrable or more secure.
//do not include id in prepare as it is auto increment
//version 1
$sql = "INSERT INTO `wbs_prod_ratings_archive` (`prodid`, `ratedate`, `ratestamp`, `rating`, `prod_owner`, `buyerid`, `buyername`, `verified_buyer`)
VALUES (:p,:r,:s,:t,:o,:b,:n,:v)";
$stmt = $this->pdo->prepare($sql);
$stmt->bindParam(':p', $newdata['prodid'], PDO::PARAM_INT);
$stmt->bindParam(':r', $newdata['ratedate']);
$stmt->bindParam(':s', $newdata['ratestamp'], PDO::PARAM_INT);
$stmt->bindParam(':t', $newdata['rating'], PDO::PARAM_INT);
$stmt->bindParam(':o', $newdata['prod_owner'], PDO::PARAM_INT);
$stmt->bindParam(':b', $newdata['buyerid'], PDO::PARAM_INT);
$stmt->bindParam(':n', $newdata['buyername']);
$stmt->bindParam(':v', $newdata['verified_buyer']);
$result = $stmt->execute();
//version 2
$p = (int) $newdata['prodid'];
$r = $newdata['ratedate'];
$s = (int) $newdata['ratestamp'];
$t = (int) $newdata['rating'];
$o = (int) $newdata['prod_owner'];
$b = (int) $newdata['buyerid'];
$n = $newdata['buyername'];
$v = $newdata['verified_buyer'];
//all int other than ratedate, buyername, verified buyer
$sql = "INSERT INTO `wbs_prod_ratings_archive` (`prodid`, `ratedate`, `ratestamp`, `rating`, `prod_owner`, `buyerid`, `buyername`, `verified_buyer`)
VALUES ($p, '$r', $s, $t, $o, $b, '$n', '$v')";
$stmt = $this->pdo->prepare($sql);
$result = $stmt->execute();
PS I originally had it written doing (?,?,?,?,?,?,?,?) method but i could never get it working. It appears the issue was that which ever way i chose to do it, i had to specify which items were (int) and i never could get it working using that format.
The version 1 option binds them to INT.
The version 2 option sets then to int via PHP (int) and then the strings are quoted in the values array.
So the above two options do work, both tested. Is there a preferrable option?
Only the first is a prepared statement, and it's definitely better. The second one isn't actually a prepared statement, and is horrifically vulnerable to SQL injection, which is the exact thing that real prepared statements protect you from.

Turning a HTML form input into an PDO variable [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I want the user to specifiy a number, this number will be used in my SQL statement when connecting to the database. If the user inputs five I want the five first rows in the table to be displayed.
If i write "SELECT * FROM TABLE WHERE ID <= 5" it works, but my variable is being fetched from a form. When I use $variable = $_POST['variable'] and print it out using "SELECT * FROM TABLE WHERE ID <= $variable" no results are being returned. Why is that?
you need to bind that variable if you use PDO.
try {
$conn = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("SELECT * FROM TABLE WHERE ID <= :id");
// bind params
$stmt->bindParam(":id", $_POST['variable']);
$stmt->execute();
// fetch with
// $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "OK";
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
According to http://www.w3schools.com/php/php_mysql_prepared_statements.asp
Looked through the code once again, just a simple typo:
Works with:
$sql = 'SELECT * FROM sql WHERE id <= ' . $items;
Before this I had
$sql = 'SELECT * FROM sql WHERE id <= $items';

php decode special entities in mysql [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am very new to PDO and I am trying to decode all the rows in my table "test" which contains special entities for instance "('L& eacute;on: The Professional')" instead of "Léon:The Professional".
So, here is what I tried:
<?php
require_once('connection.php');
$stmt = $conn->prepare("SELECT * from test");
$stmt->execute();
while ($results = $stmt->fetch()){
$b = html_entity_decode($stmt);
echo $b;
}
but I have no output printed..
Could someone kindly help me fix it?
prepare() returns a statement object ($stmt in your case)
fetch() returns associative array where the index would be the column name
$sql = "SELECT column1, column2, column3 from test";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = array()
while ($row = $stmt->fetch()){
$resutlt[] = array('column1' => html_entity_decode($row['column1']),
'column2' => html_entity_decode($row['column2']),
'column3' => html_entity_decode($row['column3'])
);
}
var_dump($result);
return $result;
EDIT: to replace the values
//prepare select
$sql = "SELECT id, column1, column2, column3 from test";
$stmt = $conn->prepare($sql);
$stmt->execute();
//prepare update
$update_sql = "UPDATE test SET column1=?,column2=?,column3=? WHERE id = ?;";
$update_stmt = $conn->prepare($update_sql);
while ($row = $stmt->fetch()){
//update
$update_stmt->execute(array(html_entity_decode($row['column1']),
html_entity_decode($row['column2']),
html_entity_decode($row['column3']),
$row['id']
);
}
You did not define $query, thus it has no execute() function. If you wish to execute your prepared statement, you should call $stmt->execute().

how to make mysqli prepared statement and fetch result? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I can't understand how to create a prepared statement, and all tutorials I have seen was fetching only column.
My normal sql query
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM files WHERE id=$id ") or die(mysql_error());
$row = mysql_fetch_array($result);
$name = $row['name'];
$date = $row['date'];
Please show me how to create a prepared statement and how to fetch more than one column and insert the date into variables.
First of all it's not a good idea to use SELECT * in production. Instead specify needed columns explicitly. Take a look at https://stackoverflow.com/a/65532/1920232.
Now your code might look like
$id = $_GET['id'];
$db = new mysqli('localhost', 'user', 'password', 'dbname');
$sql = 'SELECT name, date FROM files WHERE id = ?'; //specify columns explicitly
if ($stmt = $db->prepare($sql)) { //create a prepared statement
$stmt->bind_param('i', $id); //bind parameters
$stmt->execute(); //execute query
$stmt->bind_result($name, $date); //bind result variables
$stmt->fetch(); //fetch values
}
$db->close();
echo $id, ' ', $name, ' ', $date;
Note: All error handling intentionally skipped for brevity.

How to use PDO Statement to Bind a for loop index? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have two MySQL query statements that’s need to be convered to PDO using prepare and
BindParam. Any help is appreciated. Thanks.
Here is the problem:
The two non PDO statements are in a for loop and are setup like this:
for ($i = 0; $i < $numItem; $i++)
{
// some codes…, then
$sql = "SELECT pd_name, pd_qty, pd_type
FROM ct_products
WHERE pd_id = ".$productId[$i]."";
$result = dbQuery($sql);
// Some more codes goes here, then.....the 2nd query
$sql = "UPDATE ct_car
SET ct_qty = $newQty
WHERE ct_id = {$carId[$i]}";
dbQuery($sql);
// Some more code, some more codes goes here
// end the for loop
Now, for the new PDO statements, I would like to do something like this to replace the two statements in the for loop above:
// check stock
$sql = "SELECT pd_name, pd_qty, pd_type
FROM ct_products
WHERE pd_id = :productId[$i]";
try
{
// Build the database statement
$stmt = $this->_db->prepare($sql);
$stmt->bindParam(":productId[$i]", $productId[$i], PDO::PARAM_INT);//not sure here
$stmt->execute();
// more code here....
// more codes...
// then the next sql pdo statement:
// update
$sql = "UPDATE ct_car
SET ct_qty = :newQty
WHERE ct_id = {$carId[$i]}";
try
{
// Build the database statement
$stmt = $this->_db->prepare($sql);
$stmt->bindParam(":newQty", $newQty, PDO::PARAM_INT);
$stmt->bindParam(":cartId[$i]", $cartId[$i], PDO::PARAM_INT); // not sure here
$stmt->execute();
$count = $stmt->rowCount();
//more codes....
// code continues....
//end for
Have a look at http://php.net/manual/de/pdostatement.bindparam.php.
The placeholder needs to be a string or a ? sign. (But you cannot mix named placeholders with ? placeholders)
$sql = "SELECT pd_name, pd_qty, pd_type
FROM ct_products
WHERE pd_id = :productId";
$stmt->bindParam(":productId", $productId[$i], PDO::PARAM_INT);
// update
$sql = "UPDATE ct_car
SET ct_qty = :newQty
WHERE ct_id = :cartId";
$stmt->bindParam(":newQty", $newQty, PDO::PARAM_INT);
$stmt->bindParam(":cartId", $cartId[$i], PDO::PARAM_INT);
PDO::PARAM_INT is right if it's really an integer value. The default if you don't set it is PDO::PARAM_STR.
Another thing: you could get into troubles with bindParam because the variable is bound as a reference. In your case it should not matter because you're running execute immediate after the binding. Else have a look at bindValue which you can use in the same way.

Categories