3

I'm beginning to use prepared statements with my sql queries in php and in starting with this I have come up with a question.

I have a function that grabs a user's id from a table at login. I want the user to be able to use either their username or email address for their login.

So my sql statement is:

SELECT * FROM `login` WHERE `username`=? OR `emailAddress`=?

Now essentially when in this query username and emailAddress will be the same because it can be either or.

So when binding my statements do I bind my variable twice:

bind_param('ss', $user, $user);

So the value for username and emailAddress needs to be the same. Essentially I want $user to be the value of both the placeholders.

My questions are: Am I doing this correctly? Is there a more efficient way?

4

2 回答 2

4

是的,您必须绑定它两次。如果您出于某种原因反对,您可以将查询改写为:

SELECT *
FROM `login` l cross join
      (select ? as thename) const
WHERE l.`username` = thename OR `emailAddress` = thename;

这是使用子查询来命名参数,因此可以在查询中多次引用它。

于 2013-09-03T20:33:47.873 回答
1

是的。调用中的变量必须bind_param()与查询中的占位符一样多。考虑一下你是否有:

SELECT * FROM login
WHERE username = ? and emailAddress = ? and country = ?

你试图绑定太少:

bind_param("ss", $user, $country);

它应该如何知道应该为额外的占位符重复哪个变量?

两次使用相同的变量没有问题。不过,我不会推荐它与 bind_result 一起使用——它可能会允许它,但我不知道是否可以预测将哪一列放入变量中。

于 2013-09-03T19:55:17.380 回答