0

I'm aware that if you're inserting a variable, it is always good to use mysqli_real_escape_string. But, if I'm inserting a fixed value which is not a variable, do I need to use that function?

For example, like the syntax below. I insert a name which is a variable, and also a value '1' into the status column. Is it safe to do that to avoid SQL injection for the column status? since it is not a variable.

"INSERT INTO customer(name, status) VALUES ('".mysqli_real_escape_string($conn, $name) ."', '1')";
nodeffect
  • 1,830
  • 5
  • 25
  • 42

2 Answers2

1

When using mysqli, it is safest to use prepared statements:

$stmt=$mysqli->prepare("INSERT INTO customer(name, status) 
  VALUES (?, '1')";
$stmt->bind_param("s", $name);

(See http://php.net/manual/en/mysqli.quickstart.prepared-statements.php for the more detailed and working code).

In this you can leave static values as is, nobody can replace those. You can also alter your table:

ALTER TABLE customer ALTER COLUMN status DEFAULT '1';

Then you do not even have to set it any longer.

Norbert
  • 6,026
  • 3
  • 17
  • 40
  • if I am to insert a fixed value for example, INSERT INTO customer(status) VALUES ('1').... is it necessary to use prepared statement? – nodeffect Aug 03 '15 at 04:43
  • 1
    No, not needed at all. The prepared statement is best when you have any dynamic variable since you do not have to think about escaping, concatenating strings and quotes. – Norbert Aug 03 '15 at 04:44
1

There is no objection and need to escape the values on constant as SQL Injection will not be done on static things..

smali
  • 4,687
  • 7
  • 38
  • 60