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 8 years ago.
Improve this question
When should I use prepared statements? For any sort of query or just
specific kinds?
Should I be using prepared statements for SELECTING, or INSERTING, both, etc?
When should I not use them?
Thanks.
Prepared statements should be used for queries containing parameters. Otherwise, they are a waste of resources.
Example:
$pdo->query("SELECT * FROM `table`"); //No need for preparing here, no parameters.
However
$pdo->prepare("SELECT * FROM `table` WHERE `id` = :id"); //Prepare.
When should I use prepared statements? For any sort of query or just specific kinds?
For any sort preferably. Especially if you have a dedicated function or class for running queries. In such a case there should be just single method for running all the queries, no matter if they have dynamical parts or not.
Not to mention that all-static a query like "SELECT * FROM table" is a rare thing outside of sandbox.
Should I be using prepared statements for SELECTING, or INSERTING, both, etc?
Doesn't matter. The idea is to represent every dynamical value in the query with placeholder. the query type absolutely doesn't matter.
When should I not use them?
This question is quite similar to the first one. You would do yourself a mighty favor if use prepared statements all the way.
You should use prepared statements and parametrized queries whenever you are going to be using data that comes from anywhere outside of your program. That includes any interactions with the database, whether a INSERT, DELETE or UPDATE, or even a SELECT.
If you build SQL statements using data from the outside, you are in danger.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am developing an application to produce printed reports from a MySQL database. This uses layout files to define what data to retrieve and how to format the output. The data to be retrieved is defined by a select statement which could vary from a simple view to something very complicated. Obviously, validation of the layout requires analysis of the select statement, which is simple under mysqli - prepare the statement then use mysqli_stmt::result_metadata.
The well documented problems of calling mysqli_stmt::bind_params with dynamicly varying parameter counts has prompted me to look at PDO, but there I have the problem that the prepared query must be executed before PDOStatement::getColumnMeta can be used to identify column names. Is there a way to identify prepared select statement column names without executing the statement?
I guess you want to get the name and data type of each column in your result set, then use that information to help lay out your report.
The most reliable way to do this is to execute() the query. That puts absolute control of the columns and data types in the hands of the person who writes and troubleshoots the SQL in your layout file. I don't believe there's a reliable MySQL statement parser you can use in php to dig out aliases and data types from just the SQL.
Both PDO and mysqli require you, the programmer, to execute the query to get the metadata.
If you can organize your report program so it concludes its layout after it fetches a row of the result set, that's a good way to go.
Or you can execute the query once appending LIMIT 1, do the layout, and execute it again to get the data. But your more complex queries may not benefit much from that attempted optimization. And queries already containing a limit just won't work in this scheme.
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 6 years ago.
Improve this question
foreach($array as $values){
$MySQL_string = "
UPDATE `MyGuests` SET `firstname` ='".$values['name]."' WHERE `id` ='".$values['user]."';
";
$DB->mysqli->query($MySQL_string);
}
Are there any downfalls to performing multiple PHP MySQL queries in a for loop?
It's perfectly fine to run SQL queries in a loop in PHP as long as you know what you're doing.
If you loop queries all over the place and/or on most page-loads, or on a scale large enough to hinder your server's performance, you should look into refactoring your code/application logic and find more performance-friendly options. This is unlikely to be the case with INSERT and UPDATE queries. If you're running lots of SELECT statements in a loop, however, you're probably doing something wrong.
You could avoid a loop by using mysqli_multi_query(). However it'll make debugging individual queries more difficult. Also it won't allow you to use prepared statements (a very good idea for both performance and security reasons). There's nothing inherently evil about loops. Don't worry too much about (premature) optimization for operations that aren't the churning core of your application.
Depending on your interpretation, it might be correct to run multiple queries in a loop. However, for optimal performance, it is best to reduce the queries to a minimal number of queries.
One way this can be done with your example is to use a CASE statement. See this article for more information, and the example below, based on your sample code.
Also, while this isn't codereview.stackexchange.com, it is recommended that you prepare statements and bind parameters instead of placing values inline, so as to avoid the possibility of a SQL injection attack. See this answer where parameters are bound for the INSERT statement.
$cases = array();
$whereConditions = array();
foreach($array as $values){
$cases[] = 'WHEN `id` = '.$values['user'].' THEN \''.$values['name'].'\'';
$whereConditions[] = '`id` = \''.$values['user'].'\'';
}
$MySQL_string = "UPDATE `MyGuests` SET `firstname` = CASE ".implode(' ',$cases)." END WHERE ".implode(' OR ',$whereConditions);
$DB->mysqli->query($MySQL_string);
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 6 years ago.
Improve this question
I would like to know how to make a php file safer in general. I actually use mysqli, which is unfortunately not the newest version anymore, I know. I mysqli_escape_str...() all strings entered in input fields, too. But do you have some tips regarding the safety. I also use some ajax, if you need to know that.
This is a huge subject and it depends what you're using at the moment but by the sounds of it I would suggest things like PDO instead of mysqli as this uses prepared statements. Its impossible for a SQL injection attack when using prepared statements properly. As for the AJAX you could ensure you are using CSRF tokens.
In general you can find a lot of the security risks here: https://www.owasp.org/index.php/OWASP_Top_Ten_Cheat_Sheet and some ways to mitigate them.
When you deal with queries in database, you have to make sure that there's no sql injection. Now because you already know mysqli_escape_str, I will suggest you something better : use prepared queries.
Here's an example:
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
// insert another row with different values
$name = 'two';
$value = 2;
$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 7 years ago.
Improve this question
The most common suggestion for protection against MySQL injection is prepared statements (either from PDO of mysqli). Say for whatever reason, I can't use prepared statemnets...how do I protect my data?
I would love to create a function like the following...
function cleanse($val) {
global $db;
$val = $db->real_escape_string($val);
return $val;
}
//Then I use it like
$sql = "select abc from dyf where z='".cleanse($_GET['id'])."'";
$db->query($sql); //etc...
But I'm not sure if that stops 1=1 attacks and attacks from strange foreign characters.
Is there a bullet proof way to make my cleanse function secure (no prepared functions!)?
Do I need to convert any string to utf-8?
If I wrap all column values in quotes and use mysqli's real_escape_string, am I ok?
Are there any other tricks that would make my cleanse function safe against injection?
I won't recommend it, but using mysql_real_escape_string can do the trick.
$sql = "select abc from dyf where z='".mysql_real_escape_string($_GET['id'])."'";
But if you can use PDO use it anyday, if you are limited this would be an oportunity. Only works in some versions of PHP.
http://php.net/manual/en/function.mysql-real-escape-string.php
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 8 years ago.
Improve this question
I am coding a social debating application, and I am worried about the security of prepared statements. Why does it bother me so much? Because social networks take massive amounts of user data and some may be malicious.
I just want to know if MySQLi's prepared statements feature enough to protect from the most common types of SQL injection. This has probably been asked before somewhere on the web, but, with the massive amount of outdated information in the net, it is very hard to know if there's been anything found about it.
I've heard various exploits on PDO, for example, yet some sites say there's no exploits. That's where confusion comes in. I understand that many exploits are found each day. But at least to protect from the most popular exploits.
And, if there are any additional methods of protecting SQL queries, please point them out in your answer.
Prepared statements are a good way to prevent MySQL injection. But what about XSS attacks? Those queries do not prevent users from submitting HTML or JavaScript code. If you don't take additional steps, they will simply alter your HTML code (if you output raw database results) and injected links to unwanted sites.
About Prepared Statements:
Prepared statements prevent any input from leaving its scope as a variable. That said every "ending quote" or such would be escaped and made harmless.
SQL injection is nearly impossible. But ... who said, that the native prepared statement is enough? if you trust your native prepare methods. OK. If not, try to break it yourself. Write test cases to proof, that most basic and maybe some more complex cases can not break your prepare statement methods.