0

My code:

    $db1 = new PDO ( 'mysql:host=localhost;dbname=db;charset=utf8', 'root', '');
    $db1->setAttribute ( PDO::ATTR_ORACLE_NULLS, PDO::NULL_TO_STRING )
    $qry = $db1->prepare('SELECT user_name FROM user_data WHERE user_id = $userid LIMIT 1');
    $qry -> execute(array($userid));
    $row = $qry -> fetch();
    echo $qry -> user_name;

And it not eching nothing

And I want to find by $userid, and echo the user_name column(like user_id = 1 and it echo Name)

  • 4
    This seems to be a prepared statement with none of the advantages of prepared statments !?!?!? – Strawberry Apr 29 '14 at 12:51
  • you have missed semicolon .....;) – Avinash Babu Apr 29 '14 at 13:10
  • **Building SQL statements with outside variables makes your code vulnerable to SQL injection attacks.** Also, any input data with single quotes in it, like "O'Malley", will blow up your query. Learn about parametrized queries, preferably with the PDO module, to protect your web app. [This question](http://stackoverflow.com/questions/60174) has many detailed examples. See also http://bobby-tables.com/php for alternatives & explanation of the danger. **Running SQL statements built with outside data is like eating soup made from ingredients found on your doorstep.** – Andy Lester May 15 '14 at 16:48

2 Answers2

0
$db1 = new PDO ( 'mysql:host=localhost;dbname=db;charset=utf8', 'root', '');
$db1->setAttribute ( PDO::ATTR_ORACLE_NULLS, PDO::NULL_TO_STRING );
$qry = $db1->prepare("SELECT user_name FROM user_data WHERE user_id = ? LIMIT 1");
$qry -> execute(array($userid));
$row = $qry->fetch();
echo $row->user_name;
Daan
  • 12,099
  • 6
  • 34
  • 51
0

Change:

$qry = $db1->prepare('SELECT user_name FROM user_data WHERE user_id = $userid LIMIT 1');

For:

$qry = $db1->prepare('SELECT user_name FROM user_data WHERE user_id = ? LIMIT 1');

You will assign the value to user_id through execute statement

EDIT:

Add semicolon:

$db1->setAttribute ( PDO::ATTR_ORACLE_NULLS, PDO::NULL_TO_STRING ); <<<-- Missed semicolon
Sal00m
  • 2,938
  • 3
  • 22
  • 33