Avoiding SQL injections with prepare and execute The Next CEO of Stack OverflowHow can I prevent SQL injection in PHP?Are PDO prepared statements sufficient to prevent SQL injection?How does the SQL injection from the “Bobby Tables” XKCD comic work?Avoiding SQL injection without parametersIs MySQL more resistant to SQL injection attack than PostgreSQL (under Perl/DBI)?SQL injection that gets around mysql_real_escape_string()How safe are PDO prepared statement?Preventing SQL injection in Node.jsUsing prepared statement for Order by to prevent SQL injection javaSql injection in request body

Can you teleport closer to a creature you are Frightened of?

Why can't we say "I have been having a dog"?

Why do we say “un seul M” and not “une seule M” even though M is a “consonne”?

Another proof that dividing by 0 does not exist -- is it right?

How to implement Comparable so it is consistent with identity-equality

Could a dragon use its wings to swim?

Compilation of a 2d array and a 1d array

"Eavesdropping" vs "Listen in on"

Free fall ellipse or parabola?

Would a grinding machine be a simple and workable propulsion system for an interplanetary spacecraft?

Calculate the Mean mean of two numbers

Early programmable calculators with RS-232

How can I replace x-axis labels with pre-determined symbols?

Is it reasonable to ask other researchers to send me their previous grant applications?

logical reads on global temp table, but not on session-level temp table

Small nick on power cord from an electric alarm clock, and copper wiring exposed but intact

Is a linearly independent set whose span is dense a Schauder basis?

What is the difference between 'contrib' and 'non-free' packages repositories?

How can I prove that a state of equilibrium is unstable?

Can this transistor (2N2222) take 6 V on emitter-base? Am I reading the datasheet incorrectly?

Avoiding the "not like other girls" trope?

Oldie but Goldie

Do I need to write [sic] when including a quotation with a number less than 10 that isn't written out?

Read/write a pipe-delimited file line by line with some simple text manipulation



Avoiding SQL injections with prepare and execute



The Next CEO of Stack OverflowHow can I prevent SQL injection in PHP?Are PDO prepared statements sufficient to prevent SQL injection?How does the SQL injection from the “Bobby Tables” XKCD comic work?Avoiding SQL injection without parametersIs MySQL more resistant to SQL injection attack than PostgreSQL (under Perl/DBI)?SQL injection that gets around mysql_real_escape_string()How safe are PDO prepared statement?Preventing SQL injection in Node.jsUsing prepared statement for Order by to prevent SQL injection javaSql injection in request body










3















A line of code like



my $sql_query = "SELECT * FROM Users WHERE user='$user';";


might introduce an SQL injection vulnerability into your program. To avoid this one could use something like



my $sth = $dbh->prepare("SELECT * FROM Users WHERE user='?';");
$dbh->execute($user);


However, in the code I am currently working on the following is used



$sql_query = "SELECT * FROM Users WHERE user='" . $user . "';";
$dbh->prepare($sql_query);
$dbh->execute();


Does this actually work? If yes, are there any differences to what I would have done? What are the advantages and disadvantages?










share|improve this question

















  • 4





    You want the second one, except without the single quotes around the question mark. They make it a string, not a parameter (and use $sth->execute($user); of course). The first and third are equivalent and have the same injection vulnerability.

    – Shawn
    Mar 7 at 19:48












  • @Shawn: Thanks for the explanation!

    – eins6180
    Mar 7 at 21:34















3















A line of code like



my $sql_query = "SELECT * FROM Users WHERE user='$user';";


might introduce an SQL injection vulnerability into your program. To avoid this one could use something like



my $sth = $dbh->prepare("SELECT * FROM Users WHERE user='?';");
$dbh->execute($user);


However, in the code I am currently working on the following is used



$sql_query = "SELECT * FROM Users WHERE user='" . $user . "';";
$dbh->prepare($sql_query);
$dbh->execute();


Does this actually work? If yes, are there any differences to what I would have done? What are the advantages and disadvantages?










share|improve this question

















  • 4





    You want the second one, except without the single quotes around the question mark. They make it a string, not a parameter (and use $sth->execute($user); of course). The first and third are equivalent and have the same injection vulnerability.

    – Shawn
    Mar 7 at 19:48












  • @Shawn: Thanks for the explanation!

    – eins6180
    Mar 7 at 21:34













3












3








3








A line of code like



my $sql_query = "SELECT * FROM Users WHERE user='$user';";


might introduce an SQL injection vulnerability into your program. To avoid this one could use something like



my $sth = $dbh->prepare("SELECT * FROM Users WHERE user='?';");
$dbh->execute($user);


However, in the code I am currently working on the following is used



$sql_query = "SELECT * FROM Users WHERE user='" . $user . "';";
$dbh->prepare($sql_query);
$dbh->execute();


Does this actually work? If yes, are there any differences to what I would have done? What are the advantages and disadvantages?










share|improve this question














A line of code like



my $sql_query = "SELECT * FROM Users WHERE user='$user';";


might introduce an SQL injection vulnerability into your program. To avoid this one could use something like



my $sth = $dbh->prepare("SELECT * FROM Users WHERE user='?';");
$dbh->execute($user);


However, in the code I am currently working on the following is used



$sql_query = "SELECT * FROM Users WHERE user='" . $user . "';";
$dbh->prepare($sql_query);
$dbh->execute();


Does this actually work? If yes, are there any differences to what I would have done? What are the advantages and disadvantages?







perl sql-injection dbi






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 7 at 19:44









eins6180eins6180

1284




1284







  • 4





    You want the second one, except without the single quotes around the question mark. They make it a string, not a parameter (and use $sth->execute($user); of course). The first and third are equivalent and have the same injection vulnerability.

    – Shawn
    Mar 7 at 19:48












  • @Shawn: Thanks for the explanation!

    – eins6180
    Mar 7 at 21:34












  • 4





    You want the second one, except without the single quotes around the question mark. They make it a string, not a parameter (and use $sth->execute($user); of course). The first and third are equivalent and have the same injection vulnerability.

    – Shawn
    Mar 7 at 19:48












  • @Shawn: Thanks for the explanation!

    – eins6180
    Mar 7 at 21:34







4




4





You want the second one, except without the single quotes around the question mark. They make it a string, not a parameter (and use $sth->execute($user); of course). The first and third are equivalent and have the same injection vulnerability.

– Shawn
Mar 7 at 19:48






You want the second one, except without the single quotes around the question mark. They make it a string, not a parameter (and use $sth->execute($user); of course). The first and third are equivalent and have the same injection vulnerability.

– Shawn
Mar 7 at 19:48














@Shawn: Thanks for the explanation!

– eins6180
Mar 7 at 21:34





@Shawn: Thanks for the explanation!

– eins6180
Mar 7 at 21:34












1 Answer
1






active

oldest

votes


















6














my $sth = $dbh->prepare("SELECT * FROM Users WHERE user='?'");


This won't work because it's searching for a literal '?' character — not a parameter. If you try to send a value for the parameter, MySQL will be like, "what do you want me to do with this?" because the query has no parameter placeholder.



If you want to use a parameter, you must NOT put the parameter placeholder inside string delimiters in the SQL query, even if the parameter will take string or datetime value:



my $sth = $dbh->prepare("SELECT * FROM Users WHERE user=?");


The next example:



$sql_query = "SELECT * FROM Users WHERE user='" . $user . "'";
$dbh->prepare($sql_query);
$dbh->execute();


That will run the query, but it's NOT safe. You can prepare any query even if it has no parameters.



Using prepare() is not what makes queries safe from SQL injection. What makes it safer is using parameters to combine dynamic values instead of doing string-concatenation like you're doing in this example.



But using parameters does require the use of prepare().



PS: You don't need to put ; at the end of your SQL queries when you run them one at a time programmatically. The separator is only needed if you run multiple queries, like in an SQL script, or in a stored procedure. In your examples, the ; is harmless but MySQL doesn't require it, and it will just ignore it.






share|improve this answer

























  • Thanks for this nice answer and all the extra information!

    – eins6180
    Mar 7 at 21:35











  • I would add to this excellent answer that prepare isn't even necessary to use bound parameters safely. The second example is equivalent to $dbh->do('SELECT * FROM Users WHERE user=?', undef, $user);, which depending on the DBI driver may optimize out the statement prepare step.

    – Grinnz
    Mar 8 at 0:15












Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55051704%2favoiding-sql-injections-with-prepare-and-execute%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









6














my $sth = $dbh->prepare("SELECT * FROM Users WHERE user='?'");


This won't work because it's searching for a literal '?' character — not a parameter. If you try to send a value for the parameter, MySQL will be like, "what do you want me to do with this?" because the query has no parameter placeholder.



If you want to use a parameter, you must NOT put the parameter placeholder inside string delimiters in the SQL query, even if the parameter will take string or datetime value:



my $sth = $dbh->prepare("SELECT * FROM Users WHERE user=?");


The next example:



$sql_query = "SELECT * FROM Users WHERE user='" . $user . "'";
$dbh->prepare($sql_query);
$dbh->execute();


That will run the query, but it's NOT safe. You can prepare any query even if it has no parameters.



Using prepare() is not what makes queries safe from SQL injection. What makes it safer is using parameters to combine dynamic values instead of doing string-concatenation like you're doing in this example.



But using parameters does require the use of prepare().



PS: You don't need to put ; at the end of your SQL queries when you run them one at a time programmatically. The separator is only needed if you run multiple queries, like in an SQL script, or in a stored procedure. In your examples, the ; is harmless but MySQL doesn't require it, and it will just ignore it.






share|improve this answer

























  • Thanks for this nice answer and all the extra information!

    – eins6180
    Mar 7 at 21:35











  • I would add to this excellent answer that prepare isn't even necessary to use bound parameters safely. The second example is equivalent to $dbh->do('SELECT * FROM Users WHERE user=?', undef, $user);, which depending on the DBI driver may optimize out the statement prepare step.

    – Grinnz
    Mar 8 at 0:15
















6














my $sth = $dbh->prepare("SELECT * FROM Users WHERE user='?'");


This won't work because it's searching for a literal '?' character — not a parameter. If you try to send a value for the parameter, MySQL will be like, "what do you want me to do with this?" because the query has no parameter placeholder.



If you want to use a parameter, you must NOT put the parameter placeholder inside string delimiters in the SQL query, even if the parameter will take string or datetime value:



my $sth = $dbh->prepare("SELECT * FROM Users WHERE user=?");


The next example:



$sql_query = "SELECT * FROM Users WHERE user='" . $user . "'";
$dbh->prepare($sql_query);
$dbh->execute();


That will run the query, but it's NOT safe. You can prepare any query even if it has no parameters.



Using prepare() is not what makes queries safe from SQL injection. What makes it safer is using parameters to combine dynamic values instead of doing string-concatenation like you're doing in this example.



But using parameters does require the use of prepare().



PS: You don't need to put ; at the end of your SQL queries when you run them one at a time programmatically. The separator is only needed if you run multiple queries, like in an SQL script, or in a stored procedure. In your examples, the ; is harmless but MySQL doesn't require it, and it will just ignore it.






share|improve this answer

























  • Thanks for this nice answer and all the extra information!

    – eins6180
    Mar 7 at 21:35











  • I would add to this excellent answer that prepare isn't even necessary to use bound parameters safely. The second example is equivalent to $dbh->do('SELECT * FROM Users WHERE user=?', undef, $user);, which depending on the DBI driver may optimize out the statement prepare step.

    – Grinnz
    Mar 8 at 0:15














6












6








6







my $sth = $dbh->prepare("SELECT * FROM Users WHERE user='?'");


This won't work because it's searching for a literal '?' character — not a parameter. If you try to send a value for the parameter, MySQL will be like, "what do you want me to do with this?" because the query has no parameter placeholder.



If you want to use a parameter, you must NOT put the parameter placeholder inside string delimiters in the SQL query, even if the parameter will take string or datetime value:



my $sth = $dbh->prepare("SELECT * FROM Users WHERE user=?");


The next example:



$sql_query = "SELECT * FROM Users WHERE user='" . $user . "'";
$dbh->prepare($sql_query);
$dbh->execute();


That will run the query, but it's NOT safe. You can prepare any query even if it has no parameters.



Using prepare() is not what makes queries safe from SQL injection. What makes it safer is using parameters to combine dynamic values instead of doing string-concatenation like you're doing in this example.



But using parameters does require the use of prepare().



PS: You don't need to put ; at the end of your SQL queries when you run them one at a time programmatically. The separator is only needed if you run multiple queries, like in an SQL script, or in a stored procedure. In your examples, the ; is harmless but MySQL doesn't require it, and it will just ignore it.






share|improve this answer















my $sth = $dbh->prepare("SELECT * FROM Users WHERE user='?'");


This won't work because it's searching for a literal '?' character — not a parameter. If you try to send a value for the parameter, MySQL will be like, "what do you want me to do with this?" because the query has no parameter placeholder.



If you want to use a parameter, you must NOT put the parameter placeholder inside string delimiters in the SQL query, even if the parameter will take string or datetime value:



my $sth = $dbh->prepare("SELECT * FROM Users WHERE user=?");


The next example:



$sql_query = "SELECT * FROM Users WHERE user='" . $user . "'";
$dbh->prepare($sql_query);
$dbh->execute();


That will run the query, but it's NOT safe. You can prepare any query even if it has no parameters.



Using prepare() is not what makes queries safe from SQL injection. What makes it safer is using parameters to combine dynamic values instead of doing string-concatenation like you're doing in this example.



But using parameters does require the use of prepare().



PS: You don't need to put ; at the end of your SQL queries when you run them one at a time programmatically. The separator is only needed if you run multiple queries, like in an SQL script, or in a stored procedure. In your examples, the ; is harmless but MySQL doesn't require it, and it will just ignore it.







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 7 at 21:34

























answered Mar 7 at 20:26









Bill KarwinBill Karwin

384k64520678




384k64520678












  • Thanks for this nice answer and all the extra information!

    – eins6180
    Mar 7 at 21:35











  • I would add to this excellent answer that prepare isn't even necessary to use bound parameters safely. The second example is equivalent to $dbh->do('SELECT * FROM Users WHERE user=?', undef, $user);, which depending on the DBI driver may optimize out the statement prepare step.

    – Grinnz
    Mar 8 at 0:15


















  • Thanks for this nice answer and all the extra information!

    – eins6180
    Mar 7 at 21:35











  • I would add to this excellent answer that prepare isn't even necessary to use bound parameters safely. The second example is equivalent to $dbh->do('SELECT * FROM Users WHERE user=?', undef, $user);, which depending on the DBI driver may optimize out the statement prepare step.

    – Grinnz
    Mar 8 at 0:15

















Thanks for this nice answer and all the extra information!

– eins6180
Mar 7 at 21:35





Thanks for this nice answer and all the extra information!

– eins6180
Mar 7 at 21:35













I would add to this excellent answer that prepare isn't even necessary to use bound parameters safely. The second example is equivalent to $dbh->do('SELECT * FROM Users WHERE user=?', undef, $user);, which depending on the DBI driver may optimize out the statement prepare step.

– Grinnz
Mar 8 at 0:15






I would add to this excellent answer that prepare isn't even necessary to use bound parameters safely. The second example is equivalent to $dbh->do('SELECT * FROM Users WHERE user=?', undef, $user);, which depending on the DBI driver may optimize out the statement prepare step.

– Grinnz
Mar 8 at 0:15




















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55051704%2favoiding-sql-injections-with-prepare-and-execute%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved