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.
Related
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);
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().
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.
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 7 years ago.
Improve this question
I cannot find any documentation that adequately explains how to use them. How to you retrieve variables from a query and use them and what do the parameters mean to the queries? I want to make my website safe from sql injection and I don't have a clue how to get the following code optimized for safety. I understand how sql injection works, I just don't know how to create the prepared statements or retrieve queries.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$tempProf = $_POST["professor"];
$tempProfArray = explode("=",$tempProf);
$prof = $tempProfArray[1];
$tempName = $_POST["name"];
$tempNameArray = explode("=",$tempName);
$name = $tempNameArray[1];
$tempNum = $_POST["number"];
$tempNumArray = explode("=",$tempNum);
$num = $tempNumArray[1];
$tempSec = $_POST["section"];
$tempSecArray = explode("=",$tempSec);
$section = $tempSecArray[1];
$tempCat = $_POST["category"];
$tempCatArray = explode("=",$tempCat);
$category = $tempCatArray[1];
$con=mysqli_connect("localhost","root","*******","******");
$result = mysqli_query($con,"SELECT * FROM professors where id='$prof'");
$row = mysqli_fetch_array($result);
if(empty($prof) || empty($name) || empty($num) || empty($section) || empty($category))
{
echo "emptyField";
}
elseif(!is_numeric($num) || !is_numeric($section))
{
echo "NaN";
}
elseif(empty($row))
{
mysqli_query($con,"INSERT INTO classes (className, classNumber, section, classCategory)
VALUES ('$name','$num','$section','$category')");
$classTemp = mysqli_query($con,"SELECT id FROM classes where className='$name' and classNumber='$num' and section ='$section'");
$classTempArray = mysqli_fetch_array($classTemp);
$classId = $classTempArray['id'];
mysqli_query($con,"INSERT INTO professors (name, classes) VALUES ('$prof','$classId')");
$profTemp = mysqli_query($con,"SELECT id FROM professors where name='$prof'");
$profTempArray = mysqli_fetch_array($profTemp);
$profId = $profTempArray['id'];
mysqli_query($con,"UPDATE classes SET professor = '$profId' WHERE id = '$classId'");
echo "success";
}
else
{
$profName = $row['id'];
mysqli_query($con,"INSERT INTO classes (professor, className, classNumber, section, classCategory)
VALUES ('$prof', '$name','$num','$section','$category')");
echo "success";
}
?>
In general, something like this will suffice (note that I use the object orientated way of accessing connections, not procedural like you)
$stmt = $con->prepare( 'INSERT INTO classes (professor, className, classNumber, section, classCategory) VALUES (?, ?, ?, ?, ?)' )
$stmt->bind_param( 'ssiss', $prof, $name, $num, $section, $category );
$stmt->execute();
In this case I am assuming that everything but $num is a string, and $num is an integer.
Here is the relevant doc for binding params: http://www.php.net/manual/en/mysqli-stmt.bind-param.php
$sql="SELECT id FROM classes WEHERE className=? AND classNumber=? AND section =?";
$stmt =$con->prepare($sql);
$stmt->execute(array($name,$num,$ection));
//you can apply this for other queries
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.