Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The rules of adding strings into a query are plain and simple:</p> <ol> <li>The string should be enclosed in quotes.</li> <li>Therefore, these quotes should be escaped in the data, as well as some other characters, using <code>mysql_real_escape_string()</code></li> </ol> <p>So, your code becomes</p> <pre><code>$type = 'testing'; $type = mysql_real_escape_string($type); $reporter = "John O'Hara"; $reporter = mysql_real_escape_string($reporter); $query = "INSERT INTO contents (type, reporter, description) VALUES('$type', '$reporter', 'whatever')"; mysql_query($query) or trigger_error(mysql_error()." in ".$query); // note that when running mysql_query you have to always check for errors </code></pre> <p>But if you're going to add the variable in another part of a query, the rules change. </p> <ul> <li>To add a number, you have to cast it to its type explicitly. </li> </ul> <p>For example:</p> <pre><code>$limit = intval($_GET['limit']); //casting to int type! $query = "SELECT * FROM table LIMIT $limit"; </code></pre> <ul> <li>To add an identifier, it's better to choose it from some sort of white list, consists of hardcoded values</li> </ul> <p>For example:</p> <pre><code>if ($_GET['sortorder'] == 'name') { $sortorder = 'name'; } else { $sortorder = 'id'; } $query = "SELECT * FROM table ORDER BY $sortorder"; </code></pre> <p><strong>To make it all simplified</strong> yet with guaranteed safety, one have to use some sort of <strong>placeholder system</strong> where the variable goes into a query not directly but via some proxy, called a placeholder.</p> <p>So, your query call becomes something like this:</p> <pre><code>$type = 'testing'; $reporter = "John O'Hara"; pquery("INSERT INTO contents (type, reporter, description) VALUES(?s, ?s, ?s)", $type, $reporter,'whatever'); </code></pre> <p>And there will be absolutely no need to worry about all these matters.</p> <p>For the limited set of placeholders you can use <a href="https://stackoverflow.com/tags/pdo/info">PDO</a>. Though for real life usage you will need extended set which is offered by but a few libraries, one of which is <a href="https://github.com/colshrapnel/safemysql" rel="noreferrer">SafeMysql</a>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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