Skip to content
Advertisement

Prepared statement mysqli SELECT * FROM users

Can someone please tell me what I’m doing wrong. I am trying to select everything from users and then I want to use the [‘password’] and den [‘verified’] strings from the database, where it says ‘//use your bound variables here’. I’m new to prepared statements trying to learn. Thanks

  $read = $db->prepare('SELECT * FROM users WHERE email=? LIMIT 1'); 
  $read->bind_param('s', $email); 
  $read->execute(); 
  $read->store_result(); 
  
  if($read->num_rows > 0){ 
  $read->bind_result($*); 
  $read->fetch(); 
    // use your bound variables here 

       $userpassword=$read['password'];
       $userverified=$read['verified'];

  $read->close(); 
  } else { 
    // no results found 
  }

Advertisement

Answer

If you are only starting to learn PHP then you should learn PDO instead of mysqli. PDO is much easier and more suitable for beginners. Start here https://phpdelusions.net/pdo & https://websitebeaver.com/php-pdo-prepared-statements-to-prevent-sql-injection Don’t waste your time with mysqli.

Using PDO:

$pdo = new PDO("mysql:host=localhost;dbname=test;charset=utf8mb4", 'inet', '5432', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_EMULATE_PREPARES => false
]);

$read = $pdo->prepare('SELECT * FROM users WHERE email=? LIMIT 1');
$read->execute([$email]);
$user = $read->fetch();

if ($user) {
    $userpassword = $user['password'];
    $userverified = $user['verified'];
} else {
    // no results found
}

Using mysqli:

If you must use mysqli then you can use get_result() to fetch mysqli_result object from which you can then fetch an array or an object representing your data.

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'user', 'password', 'test');
$db->set_charset('utf8mb4'); // always set the charset

$read = $db->prepare('SELECT * FROM users WHERE email=? LIMIT 1');
$read->bind_param('s', $email);
$read->execute();
$result = $read->get_result();
$user = $result->fetch_assoc();

if ($user) {
    $userpassword = $user['password'];
    $userverified = $user['verified'];
} else {
    // no results found
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement