Michael
Michael

Reputation: 137

Cant insert string into mysql query

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

Upvotes: 0

Views: 231

Answers (3)

Risa__B
Risa__B

Reputation: 462

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

Upvotes: 0

Chris
Chris

Reputation: 3

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

Upvotes: 0

Kevin P
Kevin P

Reputation: 601

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 . '"';

Upvotes: 1

Related Questions