D
D
Donald2016-01-18 22:50:40
PHP
Donald, 2016-01-18 22:50:40

What's wrong with fetching data from the database?

All code

$host = 'localhost';
$database = 'data';
$user = 'root';
$pass = '';
$dsn = "mysql:host=$host;dbname=$database;";
$options = array(
  PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, $user, $pass, $options);
$sql = $pdo->prepare("SELECT login FROM dataname WHERE id");
$sql->execute([$id]);
$data = $sql->fetch();
echo $data['login'];

everything is going fine, it shows the login from the database, but if I substitute a placeholder in this line
$sql = $pdo->prepare("SELECT login FROM dataname WHERE id = ?");

it doesn't output anything.
Please tell me what is the reason, and what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
hello world, 2016-01-19
Duck @Don_Donald

$sql = $pdo->prepare('SELECT login FROM users WHERE id=?');
  if ( $sql->execute(array($_GET['name'])) )
  {
    while ($row = $sql->fetchAll())
    {
     print_r($row);
    }
  }

Result prntscr.com/9ru08u
Either
$sql = $pdo->prepare('SELECT login FROM users WHERE id=?');
  $sql->bindValue(1, $_GET['name']);
  $sql->execute();
  $data = $sql->fetch();

Result prntscr.com/9ru14y
Either
$sql = $pdo->prepare('SELECT login FROM users WHERE id=:id');
  $sql-> execute(array(':id' => (int)$_GET['name']));
  $data = $sql->fetchAll();

Result prntscr.com/9ru95k

S
StrikeBack, 2016-01-18
@StrikeBack

The documentation says that you need to pass an array to the execute method, try this:
$sql->execute(array([$id]));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question