Increase view counter with each page view My question is similar to before, but now the code has changed completely. I would like to understand if this code is vulnerable to mysql injection.

    &lt;?php

// Define our querystring variables
$option = (array_key_exists('option', $_POST) ? $_POST['option'] : false);
$view   = (array_key_exists('view', $_POST) ?  $_POST['view'] : false);
$id     = (array_key_exists('id', $_POST) ?  intval($_POST['id']) : false);

// Check wheter our variables are correct in order to proceed
if ($option == 'com_content' &amp;&amp; $view == 'video' &amp;&amp; $id &gt; 0) {

    // Connect to the database
    include_once("../configuration.php");
    $cg = new JConfig;
    $con = mysqli_connect($cg-&gt;host,$cg-&gt;user,$cg-&gt;password,$cg-&gt;db);
    if (mysqli_connect_errno()) {
        die('n/a');
    }

    // Add new hit: Update the `times_viewed` field corresponding to specific video id
    $query = "UPDATE " . $cg-&gt;dbprefix . "hdflv_upload 
                        SET `times_viewed` = `times_viewed` + 1 
                        WHERE `id` LIKE " . $id . ";";

    if (mysqli_query($con, $query) === true) {

    // Get the updated `times_viewed` of video id
        $query  = "SELECT `times_viewed` 
                             FROM " . $cg-&gt;dbprefix . "hdflv_upload 
                             WHERE `id` LIKE " . $id . ";";
        $result = mysqli_fetch_assoc(mysqli_query($con, $query));
    }

    // close the connection to the database
    mysqli_close($con);
    $addone = $result['times_viewed'];
    echo $addone;
}
?&gt;
No, this code is not vulnerable to SQL injection.  The use of intval() and if (… &amp;&amp; $id &gt; 0) guarantee that $id is a positive integer, so the UPDATE and SELECT queries cannot be malicious.

It is very weird that you use the LIKE operator, though.  Is the id column not an INTEGER?  I would expect that that works by converting every id into a string, then performing pattern matching.  That would be slow because


Converting every id in the hdflv_upload table would be extra work.
The database cannot locate the row with the right id using an index; it has to examine every id.
Pattern matching is more complicated than a simple integer equality check.


Note that in this version, you have fixed a race condition that existed in the previous version.  In the previous version, it is possible to under-count if two pages simultaneously try to update the count, and the sequence ends up being SELECT, SELECT, UPDATE, UPDATE.  This code is better because UPDATE hdflv_upload SET times_viewed = times_viewed + 1 WHERE … should be immune to race conditions.