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

5
  • go for curly syntax like 'My sentence and {$keywords}' Commented Jul 25, 2017 at 2: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. Commented Jul 25, 2017 at 2:15
  • SQL injection, take care, whats the datatype of userid ? its not javascript Commented Jul 25, 2017 at 2:15
  • Possible duplicate of How to combine two strings together in PHP? Commented Jul 25, 2017 at 2:16
  • Its in an If statement, and I check for SQL injection in the username and password, and userid is a VARCHAR. Commented Jul 25, 2017 at 2:20

3 Answers 3

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 . '"';
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.