2

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();
}
Nicholas Kan
  • 161
  • 1
  • 3
  • 14

3 Answers3

3
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.

Pranav MS
  • 2,235
  • 2
  • 23
  • 50
0

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();
    }
}
Maths RkBala
  • 2,207
  • 3
  • 18
  • 21
0

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.