Question

In my PHP document, I got a SQL query looking like this:

if(isset($_GET['id']))
{
    $id = $_GET['id'];
    $q = "SELECT * FROM `objekt_t` WHERE `id`='" . $id . "'";
    $row = mysqli_query($con, $q) or die(mysqli_error($con));
    while($r = mysqli_fetch_assoc($row))
    {
        $objekt = $r;
    }
}

I realize this is very unsafe practice concerning SQL injections and such, so I've been looking into prepared SQL querys, using bound parameters. Looking at bobby-tables.com I see this example query:

$stmt = $db->prepare('update people set name = ? where id = ?');
$stmt->bind_param('si',$name,$id);
$stmt->execute();

I do not understand how I should modify my current query to match the safer one using bound parameters. Any help is appreciated.

Was it helpful?

Solution

Just the same way

$mysqli = new mysqli("localhost", "my_user", "my_password", "db");

if(isset($_GET['id']))
{
    $id = $_GET['id'];
    $q = "SELECT some_field FROM `objekt_t` WHERE `id`= ?";

    if ($stmt = $mysqli->prepare($q)) {    
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $stmt->bind_result($result);
        $stmt->fetch();
    }
}

Now $result variable contains the resuts of your query.

OTHER TIPS

prepared statements transmit raw data to the query so that SQL injection is not possible. There is no need to escape for real_escape_String or any other formatting functions, as this does it for you.

Example:

$db = new mysqli ("host","user","password","database");
$statement = $db->prepare("SELECT test FROM test WHERE Username=?");
$statement->bind_param('s',$_POST['Username']);
$statement->execute();
$statement->bind_result($resultCol);
$statement->fetch();
$statement->close();

I am basically binding my $_POST data directly to the query because the data is being sent as raw, so even if the query contained a form of injection, as the $_POST['username']; the query will run as normal.


IN terms of the procedure and OOP style, it's down to preference, I personlly prefer the OOP style over the other options as it's more readable.

Working with numbers:

$ID= 5;
$db = new mysqli ("host","user","password","database");
$statement = $db->prepare("SELECT test FROM test WHERE ID=?");
$statement->bind_param('i',$ID);
$statement->execute();
$statement->bind_result($resultCol);
$statement->fetch();
$statement->close();

Or you can work with exact values directly within the statement:

$db = new mysqli ("host","user","password","database");
$statement = $db->prepare("SELECT test FROM test WHERE ID='5'");
$statement->execute();
$statement->bind_result($resultCol);
$statement->fetch();
$statement->close();

You can do it like this:

$stmt = $mysqli->prepare('SELECT * FROM objekt_t WHERE id = ?');
$stmt->bind_param('i', $id);
$stmt->execute();

$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    // $row is an associative array
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top