0

I am trying to create a login page where I have to link my database to the PHP code along with SQL query. I am using a SELECT and WHERE statement to assign the variable to the code, but it gives me a syntax error because I cannot concatenate the variables. Here's the code and please help me out.

$login = trim($_POST["id"]);

$password = trim($_POST["pass"]);

$conn = db_connect();


$sql = "SELECT first_name, last_name, email_address, last_access FROM
users WHERE id = '".$login."' AND password = '".$password."'";

$results = pg_query($conn, $sql);

if(pg_num_rows($results))
{ 
   //not zero means something was found
   //user found, use pg_fetch_result to pull user specific info to display
   pg_fetch_result($results);

}
else
{
   //user not found, check for just login id
   $sql = "SELECT * FROM users WHERE id = '".$login."'";
   $results = pg_query($conn, $sql);
   if(!pg_num_rows($results))
   {  //user not found, empty $login to unstick it
      $login = ""; //when echo’’ed in the form
   }
}


?>

I can also show you a snip where the AND password part is showing in green color which means it is getting inside the double quotes and not working as an inbuilt function.

You can see the green part which is getting inside the double quotes.

  • 4
    Your `php` code is syntactically correct and the concatenation works. But you shouldn't take that approach. You should always use [prepared statements and parameterized queries](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) in either the `MYSQLI` or `PDO` instead of concatenating user provided values into the query. This is to avoid [SQL Injection attacks](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) but it also has the side benefit of allowing perfect syntax highlighting in your editor. – Andrea Olivato Apr 10 '22 at 01:25
  • 1
    If you're receiving error it's not about the concatenation but something else. Please edit your question to share the code above/after this sql statement and the exact error. – Andrea Olivato Apr 10 '22 at 01:27
  • Practice using prepared statements. –  Apr 10 '22 at 01:51
  • `This is to avoid SQL Injection attacks` .... which should be a big concern to you period, but even more so because you appear to be storing passwords in plain text! Passwords should be hashed and never stored in plain text. – SOS Apr 10 '22 at 05:39

0 Answers0