Hendz Posted April 23, 2021 Share Posted April 23, 2021 Hi Guys ive given this a go and im continuing to learn php. I want to check from a login section to see does the username exist in the database. Ive gotten this far but i feel like im miles away. Any suggestions would be appreciated. <?php require "config.php"; try { $pdo = new PDO("mysql:host=$host", $username, $password, $options); echo 'DB connected'; } catch (PDOException $e) { throw new PDOException($e->getMessage(), (int)$e->getCode()); } $stmt = $pdo->query('SELECT username FROM databasetest.login WHERE username = !null'); while ($row = $stmt->fetch()) { echo "\n" . PHP_EOL; echo "<br>" . PHP_EOL; echo $row['username']; } Quote Link to comment Share on other sites More sharing options...
Barand Posted April 23, 2021 Share Posted April 23, 2021 You don't say what the problem is, but WHERE username = !null - WRONG WHERE username IS NOT NULL - CORRECT; Quote Link to comment Share on other sites More sharing options...
Strider64 Posted April 23, 2021 Share Posted April 23, 2021 $pwd = password_hash($data['password'], PASSWORD_DEFAULT); unset($data['password']); try { $query = 'INSERT INTO users (fullName, username, status, password, security, email, date_added) VALUES (:fullName, :username, :status, :password, :security, :email, Now())'; $stmt = Database::pdo()->prepare($query); $result = $stmt->execute([':fullName' => $data['fullName'], ':username' => $data['username'], ':status' => $data['status'], ':password' => $this->pwd, ':security' => 'newuser', ':email' => $data['email']]); } catch (PDOException $e) { /* * echo "unique index" . $e->errorInfo[1] . "<br>"; * * An error has occurred if the error number is for something that * this code is designed to handle, i.e. a duplicate index, handle it * by telling the user what was wrong with the data they submitted * failure due to a specific error number that can be recovered * from by the visitor submitting a different value * * return false; * * else the error is for something else, either due to a * programming mistake or not validating input data properly, * that the visitor cannot do anything about or needs to know about * * throw $e; * * re-throw the exception and let the next higher exception * handler, php in this case, catch and handle it */ if ($e->errorInfo[1] === 1062) { return false; } throw $e; } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; // Not for a production server: } If you really want to make sure there can be no duplicates then create an unique index for the username and throw an PDO exception if a duplicate is found. Though I think this would only be useful for a busy busy website. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.