Why This INSERT Doesn't Work...?

@robertbralic007,

It is often useful to start with something simple and then expand once it is working. Here is a functioning example using only two columns for clarity:

<?php
// Always start with this so you can see your errors
error_reporting(E_ALL);

$link = new mysqli('localhost', 'user', 'password', 'mysqli');

// Some sample values, no real need to deal with POST for now
$b_mjestro  = 'mjestro';
$b_restoran = 'restoran';

// This works but is very insecure
$query = 
    "INSERT INTO restoran (b_mjesto,b_restoran) 
     VALUES ('$b_mjestro','$b_restoran');";
$link->query($query);

// Prepared statements should be used instead
$stmt = $link->prepare(
    'INSERT INTO restoran (b_mjesto,b_restoran) VALUES (?,?);'
);
$stmt->bind_param('ss',$b_mjestro,$b_restoran);
$stmt->execute();

You can actually put the above code in a php file and then test it from a console window with ‘php filename.php’; You might find it easier to understand what is going on without having to make an html page and deal with posting and whatnot.

The first example is what everyone is talking about when they say things like “sql injection”. Just avoid it.

The second example is more secure. There are actually a number of possible variations. You can for example use names instead of ? marks as placeholders. Here is a more detailed example of using prepared statements.

Enjoy

8 Likes