[英]How to use PHP constants in Mysqli prepared statements
I'm building an API with a bunch of db queries. 我正在使用一堆数据库查询构建一个API。 To avoid repeating some pre established values in each query I created some PHP constants.
为了避免在每个查询中重复一些预先建立的值,我创建了一些PHP常量。 However I'm not sure about the right way to include them in Mysqli prepared statements.
但是我不确定将它们包含在Mysqli准备语句中的正确方法。 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.
所以我想知道我是否应该为包含常量的查询创建一个变量,或者我是否可以直接将字符串与常量一起传递给prepare()函数。 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()?
所以我可以这样做,或者我应该在调用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. 由于您使用的是常量值,因此通过将值连接到查询中,您不会暴露自己潜在的SQL注入攻击。 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. 值得指出的是,这是mysqli,而不是PDO。 If you were using PDO you could do this:
如果您使用PDO,您可以这样做:
$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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.