0

I'm trying to make a login page in PHP, and I'm trying to construct the query here:

$q = 'SELECT * FROM users WHERE userid="'+$username+'"';

When I echo it out with

echo $q

I get 0. When I do

$q = 'SELECT * FROM users WHERE userid="'+"test"+'"';

I get 0. When I do

$q = 'SELECT * FROM users WHERE userid="michael"';

I get my expected result of the string being printed out

chris85
  • 23,846
  • 7
  • 34
  • 51
Michael
  • 137
  • 1
  • 10
  • go for curly syntax like `'My sentence and {$keywords}'` – aldrin27 Jul 25 '17 at 02:15
  • 1
    `+` is for math in PHP. Use a `.` You also might be open to SQL injections with this code, best to parameterize your query. Also `userid` will probably never equal `$username`. – chris85 Jul 25 '17 at 02:15
  • SQL injection, take care, whats the datatype of userid ? its not javascript – Akshay Hegde Jul 25 '17 at 02:15
  • Possible duplicate of [How to combine two strings together in PHP?](https://stackoverflow.com/questions/8336858/how-to-combine-two-strings-together-in-php) – chris85 Jul 25 '17 at 02:16
  • Its in an If statement, and I check for SQL injection in the username and password, and userid is a VARCHAR. – Michael Jul 25 '17 at 02:20

3 Answers3

1

Use a . for concatenation, also don't forget to clean the data to prevent mysql injection.

$user_id = 'test';
$q = 'SELECT * FROM users WHERE userid="' . $user_id . '"';
Kevin P
  • 601
  • 3
  • 9
0

Try using a PDO Prepared statement to protect yourself from SQL injection.

$q = 'SELECT * FROM users WHERE userid = ?';
$stmt = $dbh->prepare($q);
if ($stmt->execute(array($username))) {
  while ($row = $stmt->fetch()) {
    print_r($row);
  }
}

http://php.net/manual/en/pdo.prepared-statements.php

Chris
  • 33
  • 4
0

you can use .

$user_id = 'michael';
$q = 'SELECT * FROM users WHERE userid="'.$user_id.'"';

or use double quotes for the expression and use single quotes for the variables

$user_id = 'michael';
$q = "SELECT * FROM users WHERE userid='$user_id'";

im Believe the second option is smallest and easiest to remember

Risa__B
  • 451
  • 4
  • 8