D
D
Donald2016-01-17 22:33:11
PHP
Donald, 2016-01-17 22:33:11

Pulling data from db using pdo?

I swim in php for about a month and a half, I used to do it through mysqli, but I found out that it’s better through PDO
. So the problem is that I can’t figure out how to display data from the database.
In the database table
id record 1
login record admin
code

$pdo = new PDO("mysql:dbname=user;host=localhost", "root", "");
$sql = $pdo->prepare('SELECT * FROM use WHERE login = :login');
$sql->execute([':login' => $login]);
$data = $sql->fetch(PDO::FETCH_ASSOC);
print $data;

nothing to show, please help a newbie, thanks in advance!

Answer the question

In order to leave comments, you need to log in

4 answer(s)
H
hello world, 2016-01-17
Duck @Don_Donald

How do I use PDO. I create a dbconnection.php file and put the following code

$host = 'localhost';
  $database = 'dbname';
  $user = 'user';
  $pass = 'root';

  $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);

As you can see, PDO::FETCH_ASSOC will be the default for everything. Very convenient + easier to edit.
Then I create a function. Here is your example:
function user() {
  global $pdo;
  $stmt = $pdo->query('SELECT * FROM users');
  $data = $stmt->fetchAll();
  return $data;
 }
 $datas = user();
 var_dump($datas);

UPD. #1: Problem Solving. It is possible through the function as above, it is possible without the function. Decide for yourself
$stmt = $pdo->query('SELECT * FROM users');
$data = $stmt->fetchAll();

R
romy4, 2016-01-17
@romy4

turn on all the logs first, maybe there is no connection to the database and the use word is reserved. try to `screen` all fields and table names
ps. through PDO is not better. she is more blunt. it is better to write your own wrapper and inject your own specific driver into it.

A
Alexander Tokmakov, 2016-01-17
@calliko

Try like this

$query = $this->db->prepare("SELECT * FROM model WHERE id=:cat_id");
    $query->execute(array('cat_id'=>$cat_id));
    return $query->fetchAll();

S
Salavat Sitdikov, 2016-01-18
@zona7o

$data - an array? Try print $data['login']for example.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question