Is merging variables safe for SQL injection?

I have multiple user inputs

$place = $_POST["errorreport_place"];
$os = $_POST["errorreport_os"];
$browser = $_POST["errorreport_browser"];
$text_user = $_POST["errorreport_text_user"];
$section = $_GET["section"];

      

and a few session variables that are not created by the user (they are from the database)

$user_id = $_SESSION["user_id"];
$username = $_SESSION["username"];

      

Now Im merging all these user created variables into one text string

$text = "ERROR REPORTED BY $username (ID: $user_id)<br /><br />Place: $place<br />Operating System: $os<br />Browser: $browser<br />Text:<br />$text";

      

And then I insert this data into the database (but with prepared statements)

$done = 0;
$sql = $db->prepare("INSERT INTO errorreports (user_id, section, text, done) VALUES (?, ?, ?, ?)");
$sql->bind_param('issi', $user_id, $section, $text, $done);
$sql->execute();

      

And now my question is, is this method safe against SQL injection (because I didn't prepare each user input separately?

+3


source to share


2 answers


Your method is safe. Concatenation before insertion is irrelevant when using prepared statements. The prepared statement will prepare the integer value $text

as a whole string for insertion, which is still separated from the query itself.



+4


source


Your method is safe because you are using Prepared Statements. $sql = $db->prepare("INSERT INTO errorreports (user_id, section, text, done) VALUES (?, ?, ?, ?)");



SQL injection can occur when mixing data with a query. Prepared assertions ensure that the request and data are sent separately to the server

+2


source







All Articles