MySQL使用变量准备语句

问题描述:

I am using below PHP + MySQL prepare statement to select values from database, passing the variable into the statement using function, however I could not get my wanted result. The problem is I don't know how to using the variable in the prepare statement.

Question: Could you take a look whether the syntax I am using is correct?

public function getToken($committeeValue){
    $stmt = $this->conn->prepare("SELECT u.token FROM users u INNER JOIN committee c ON u.email = c.email WHERE c.'$committeeValue' = 1");
    $stmt->execute();
}

我在PHP + MySQL下面使用prepare语句从数据库中选择值,使用函数将变量传递给语句, 但是我无法得到我想要的结果。 问题是我不知道如何在prepare语句中使用变量。 p>

问题: 你能看看我使用的语法是否正确吗? p>

 公共函数getToken($ committeeValue){
 $ stmt = $ this-> conn-> prepare(“SELECT u.token FROM users u INNER JOIN committee c ON u.email  = c.email WHERE c。'$ committeeValue'= 1“); 
 $ stmt-> execute(); 
} 
  code>  pre> 
  div>

Please try the below one.   

 public function getToken($committeeValue){
        $stmt = $this->conn->prepare("SELECT u.token FROM users u INNER JOIN committee c ON u.email = c.email WHERE c.".$committeeValue." = 1");
        $stmt->execute();
    }

I think you are made a mistake to appending a php variable within the string.Please try this.

You made the mistake of concatenating string in PHP.

So please try this below:

public function getToken($committeeValue){
    $committeeValue = trim($committeeValue);
    if(!empty($committeeValue)){
        $query = "SELECT u.token FROM users u INNER JOIN committee c ON u.email = c.email WHERE c.".$committeeValue." = 1";
        $stmt = $this->conn->prepare($query);
        $stmt->execute();
    }
}

Using var content directly is not safe because it allow to inject SQL statements. The safe way is, in your case:

public function getToken($committeeValue){
  $committeeValue = trim($committeeValue);
  if(!empty($committeeValue)){
    $query = "SELECT u.token FROM users u INNER JOIN committee c ON u.email = c.email WHERE c.? = 1";
    $stmt = $this->conn->prepare($query);
    $stmt->bindParam(1, $committeeValue);
    $stmt->execute();
  }
}

The query will be compiled without the var content so you dont have to worry about SQL injection.