<?php
require_once('dbconfig.php');
global $con;
$query = $con->prepare("SELECT * FROM userinfo order by id DESC");
$query->execute();
mysqli_stmt_bind_result($query, $id, $name, $username, $password);
Asked
Active
Viewed 78 times
0
-
1Don't globalise `$con`, that's a huge security hole and is also bad practise from a coding point of view – Martin Sep 16 '20 at 17:39
2 Answers
1
Try this
$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$options = [
PDO::ATTR_EMULATE_PREPARES => false, // turn off emulation mode for "real" prepared statements
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array
];
try {
$pdo = new PDO($dsn, "username", "password", $options);
} catch (Exception $e) {
error_log($e->getMessage());
exit('Something weird happened'); //something a user can understand
}
$arr = $pdo->query("SELECT * FROM myTable")->fetchAll(PDO::FETCH_ASSOC);

mzea
- 26
- 5
-
Some good advice here. If you can add some text to explain it a little that would be great. – Martin Sep 16 '20 at 17:52
1
You should use ->bindColumn
Manual
See also This answer.
- Best Practise: Do not use
SELECT *
instead define each column you need to grab from the table. - Do not globalise your connection variable. This is a security risk as well as adding bloat and should be unneeded on your code.
- Because it is a static statement you can use
->query
rather thanprepare
, as nothing needs to be prepared.
Solution:
$query = $con->query("SELECT id,name,username,password FROM userinfo ORDER BY id DESC");
try {
$query->execute();
$query->bindColumn(1, $id);
$query->bindColumn(2, $name);
$query->bindColumn(3, $username);
$query->bindColumn(4, $password);
}
catch (PDOException $ex) {
error_log(print_r($ex,true);
}
Alternatively:
A nice feature of PDO::query() is that it enables you to iterate over the rowset returned by a successfully executed SELECT statement. From the manual
foreach ($conn->query('SELECT id,name,username,password FROM userinfo ORDER BY id DESC') as $row) {
print $row['id'] . " is the ID\n";
print $row['name'] . " is the Name\n";
print $row['username'] . " is the Username\n";
}
See Also:
Mzea Has some good hints on their answer, you should use their $options
settings as well as using their suggested utf8mb4
connection character set.
And their suggestion for using ->fetchAll
is also completely valid too.

Martin
- 22,212
- 11
- 70
- 132