Nicholas Kan
Nicholas Kan

Reputation: 161

MySQL prepare statement using variable

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();
}

Upvotes: 2

Views: 194

Answers (3)

Erwan MEYNIER
Erwan MEYNIER

Reputation: 1

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.

Upvotes: 0

Maths RkBala
Maths RkBala

Reputation: 2195

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();
    }
}

Upvotes: 0

Pranav MS
Pranav MS

Reputation: 2296

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.

Upvotes: 3

Related Questions