Does this code avoid SQL injection? I have the following PHP code but I'm unsure, based on the many things I've read, whether or not this is actually safe from an SQL injection attack.

$mysqli = new mysqli("address.address.address", "username", "password", "database");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$stmt = $mysqli-&gt;prepare('INSERT INTO tablename (value) VALUES (?)');
$stmt-&gt;bind_param("s", $val);

$val = $_GET['val'];
$stmt-&gt;execute();


$stmt = $mysqli-&gt;prepare('SELECT * FROM tablename WHERE value = ?');
$stmt-&gt;bind_param('s', $val);

$val = $_GET['val'];

$stmt-&gt;execute();

$result = $stmt-&gt;get_result();
while ($row = $result-&gt;fetch_assoc()) {
    echo $row['id'].'&lt;br /&gt;';
}

$stmt-&gt;close();

$mysqli-&gt;close();


Can anyone offer their opinion on how to improve this, please?
It looks safe from SQL Injection, your binding and preparing is fine.

This is how I would do it, using the PHP code found here in the manual.

In fact, these calls would benefit from being in their own functions; however this would work the same.

&lt;?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$val = $_GET['val'];

/* create a prepared statement */
if ($stmt = $mysqli-&gt;prepare("INSERT INTO tablename (value) VALUES (?)")) {

    /* bind parameters for markers */
    $stmt-&gt;bind_param("s", $val);

    /* execute query */
    if($stmt-&gt;execute()) {
       echo 'INSERTED';
    }
    /* close statement */
    $stmt-&gt;close();
}

if ($stmt = $mysqli-&gt;prepare("SELECT * FROM tablename WHERE value = ?")) {

    /* bind parameters for markers */
    $stmt-&gt;bind_param("s", $val);

    /* execute query */
    if($stmt-&gt;execute()) {
        $result = $stmt-&gt;get_result();
        while ($row = $result-&gt;fetch_assoc()) {
            echo $row['id'].'&lt;br /&gt;';
        }
    }

    /* close statement */
    $stmt-&gt;close();
}

/* close connection */
$mysqli-&gt;close();
?&gt;