Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>how can I implement this in a generic way?</p> </blockquote> <p>All queries must be hardcoded in your script.<br> Of course some of them can be dynamically built, but you're allowed to make only DATA dynamic, not control structures.<br> So, it must be like this:</p> <pre><code>$name=mysql_real_escape_string($_POST['name']); if ($id = intval($_POST['id'])) { $query="UPDATE table SET name='$name' WHERE id=$id"; } else { $query="INSERT INTO table SET name='$name'"; } </code></pre> <p>or this:</p> <pre><code>if (!isset($_GET['id'])) { $query="SELECT * FROM table"; } else { $id = intval($_GET['id']; $query="SELECT * FROM table WHERE id=$id"; } </code></pre> <p>or whatever.<br> Of course, inserted data must be properly escaped, cast or <a href="https://stackoverflow.com/questions/1299182/prepared-parameterized-query-with-pdo">binded</a>.</p> <p>But sometimes we need to use dynamic operator or identifier. The principle is the same: everything must be hardcoded in your script, nothing to be passed from the client side to the SQL query directly.<br> Say, to make a dynamic sorting, you can use a code like this</p> <pre><code>$orders=array("name","price","qty"); $key=array_search($_GET['sort'],$orders)); $orderby=$orders[$key]; $query="SELECT * FROM `table` ORDER BY $orderby"; </code></pre> <p>or to assemble a dynamic WHERE: </p> <pre><code>$w=array(); if (!empty($_GET['rooms'])) $w[]="rooms='".mysql_real_escape_string($_GET['rooms'])."'"; if (!empty($_GET['space'])) $w[]="space='".mysql_real_escape_string($_GET['space'])."'"; if (!empty($_GET['max_price'])) $w[]="price &lt; '".mysql_real_escape_string($_GET['max_price'])."'"; if (count($w)) $where="WHERE ".implode(' AND ',$w); else $where=''; $query="select * from table $where"; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload