{"id":3831,"date":"2022-08-20T19:05:49","date_gmt":"2022-08-20T13:35:49","guid":{"rendered":"https:\/\/jassweb.com\/solved\/solved-how-can-i-prevent-sql-injection-in-php\/"},"modified":"2022-08-20T19:05:49","modified_gmt":"2022-08-20T13:35:49","slug":"solved-how-can-i-prevent-sql-injection-in-php","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-how-can-i-prevent-sql-injection-in-php\/","title":{"rendered":"(Solved) How can I prevent SQL injection in PHP?"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-60496\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"60496\" data-parentid=\"60174\" data-score=\"9490\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<p>The <em>correct<\/em> way to avoid SQL injection attacks, no matter which database you use, is to <strong>separate the data from SQL<\/strong>, so that data stays data and will <strong>never be interpreted<\/strong> as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don&#8217;t <em>fully<\/em> understand the details, you should always <strong>use prepared statements and parameterized queries.<\/strong> These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.<\/p>\n<p>You basically have two options to achieve this:<\/p>\n<ol>\n<li>\n<p>Using <a rel=\"nofollow noopener\" target=\"_blank\" href=\"http:\/\/php.net\/manual\/en\/book.pdo.php\"><strong>PDO<\/strong><\/a> (for any supported database driver):<\/p>\n<pre class=\"lang-php prettyprint-override\"><code>$stmt = $pdo-&gt;prepare('SELECT * FROM employees WHERE name = :name');\n$stmt-&gt;execute([ 'name' =&gt; $name ]);\n\nforeach ($stmt as $row) {\n    \/\/ Do something with $row\n}\n<\/code><\/pre>\n<\/li>\n<li>\n<p>Using <a rel=\"nofollow noopener\" target=\"_blank\" href=\"http:\/\/php.net\/manual\/en\/book.mysqli.php\"><strong>MySQLi<\/strong><\/a> (for MySQL):<\/p>\n<pre class=\"lang-php prettyprint-override\"><code>$stmt = $dbConnection-&gt;prepare('SELECT * FROM employees WHERE name = ?');\n$stmt-&gt;bind_param('s', $name); \/\/ 's' specifies the variable type =&gt; 'string'\n$stmt-&gt;execute();\n\n$result = $stmt-&gt;get_result();\nwhile ($row = $result-&gt;fetch_assoc()) {\n    \/\/ Do something with $row\n}\n<\/code><\/pre>\n<\/li>\n<\/ol>\n<p>If you&#8217;re connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, <code>pg_prepare()<\/code> and <code>pg_execute()<\/code> for PostgreSQL). PDO is the universal option.<\/p>\n<hr>\n<h2>Correctly setting up the connection<\/h2>\n<h4>PDO<\/h4>\n<p>Note that when using <strong>PDO<\/strong> to access a MySQL database <em>real<\/em> prepared statements are <strong>not used by default<\/strong>. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using <strong>PDO<\/strong> is:<\/p>\n<pre class=\"lang-php prettyprint-override\"><code>$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8mb4', 'user', 'password');\n\n$dbConnection-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false);\n$dbConnection-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n<\/code><\/pre>\n<p>In the above example, the error mode isn&#8217;t strictly necessary, <strong>but it is advised to add it<\/strong>. This way PDO will inform you of all MySQL errors by means of throwing the <code>PDOException<\/code>.<\/p>\n<p>What is <strong>mandatory<\/strong>, however, is the first <code>setAttribute()<\/code> line, which tells PDO to disable emulated prepared statements and use <em>real<\/em> prepared statements. This makes sure the statement and the values aren&#8217;t parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).<\/p>\n<p>Although you can set the <code>charset<\/code> in the options of the constructor, it&#8217;s important to note that &#8216;older&#8217; versions of PHP (before 5.3.6) <a rel=\"nofollow noopener\" target=\"_blank\" href=\"http:\/\/php.net\/manual\/en\/ref.pdo-mysql.connection.php\">silently ignored the charset parameter<\/a> in the DSN.<\/p>\n<h4>Mysqli<\/h4>\n<p>For mysqli we have to follow the same routine:<\/p>\n<pre class=\"lang-php prettyprint-override\"><code>mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); \/\/ error reporting\n$dbConnection = new mysqli('127.0.0.1', 'username', 'password', 'test');\n$dbConnection-&gt;set_charset('utf8mb4'); \/\/ charset\n<\/code><\/pre>\n<hr>\n<h2>Explanation<\/h2>\n<p>The SQL statement you pass to <code>prepare<\/code> is parsed and compiled by the database server. By specifying parameters (either a <code>?<\/code> or a named parameter like <code>:name<\/code> in the example above) you tell the database engine where you want to filter on. Then when you call <code>execute<\/code>, the prepared statement is combined with the parameter values you specify.<\/p>\n<p>The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn&#8217;t intend.<\/p>\n<p>Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the <code>$name<\/code> variable contains <code>'Sarah'; DELETE FROM employees<\/code> the result would simply be a search for the string <code>\"'Sarah'; DELETE FROM employees\"<\/code>, and you will not end up with <a rel=\"nofollow noopener\" target=\"_blank\" href=\"http:\/\/xkcd.com\/327\/\">an empty table<\/a>.<\/p>\n<p>Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.<\/p>\n<p>Oh, and since you asked about how to do it for an insert, here&#8217;s an example (using PDO):<\/p>\n<pre class=\"lang-php prettyprint-override\"><code>$preparedStatement = $db-&gt;prepare('INSERT INTO table (column) VALUES (:column)');\n\n$preparedStatement-&gt;execute([ 'column' =&gt; $unsafeValue ]);\n<\/code><\/pre>\n<hr>\n<h2>Can prepared statements be used for dynamic queries?<\/h2>\n<p>While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.<\/p>\n<p>For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.<\/p>\n<pre><code>\/\/ Value whitelist\n\/\/ $dir can only be 'DESC', otherwise it will be 'ASC'\nif (empty($dir) || $dir !== 'DESC') {\n   $dir=\"ASC\";\n}\n<\/code><\/pre>\n<\/p><\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\">10<\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved How can I prevent SQL injection in PHP? <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don&#8217;t &#8230; <a title=\"(Solved) How can I prevent SQL injection in PHP?\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-how-can-i-prevent-sql-injection-in-php\/\" aria-label=\"More on (Solved) How can I prevent SQL injection in PHP?\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[340,339,342,341,343],"class_list":["post-3831","post","type-post","status-publish","format-standard","hentry","category-solved","tag-mysql","tag-php","tag-security","tag-sql","tag-sql-injection"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>(Solved) How can I prevent SQL injection in PHP? - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-how-can-i-prevent-sql-injection-in-php\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"(Solved) How can I prevent SQL injection in PHP? - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don&#8217;t ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-how-can-i-prevent-sql-injection-in-php\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2022-08-20T13:35:49+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-how-can-i-prevent-sql-injection-in-php\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-how-can-i-prevent-sql-injection-in-php\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"(Solved) How can I prevent SQL injection in PHP?\",\"datePublished\":\"2022-08-20T13:35:49+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-how-can-i-prevent-sql-injection-in-php\/\"},\"wordCount\":622,\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"keywords\":[\"mysql\",\"php\",\"security\",\"sql\",\"sql-injection\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-how-can-i-prevent-sql-injection-in-php\/\",\"url\":\"https:\/\/jassweb.com\/solved\/solved-how-can-i-prevent-sql-injection-in-php\/\",\"name\":\"(Solved) How can I prevent SQL injection in PHP? - JassWeb\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#website\"},\"datePublished\":\"2022-08-20T13:35:49+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-how-can-i-prevent-sql-injection-in-php\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jassweb.com\/solved\/solved-how-can-i-prevent-sql-injection-in-php\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-how-can-i-prevent-sql-injection-in-php\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jassweb.com\/solved\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"(Solved) How can I prevent SQL injection in PHP?\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jassweb.com\/solved\/#website\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jassweb.com\/solved\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"contentUrl\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939\",\"contentUrl\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\/\/jassweb.com\"],\"url\":\"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"(Solved) How can I prevent SQL injection in PHP? - JassWeb","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jassweb.com\/solved\/solved-how-can-i-prevent-sql-injection-in-php\/","og_locale":"en_US","og_type":"article","og_title":"(Solved) How can I prevent SQL injection in PHP? - JassWeb","og_description":"[ad_1] The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don&#8217;t ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-how-can-i-prevent-sql-injection-in-php\/","og_site_name":"JassWeb","article_published_time":"2022-08-20T13:35:49+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-how-can-i-prevent-sql-injection-in-php\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-how-can-i-prevent-sql-injection-in-php\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"(Solved) How can I prevent SQL injection in PHP?","datePublished":"2022-08-20T13:35:49+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-how-can-i-prevent-sql-injection-in-php\/"},"wordCount":622,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":["mysql","php","security","sql","sql-injection"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-how-can-i-prevent-sql-injection-in-php\/","url":"https:\/\/jassweb.com\/solved\/solved-how-can-i-prevent-sql-injection-in-php\/","name":"(Solved) How can I prevent SQL injection in PHP? - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2022-08-20T13:35:49+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-how-can-i-prevent-sql-injection-in-php\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-how-can-i-prevent-sql-injection-in-php\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-how-can-i-prevent-sql-injection-in-php\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"(Solved) How can I prevent SQL injection in PHP?"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/3831","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=3831"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/3831\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=3831"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=3831"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=3831"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}