I'm building an API with a bunch of db queries. To avoid repeating some pre established values in each query I created some PHP constants. However I'm not sure about the right way to include them in Mysqli prepared statements. I know that constants can't be passed by reference. So I wonder if I should create a variable for the query that includes the constants or if I could just pass the string directly with the constants to the prepare() function. So it is okay if I do it like this or should I create a variable and storing the string there prior to calling prepare()?
$stmt = $this->conn->prepare("SELECT city FROM masters WHERE email = ? AND estado != '" . STATE_INACTIVE . "'");
$stmt->bind_param("s", $email );
VERSUS
$query = "SELECT city FROM masters WHERE email = ? AND estado != '" . STATE_INACTIVE . "'";
$stmt = $this->conn->prepare($query);
$stmt->bind_param("s", $email );
Since you're using a constant value, you're not exposing yourself to potential SQL injection attacks by concatenating the value into your query. So, I think what you have is fine. Your other option would be to assign the constant value to a variable and bind it, like this:
$query = "SELECT city FROM masters WHERE email = ? AND estado != ?";
$inactiveState = STATE_INACTIVE;
$stmt = $this->conn->prepare($query);
$stmt->bind_param("ss", $email, $inactiveState);
It's worth pointing out as well here that this is mysqli, not PDO. If you were using PDO you could do this:
$query = "SELECT city FROM masters WHERE email = ? AND estado != ?";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $email, PDO::PARAM_STR);
$stmt->bindValue(2, STATE_INACTIVE, PDO::PARAM_STR);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With