Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You need form validation. Easy solution will not allow empty fields save in db and prevent <a href="https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php">SQL-injections</a>.</p> <p><strong>Easy solution</strong>:</p> <pre><code>$fname = isset($_POST['firstname']) and nameIsValid($_POST['firstname']) ? $_POST['firstname'] : false; $lname = isset($_POST['lastname']) and nameIsValid($_POST['lastname']) ? $_POST['lastname'] : false; if (false === $fname or false === $lname) { // report about not valid form fields } else { $dsn = 'mysql:dbname=yourdb;host=yourhost;charset=utf8'; $dbh = new PDO($dsn, 'user', 'pass'); $sql = "UPDATE profile SET first = :fname, last = :lname WHERE id = :id"; $stmt = $dbh-&gt;prepare($sql); $stmt-&gt;execute(array(':fname' =&gt; $value, ':lname' =&gt; $lname, ':id' =&gt; $id)); } /** * Validation names for empty values * * @param string $name First name or last name * @return bool */ function nameIsValid($name) { return '' !== $name; } </code></pre> <p>But be aware of <a href="https://stackoverflow.com/questions/6857817/a-php-function-to-prevent-sql-injections-and-xss">XSS-injection</a>. For example somebody can save in your db Fist name:</p> <pre><code>&lt;script&gt;alert('Woohoo! You have vulnerability!');&lt;/script&gt; </code></pre> <p>And next time, when you print First name of the user, everyone will see message about vulnerability :)</p> <p>You may decide implement more strict validation rules, which will not allow names like <strong>"asfyua23807*^2#"</strong>, <strong>"-2*&amp;%$9837239askHF"</strong> or XSS-injections. In this case you should modify <code>nameIsValid()</code> function.</p> <p><strong>Safe solution:</strong></p> <pre><code>/** * Validation names and prevent XSS-injections * * @param string $name First name or last name * @return bool */ function nameIsValid($name) { $pattern = '/^[\.a-z-]+$/i'; return (bool) preg_match($pattern, $name); } </code></pre> <p>This logic allow names containing A-z . - symbols: <strong>J.Jameson</strong>, <strong>Jackson-Piterson</strong>, <strong>JOHn</strong>, <strong>smIth</strong>, <strong>etc</strong>. For more strict validation rules check <a href="http://php.net/manual/en/book.pcre.php" rel="nofollow noreferrer">Official PHP Regular Expressions manual</a>.</p>
 

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