create account

Dynamic Queries In SQL Injection By albro by albro

View this thread on: hive.blogpeakd.comecency.com
· @albro ·
$1.54
Dynamic Queries In SQL Injection By albro
<center>![SQL-Injection-what-is-sql-injection - Copy.jpg](https://files.peakd.com/file/peakd-hive/albro/23qrSePYyH3ajM5ZGqv6KB122SgvP2c4qAf4Rs9kUgMp5DSKxFrEL2PHjxPpRrKQavjDE.jpg)</center>

<p>
    In this post, I want to talk about queries that are created dynamically.
</p>
<h3 style="text-align:justify;">
    Dynamic Queries
</h3>
<p>
    One of the issues that needs to be investigated is the issue of creating complex queries. One of the good examples in this field is the advanced search section of the sites. For example, some online stores allow you to search with different factors (product color, price, company name, etc.). In this case, our query is created dynamically according to the user's request. In other words, wherever parts of the SQL code are added to the query according to the user's request or parts are removed from it, they are placed in this category.
</p>
<p>
    In such cases, it's not possible to use placeholders, so we need another mechanism. If the desired part of your site (for example, advanced search) does not have many complications, you can use the query builder. The action mechanism of these query builders is as follows:
</p>
<pre><code class="language-php">$query = $users = DB::table('users')-&gt;select('*');
if ($fname = input::get('first_name'))
{
    $query-&gt;where('first_name = ?', $fname);
}
if ($lname = input::get('last_name'))
{
    $query-&gt;where('last_name = ?', $lname);
}
// etc......
$results = $query-&gt;get();</code></pre>
<p>
    But most of the time we have queries that are much more complex and using query builders becomes so difficult that it no longer has a rational justification. We always know that all the dynamic parts of a query are entered into the main query with placeholders, but for this case, I know a very good trick:
</p>
<p>
    On <a href="https://stackoverflow.com/">stackoverflow</a> website, <a href="https://stackoverflow.com/questions/11231597/ignore-particular-where-criteria/11231629#11231629">a question</a> was asked in this regard and the answer (although it is simple) is one of the smartest and very good answers that I have seen in these few years. The questioner intends to design a search system on the website, whose various factors are determined by the users. On the other hand, the user may leave some of these factors (for example, age is not important). The questioner wants to know how it is possible to create a query in this situation that has all the different states (such as leaving the age and age by the user) and is also executable. The example mentioned by the questioner is as follows:
</p>
<pre><code class="language-php">$sql = 'SELECT * FROM people WHERE first_name = :first_name AND last_name = :last_name AND age = :age AND sex = :sex';
$query = $db-&gt;prepare($sql);
$query-&gt;execute(array(':first_name' =&gt; 'John', ':age' =&gt; '27');</code></pre>
<p>
    Received the following code as an answer:
</p>
<pre><code class="language-php">SELECT * FROM people 
WHERE (first_name = :first_name or :first_name is null)
AND (last_name = :last_name or :last_name is null)
AND (age = :age or :age is null)
AND (sex = :sex or :sex is null)</code></pre>
<p>
    If we give the <code>null</code> parameter to the abandoned items, there is no need to worry. Of course, in this case, if you use PDO, the <code>emulation mode</code> must be <code>ON</code>. In fact, looking at the code above, you'll notice that it is enough to bind our variables to placeholders (either they have a value or they become <code>null</code>). If we do this, those with <code>null</code> values will be discarded and only those with a certain value will be included in the query.
</p>
<p>
    However, always remember that the final query must be built from only two sources: constants and placeholders. Therefore, in summary, any SQL query can only be made of two types of data:
</p>
<ul>
    <li>
        Fixed sections manually written into the script.
    </li>
    <li>
        Use placeholders for dynamic values
    </li>
</ul>
<p>
    If you follow this rule you will be safe against SQL injection.
</p>
<h3>
    Common Mistakes
</h3>
<p>
    Some of the common mistakes of programmers in this field are as follows:
</p>
<ul>
    <li>
        <strong>Escaping user data</strong>: This is one of the biggest mistakes programmers make. Escaping user data has two problems:
        <ul>
            <li>
                <i>Escaping</i>: Escaping only provides part of the protection for a literal type, and you will not be protected from SQL injection by doing it alone, but if you don't use it in the right place, you will hurt your program.
            </li>
            <li>
                <i>Data or user input</i>: Any variable that exists can be dangerous, whether it comes from the user or not. Therefore, every variable must be formatted before it is included in the query, whether it is from the user side or from somewhere else.
            </li>
        </ul>
    </li>
    <li>
        <code><strong>magic quotes</strong></code>: Never use this feature. This feature was exactly the implementation of the above mistakes (escaping user data), which fortunately has now been removed from the SQL language. If you don't know what this feature is, what's better! Don't waste your time!
    </li>
    <li>
        <strong>Data validation</strong>: Data validation in forms has nothing to do with SQL and the security of our database. In fact, we can control the basic things, but be sure that form validation cannot protect you from the risk of SQL injection. Do you remember the example of Leo O'Hara? This name is completely correct and valid and appears valid during validation, but it caused a problem in our program.
    </li>
    <li>
        <code><strong>htmlspecialchars</strong></code><strong> (also things like </strong><code><strong>filter_var()</strong></code><strong> and </strong><code><strong>strip_tags()</strong></code><strong>):</strong> as the name suggests! It's called HTML, which means it's not related to SQL, and you shouldn't associate it with SQL injection. All these things that I mention have their own functions and I am not saying that they are useless, but I am saying that they are unimportant in the field of SQL injection protection. SQL formatting should never change data! For example, when you put your jewelry in the safe to protect them, you expect to take the same jewelry intact later, not that a part of it has changed! The same is true in the SQL language; The job of a database is to store data, not to protect and change it.
    </li>
    <li>
        <strong>Use of a function for sanitization of all data</strong>: Our data is used in different contexts (SQL queries, HTML codes, JS codes, JSON codes, etc.). For this reason, we cannot clean everyone in the same way. You must clear your data for each specific field separately so that there is no problem in your application.
    </li>
    <li>
        <strong>Using separate databases to execute DML queries</strong>: This item will not help you either. In fact, this method tries to prevent our information from falling into the hands of unknown people if our database is hacked and SQL Injection is performed. Therefore, protection against SQL Injection is not considered (besides, it may consume our costs and time unnecessarily).
    </li>
</ul>
<p>
    In several posts, I tried to focus my attention on the topic of SQL Injection (as a topic independent of different tools) so that the topics are general and generalizable and you can implement it in MySQL or PDO or whatever method you have.
</p>
<p>
    Thank you for being with me and I hope these posts have helped you and your website security. Looking forward to your comments!
</p>
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 128 others
properties (23)
authoralbro
permlinkdynamic-queries-in-sql-injection-by-albro
categoryhive-169321
json_metadata"{"app":"peakd/2023.11.3","format":"markdown","author":"albro","description":" In this post, I want to talk about queries that are created dynamically. ","tags":["development","programming","hive-engine","threads","neoxian","chessbrothers","stem","tricks","sql-injection","leofinance"],"users":[],"image":["https://files.peakd.com/file/peakd-hive/albro/23qrSePYyH3ajM5ZGqv6KB122SgvP2c4qAf4Rs9kUgMp5DSKxFrEL2PHjxPpRrKQavjDE.jpg"]}"
created2024-01-14 18:13:30
last_update2024-01-14 18:13:30
depth0
children5
last_payout2024-01-21 18:13:30
cashout_time1969-12-31 23:59:59
total_payout_value0.774 HBD
curator_payout_value0.763 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length7,761
author_reputation30,477,419,385,789
root_title"Dynamic Queries In SQL Injection By albro"
beneficiaries
0.
accounthive-169321
weight200
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id130,479,180
net_rshares3,602,814,455,604
author_curate_reward""
vote details (192)
@agileautomation ·
nice info and share, thanks again!
👍  
properties (23)
authoragileautomation
permlinkre-albro-s7ddph
categoryhive-169321
json_metadata{"tags":["hive-169321"],"app":"peakd/2023.11.3"}
created2024-01-16 19:48:51
last_update2024-01-16 19:48:51
depth1
children0
last_payout2024-01-23 19:48:51
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length34
author_reputation55,848,601,723
root_title"Dynamic Queries In SQL Injection By albro"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id130,534,277
net_rshares45,822,526,353
author_curate_reward""
vote details (1)
@chessbrotherspro ·
<h3>Congratulations!</h3><hr /><div class="pull-right"><img src="https://images.hive.blog/DQmQLssYuuJP2neoTVUbMRzvAu4Ptg7Vwt92aTM7Z3gNovg/cb-logo-150.png" alt="You have obtained a vote from CHESS BROTHERS PROJECT"/></div><div class="text-justify"><h3>✅ Good job. Your post has been appreciated and has received support from <a href="/@chessbrotherspro"><b>CHESS BROTHERS</b></a> ♔ 💪</h3><p><br>♟ We invite you to use our hashtag <b>#chessbrothers</b> and learn more <a href="/@chessbrotherspro/introducing-chess-brothers-project-the-most-innovative-community-combining-chess-fitness-and-more"><b>about us</b></a>.</p><p>♟♟ You can also reach us on our <a href="https://discord.gg/73sK9ZTGqJ" rel="noopener" title="This is going to take you to the Discord of Chess Brothers"><b>Discord server</b></a>  and promote your posts there.</p><p>♟♟♟  Consider <a href="/@chessbrotherspro/teamwork-is-worthwhile-join-the-chess-brothers-healing-trail-supporting-the-work-being-done-and-earning-rewards"><b>joining our curation trail</b></a> so we work as a team and you get rewards automatically.</p><p>♞♟ Check out our <a href="/@chessbrotherspro"><b>@chessbrotherspro</b></a> account to learn about the curation process carried out daily by our team.</p><p><br>🏅 If you want to earn profits with your HP delegation and support our project, we invite you to join the <i>Master Investor</i> plan. <a href='/@chessbrotherspro/master-investor-plan-or-programa'>Here you can learn how to do it.</a></p></div><div class="text-center"><p><br>Kindly</p><p><strong><em>The CHESS BROTHERS team</em></strong></p></div>
👍  
properties (23)
authorchessbrotherspro
permlinkre-dynamic-queries-in-sql-injection-by-albro
categoryhive-169321
json_metadata""
created2024-01-14 22:02:54
last_update2024-01-14 22:02:54
depth1
children0
last_payout2024-01-21 22:02:54
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,598
author_reputation78,235,631,274,099
root_title"Dynamic Queries In SQL Injection By albro"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id130,483,384
net_rshares45,819,494,147
author_curate_reward""
vote details (1)
@hivebuzz ·
Congratulations @albro! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

<table><tr><td><img src="https://images.hive.blog/60x70/http://hivebuzz.me/@albro/posts.png?202401141913"></td><td>You published more than 80 posts.<br>Your next target is to reach 90 posts.</td></tr>
</table>

<sub>_You can view your badges on [your board](https://hivebuzz.me/@albro) and compare yourself to others in the [Ranking](https://hivebuzz.me/ranking)_</sub>
<sub>_If you no longer want to receive notifications, reply to this comment with the word_ `STOP`</sub>


To support your work, I also upvoted your post!


**Check out our last posts:**
<table><tr><td><a href="/hive-122221/@hivebuzz/lpud-202401"><img src="https://images.hive.blog/64x128/https://i.imgur.com/pVZi2Md.png"></a></td><td><a href="/hive-122221/@hivebuzz/lpud-202401">LEO Power Up Day - January 15, 2024</a></td></tr></table>
properties (22)
authorhivebuzz
permlinknotify-albro-20240114t192903
categoryhive-169321
json_metadata{"image":["http://hivebuzz.me/notify.t6.png"]}
created2024-01-14 19:29:03
last_update2024-01-14 19:29:03
depth1
children0
last_payout2024-01-21 19:29:03
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length940
author_reputation369,430,992,899,231
root_title"Dynamic Queries In SQL Injection By albro"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id130,480,537
net_rshares0
@stemsocial ·
re-albro-dynamic-queries-in-sql-injection-by-albro-20240115t204532646z
<div class='text-justify'> <div class='pull-left'>
 <img src='https://stem.openhive.network/images/stemsocialsupport7.png'> </div>

Thanks for your contribution to the <a href='/trending/hive-196387'>STEMsocial community</a>. Feel free to join us on <a href='https://discord.gg/9c7pKVD'>discord</a> to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support.&nbsp;<br />&nbsp;<br />
</div>
👍  
properties (23)
authorstemsocial
permlinkre-albro-dynamic-queries-in-sql-injection-by-albro-20240115t204532646z
categoryhive-169321
json_metadata{"app":"STEMsocial"}
created2024-01-15 20:45:33
last_update2024-01-15 20:45:33
depth1
children0
last_payout2024-01-22 20:45:33
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length565
author_reputation22,920,436,264,631
root_title"Dynamic Queries In SQL Injection By albro"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id130,508,605
net_rshares43,730,450,148
author_curate_reward""
vote details (1)
@wittythedev ·
Providing an Or statement with `is null` to the dynamic fields works great. Providing a lot of IF statement wasn't the best and could get complicated. 
👍  
properties (23)
authorwittythedev
permlinkre-albro-s7b347
categoryhive-169321
json_metadata{"tags":["hive-169321"],"app":"peakd/2023.11.3"}
created2024-01-15 14:04:57
last_update2024-01-15 14:04:57
depth1
children0
last_payout2024-01-22 14:04:57
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length151
author_reputation1,357,282,519,977
root_title"Dynamic Queries In SQL Injection By albro"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id130,499,122
net_rshares44,623,278,644
author_curate_reward""
vote details (1)