Search code examples
phpmysqliprepared-statement

Passing one literal variable as well as placeholders in prepared statement?


I am creating a form that will be submitted by the user. In the form submission process, some values are hardcoded in the source code and are inserted as it is. Can I pass these values directly to the prepared statement? Other user input data I am binding that will be replaced with the ? placeholder.

For example:

...
$litVariable = 1;
$userInput   = $_POST['user_input'];
$myquery     = $mysqli->prepare("INSERT INTO table(`column1`,`column2`) VALUES('$litVariable',?)");
$myquery->bind_param("s",$user_input);
...

Is that ok and safe to pass $litVariable directly to query and user-generated input with $myquery->bind_param("s",$user_input);, as I did above?


Solution

  • Yes, what you are doing should be safe, because the value $litVariable which you are concatenating into the query string does not come from the outside. This means that the first item in your VALUES clause should not be prone to injection attacks coming from the outside. That being said, I would still suggest not even doing this, because it leaves your insert query looking prone to attack. There is no reason to not use bound parameters everywhere. That is, I suggest the following:

    $litVariable = 1;
    $userInput = $_POST['user_input'];
    $sql = "INSERT INTO table(column1, column2) VALUES (?, ?)";
    $myquery = $mysqli->prepare(sql)
    $myquery->bind_param("is", $litVariable, $user_input);