skip to Main Content

In a PHP application I am trying to the users information from the table like below

session_start();

$sql = "SELECT * FROM users WHERE company_id = $_SESSION[‘companyId’]";

$result = $connect->query($sql);

but query statement in bold throws syntax error.

syntax error, unexpected string content "", expecting "-" or identifier or variable or number
Am I missing something?

Attached screenshot

2

Answers


  1. Try this :

    $sql = "SELECT * FROM users WHERE company_id = " . $_SESSION['companyId'];
    

    There are several ways to do this.

    Login or Signup to reply.
  2. First of all, you can’t embed complex expressions in a string that way. You can use braces:

    $string = "Some complex {$expression['value']}";
    

    Or concatenation:

    $string = "Some complex " . $expression['value'];
    

    More importantly, writing a query like that leaves you open to SQL injection. This is a very dangerous way to write queries.

    What you should do is use prepared statements to bind the parameters to your query, like this:

    $statement = $connect->prepare("SELECT * FROM users WHERE company_id = ?");
    
    $statement->bind_param("i", $_SESSION['companyId']);
    
    $result = $statement->execute();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search