OOP PHP Login/Register System - php

I'm busy with learning OOP PHP and my goal is to make a simple login/register system for users. The idea is to simply register your first name, last name and password, that would be stored into a MySQL database.
Right now i'm trying to store some data into the database, but I'm stuck.. I can't get any data stored into my database. Here is the code I'm working on:
register.php :
<?php
error_reporting(E_ALL);
require_once 'inc/user.php';
$user = new User();
if(isset($_POST['register'])) {
$firstname = ($_POST['firstname']);
$lastname = ($_POST['lastname']);
$password = ($_POST['password']);
$email = ($_POST['email']);
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title> Project Hour </title>
<script src="js/script.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="logo">
<img src="img/logo.png">
</div>
<div class="login">
<div class="form">
<form method="POST" action="#" class="register-form">
<input type="text" name="firstname" placeholder="voornaam"/>
<input type="text" name="lastname" placeholder="achternaam"/>
<input type="password" name="password" placeholder="************"/>
<input type="text" name="email" placeholder="emailadres"/>
<button type="submit" name="register">create</button>
<p class="message"> Al geregistreerd? Inloggen </p>
</form>
</div>
user.php :
<?php
error_reporting(E_ALL);
require_once 'connect.php';
class User {
private $dbase;
public function __constructor() {
$this->dbase = new Connect();
$this->dbase = $this->dbase->dbConnect();
}
public function userRegiser($firstname, $lastname, $password, $email) {
try {
$st = $dbase->prepare("INSERT INTO users(firstname, lastname, password, email) VALUES (:firstname, :lastname, :password, :email)");
$st->bindparam(":firstname", $firstname);
$st->bindparam(":lastname", $lastname);
$st->bindparam(":password", $password);
$st->bindparam(":email", $email);
if($st->execute()) {
echo 'Inserted successfully.';
}
} catch (PDOException $e) {
echo 'Something failed :' . $e->getMessage;
}
}
}
?>
connect.php
<?php
class Connect {
public function dbConnect() {
$user = "root";
$pass = "";
$pdo = 'mysql:host=localhost;dbname=projecthour';
try {
$db = new PDO($pdo, $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed : ' . $e->getMessage();
}
}
}
?>

There are several errors I see here.
First - when form submitted and you have user data - you should call userRegister method:
if(isset($_POST['register'])) {
$firstname = ($_POST['firstname']);
$lastname = ($_POST['lastname']);
$password = ($_POST['password']);
$email = ($_POST['email']);
$user->userRegister($firstname, $lastname, $password, $email);
}
Next problem is
$this->dbase = $this->dbase->dbConnect();
So here $this->dbase is equals to something that is returned by dbConnect method. But this method returns nothing. But it should return PDO instance:
public function dbConnect() {
$user = "root";
$pass = "";
$pdo = 'mysql:host=localhost;dbname=projecthour';
try {
$db = new PDO($pdo, $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// here, return new PDO instance
return $db;
} catch (PDOException $e) {
echo 'Connection failed : ' . $e->getMessage();
}
}
And finally, your userRegiser (by the way it should be userRegis**t**er) method uses $dbase. But $dbase is not what you expect it to be. It's just a local variable, but you need a class property:
public function userRegiser($firstname, $lastname, $password, $email) {
try {
$st = $this->dbase->prepare("INSERT INTO users(firstname, lastname, password, email) VALUES (:firstname, :lastname, :password, :email)");
// ^ here
And thanks to #RajdeepPaul: constructor definition should be:
public function __construct() { // not __constructor!

if(!empty($_POST)) {
$firstname = ($_POST['firstname']);
$lastname = ($_POST['lastname']);
$password = ($_POST['password']);
$email = ($_POST['email']);
// call userRegiser
echo $user->userRegiser($firstname, $lastname, $password, $email);
}
and in User.php
public function userRegiser($firstname, $lastname, $password, $email) {
try {
$st = $dbase->prepare("INSERT INTO users(firstname, lastname, password, email) VALUES (:firstname, :lastname, :password, :email)");
$st->bindparam(":firstname", $firstname);
$st->bindparam(":lastname", $lastname);
$st->bindparam(":password", $password);
$st->bindparam(":email", $email);
if($st->execute()) {
return 'Inserted successfully.';
}
} catch (PDOException $e) {
return 'Something failed :' . $e->getMessage;
}
}

Related

Data not inserting into database when using pdo

i am learning pdo and i tried to play with CRUD method. I am trying to insert data into database using pdo but it isn't inserting. Below is my code
<?php
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT ));
try {
$query = $connect->prepare("INSERT INTO users(username, password) VALUES(?,?)");
$query->execute(array($username, $password));
echo "data";
}
catch (PDOException $event) {
echo $event->getMessage();
}
?>
i have this index file named as index.php
<?php
require_once 'db.php';
session_start();
session_regenerate_id();
?>
<!DOCTYPE html>
<html>
<head>
<title>Sign-Up/Login Form</title>
</head>
<?php
if ($_SERVER['REQUEST_METHOD'] == '$_POST') {
if (isset($_POST['login'])) {
require 'login.php';
}
elseif (isset($_POST['register'])) {
require 'register.php';
}
}
?>
<body>
<form action="index.php" method="POST">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="register" value="Submit">
</form>
</body>
</html>
my db.php looks like
<?php
try {
$connect = new PDO('mysql:dbname=pdologin;host=localhost', 'root', '$$$$');
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $event) {
$event->getMessage();
}
?>
The problem is that your code never reaches your require scripts (login.php or register.php) because your conditional is incorrect.
You have: if ($_SERVER['REQUEST_METHOD'] == '$_POST')
It should be if ($_SERVER['REQUEST_METHOD'] == 'POST')
You're going to end up with something like below while learning or doing some small script that will need a connection, in the long run wrapping this stuff in a function or using a small helper or framework can make this a little easy. Great idea to learn but its still tedious boiler plate no matter how many years you write this stuff.
<?php
//db settings that are typically in a config somewhere
$db_servername = "localhost";
$db_username = "username for your database";
$db_password = "password for your database";
$db_name = "your_db_name";
try {
$connect = new PDO("mysql:host=$db_servername;dbname=$db_name, $db_username, $db_password");
// set the PDO error mode to exception
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Connected successfully";
}catch(PDOException $e){
//echo "Connection failed: " . $e->getMessage();
}
$sth = $connect->prepare("INSERT INTO users(username, password) VALUES(:username,:password)");
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT );
$sth->bindValue(':username', $username, PDO::PARAM_STR);
$sth->bindValue(':password', $password, PDO::PARAM_STR);
$sth->execute();
as a example my team now just writes database binding code like
<?php
//array of ids to insert
$binds['ids'] = array(1,3,4,5,6,7,9,08098);
//Database class is auto included with every script
$success = Database::query('insert into my_table (id) values(:ids)',$binds);
connect first
$connect = mysqli_connect("localhost","root","root","my_db");
then remove the parameters when executing
$query->execute();
try this
<?php
$connect = mysqli_connect("localhost","root","root","my_db");
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT );
try {
$query = $connect->prepare("INSERT INTO users(username, password) VALUES('$username', '$password')");
$query->execute();
}
catch (PDOException $e) {
echo $e->getMessage();
}
?>

Insert multiple rows using form and PDO

Hello guys i am stuck in PHP code to Insert multiple rows using form and PDO
Below my code please help me to fix it
I'll appreciate all comments and suggested solutions
and forgive my mistakes because I am new i PHP
HTML code
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Firstname: <input type="text" name="firstname[]"><br>
Lastname: <input type="text" name="lastname[]"><br>
Email: <input type="text" name="email[]"><br>
<hr>
Firstname: <input type="text" name="firstname[]"><br>
Lastname: <input type="text" name="lastname[]"><br>
Email: <input type="text" name="email[]"><br>
<input type="submit" name="submit" value="Submit">
</form>
PHP Code
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$firstname = input_checker($_POST["firstname"]);
$lastname = input_checker($_POST["lastname"]);
$email = input_checker($_POST["email"]);
foreach ($row as $rows) {
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO memo (firstname, lastname, email)
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $rows);
$stmt->bindParam(':lastname', $rows);
$stmt->bindParam(':email', $rows);
$stmt->execute();
echo "New records created successfully";
}
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
function input_checker($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Indent please, it's hard to read.
It can't work.
DONT FOREACH THE QUERY. You'll send one query with bad datas as many times as you have elements in $rows array
What you're doing here is sending nothing cause $rows don't exist.
So here are the steps.
Do
$rows = array($firstname, $lastname, $email);
$stmt = $conn->prepare("INSERT INTO memo(ID, firstname, lastname, email)
VALUES (NULL, :firstname, :lastname, :email)");
foreach($rows as $key => $value){
$stmt->bindParam($key, $value);
}
$stmt -> execute();
OR you can try building the query this way :
DB_connect :
<?php
$db_username = "root";
$db_password = "";
$db_host = "localhost";
$db_name = "veterinaires";
/* PDO EN FR OU EN ARABE C ISSI */
$db_options = array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");
try {
$db = new PDO("mysql:host={$db_host};dbname={$db_name};charset=utf8", $db_username, $db_password, $db_options);
} catch(PDOException $ex) {
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
?>
Query :
$query = "INSERT INTO patients
(ID,
pet_name,
breed,
colour,
sex,
date_of_birth,
microchip_tatoo,
comment,
owner_ID)
VALUES
(NULL,
:pet_name,
:breed,
:colour,
:sex,
:date_of_birth,
:microchip_tatoo,
:comment,
:owner_ID)";
$query_params = array(':pet_name' => $pet_name,
':breed' => $breed,
':colour' => $colour,
':sex' => $sex,
':date_of_birth' => $date_of_birth,
':microchip_tatoo' => $microchip_tatoo,
':comment' => $comment,
':owner_ID' => $_SESSION['ID']);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$check = true;
}catch(PDOException $ex){
$check = false;
die("Failed to run query: " . $ex->getMessage());
}
?>

PDO connection class prepare error

I got my connection class in a different folder core/connect.php, it's giving me this error and i dont know how to fix it? sorry for the newb question.
Fatal error: Call to a member function prepare() on a non-object in C:\wamp\www\register.php on line 11
<?php
function dbconnect(){
try{
$username = 'root';
$password = '';
$pdo = new PDO("mysql:host=localhost;dbname=lr;", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
echo 'ERROR',$e->getMessage();
}
}
?>
register.php
<form method="POST">
<input type="text" name="username"><br/>
<input type="password" name="password"><br />
<input type="submit">
</form>
<?php
if(isset($_POST['username'], $_POST['password'])){
require 'core/connect.php';
$query = dbconnect()->prepare('INSERT INTO `users` (username, password) VALUES (?, ?)');
$query->bindParam(1, $_POST['username']);
$query->bindParam(2, $_POST['password']);
$query->execute();
}
?>
Try this:
<?php
function dbconnect(){
try{
$username = 'root';
$password = '';
$pdo = new PDO("mysql:host=localhost;dbname=lr;", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
} catch(PDOException $e){
echo 'ERROR',$e->getMessage();
}
}
?>
Make sure you include connect.php in register.php or are using an autoloader etc.

Why won't the data be stored in my database?

Sorry I am new to php so please be patient with me. I am creating a user interface and when I register it says I have registered but it doesn't store the data into the database. can someone please help me!
<?PHP
$uname = "";
$pword = "";
$errorMessage = "";
$num_rows = 0;
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$uname = $_POST['username'];
$pword = $_POST['password'];
$uname = htmlspecialchars($uname);
$pword = htmlspecialchars($pword);
$uLength = strlen($uname);
$pLength = strlen($pword);
if ($uLength >= 10 && $uLength <= 20) {
$errorMessage = "";
}
else {
$errorMessage = $errorMessage . "Username must be between 10 and 20 characters" . "<BR>";
}
if ($pLength >= 8 && $pLength <= 16) {
$errorMessage = "";
}
else {
$errorMessage = $errorMessage . "Password must be between 8 and 16 characters" . "<BR>";
}
if ($errorMessage == "") {
$user_name = "root";
$pass_word = "";
$database = "user authentication";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$uname = quote_smart($uname, $db_handle);
$pword = quote_smart($pword, $db_handle);
$SQL = "SELECT * FROM login WHERE USERNAME = $uname";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$errorMessage = "Username already taken";
}
else {
$SQL = "INSERT INTO login (L1, L2) VALUES ($uname, md5($pword))";
$result = mysql_query($SQL);
mysql_close($db_handle);
//=================================================================================
// START THE SESSION AND PUT SOMETHING INTO THE SESSION VARIABLE CALLED login
// SEND USER TO A DIFFERENT PAGE AFTER SIGN UP
//=================================================================================
session_start();
$_SESSION['login'] = "1";
header ("Location: page1.php");
}
}
else {
$errorMessage = "Database Not Found";
}
}
}
?>
<html>
<head>
<title>Basic Login Script</title>
</head>
<body>
<FORM NAME ="form1" METHOD ="POST" ACTION ="signup.php">
Username: <INPUT TYPE = 'TEXT' Name ='username' value="<?PHP print $uname;?>" maxlength="20">
Password: <INPUT TYPE = 'TEXT' Name ='password' value="<?PHP print $pword;?>" maxlength="16">
<P>
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Register">
</FORM>
<P>
<?PHP print $errorMessage;?>
</body>
</html>
You might also want to rather make use of PDO then you don't have to to do the cleanup of the user input as PDO will take care of that for you. You might want to creat a file that hold all your connection details like this:
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'user authentication');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DSN', 'mysql:host='. DB_HOST . ';dbname=' . DB_NAME);
?>
You then might want to create a class to do the connection to your database like:
<?php
class database{
public function databaseConnect(){
/*Creates a new instance of the PDO called $db.
* NOTE: the use of DSN, DB_USER and so on. These variable live in the dbsettings file.
*/
$db = new PDO(DSN,DB_USER,DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
}
}
?>
Then you might want to create a class to register your user like:
<?php
//Include the database class file to allow access to properties and methods within that class.
require_once 'class.database.php';
//echo 'I am database class file now included in the users class file. <br />';
//This method will be user to check if the user enter the correct username password pair.
class users{
public function checkValidUser($username){
$userExists = false;
try {
$db = database::databaseConnect();
$stmt = $db->prepare('SELECT uname FROM table WHERE uname=:username');
$stmt->bindParam(':uname', $username, PDO::PARAM_STR);
$stmt->execute();
if ($stmt->rowCount() == 1){
$userExists = true;
}
$db = null;
} catch (PDOException $e) {
$userExists = false;
}
return $userExists;
}
public function addUser($firstname, $lastname, $username,$password){
$success = true;
//Connect to the database
try {
$db = database::databaseConnect();
//$db->databaseConnect();
$stmt = $db->prepare('INSERT INTO table (FirstName, LastName, Username, Password) VALUES (:firstname, :lastname, :username, :password)');
$stmt->bindParam(':firstname', $firstname, PDO::PARAM_STR);
$stmt->bindParam(':lastname', $lastname, PDO::PARAM_STR);
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$success = $stmt->execute();
if ($success){
$success = true;
}
$db = null;
} catch (PDOException $e) {
//echo 'There was an error adding a new user. Please go back and try again. If this problem persits please contact the administrator.';
$success = false;
}
return $success;
}
?>
Hope that this helps.
enter link description here$SQL = "INSERT INTO login (L1, L2) VALUES ($uname, md5($pword))";
You're not inserting the values into proper fields, it appears. You're inserting the $uname into L1 and md5($pword) into L2 but in the select query above, you have a different field name for username and I presume the same for password.
$SQL = "SELECT * FROM login WHERE USERNAME = $uname";
Most likely, your insert query should be something like:
$SQL = "INSERT INTO login (USERNAME, PASSWORD) VALUES ('{$uname}', MD5('{$pword}'))";
I added single quotes around the username and password since presumably they are strings. Also, I added curly braces around the variables to segregate what is SQL from what is PHP.
One last thing, I would check into doing this with PDO as Willem suggested

php script echoing part of the php instead of what intended [duplicate]

This question already has answers here:
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
Closed 2 years ago.
I'm having trouble with php script that I've created to insert instances into a database, however I'm getting a trivial output and i dont know how to fix it. the code is:
<?php
try{
$user = 'root';
$pass = null;
$pdo = new PDO('mysql:host=localhost; dbname=divebay', $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$username = $_POST['username'];
$password = sha1($_POST['password']);
$location = %_POST['location'];
$email = $_POST['email'];
$name = $_POST['fname'] . " " . $_POST['surname'];
$check = $pdo->prepare('SELECT * FROM user WHERE username=?');
$check->bindValue(1, $username);
$check->execute();
if($check->fetch(PDO::FETCH_OBJ)){
echo "Account name already exists";
}
else{
$stmt = $pdo->prepare('INSERT INTO user(username, password, location, email, name)
VALUES(:username, :password, :location, :email, :name)');
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->bindParam(':location', $location, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
if($stmt->execute()){
echo "Account created";
}
else{
echo "Account could not be created";
}
}
$pdo = null;
}catch(PDOException $e){
echo $e->getMessage();
}
?>
i would expect the output to be something like "Account created". Instead the output I'm getting this error:
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $username =
$_POST['username']; $password = sha1($_POST['password']);
$location = %_POST['location']; $email = $_POST['email']; $name =
$_POST['fname'] . " " . $_POST['surname']; $check =
$pdo->prepare('SELECT * FROM user WHERE username=?');
$check->bindValue(1, $username); $check->execute();
if($check->fetch(PDO::FETCH_OBJ)){ echo "Account name already exists";
} else{ $stmt = $pdo->prepare('INSERT INTO user(username, password,
location, email, name) VALUES(:username, :password, :location, :email,
:name)'); $stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->bindParam(':location', $location, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
if($stmt->execute()){ echo "Account created"; } else{ echo "Account
could not be created"; } } $pdo = null; }catch(PDOException $e){ echo
$e->getMessage(); } ?>
whats going wrong with this script to cause this?
The only way you'd get that output is if you had written:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
as:
$pdo?>setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
by mistake.
YOU HAVE a % INSTEAD OF $ on %_POST['location']
RECOMMENDATION:
Also I HIGHLY recommend wrapping the PDO functions into a class. Here is what I use personally in every single project:
save this to it's own file (ex:sql.class.php)
<?php
class SqlIt{
public $Sql;
public $Response;
private $Host;
private $DBname;
private $User;
private $Pass;
public $NumResults;
public function __construct($Sql, $type, $vars){
if($vars == ""){
$vars = array();
}
try{
$DB = $this->db_connect();
$DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH = $DB->prepare($Sql);
$doit = $STH->execute($vars);
$this->Result = $doit;
}
catch(PDOException $e){
echo $e->getMessage();
}
//find function to run
switch($type){
case 'select':
$this->select($STH);
break;
}
}
public function select($query){
$rows = $query->rowCount();
$this->NumResults = $rows;
while($row = $query->fetchObject()){
$this->Response[] = $row;
}
}
//create a separate function for connecting to DB. Private to only this class.
private function db_connect(){
$this->User = 'root';
$this->Pass = '';
$DBH = new PDO("mysql:host=localhost;dbname=divebaby", $this->User, $this->Pass);
return $DBH;
}
}
?>
Then to actually run the statement you placed above you simply right the following code:
$username = $_POST['username'];
$password = sha1($_POST['password']);
$location = $_POST['location'];
$email = $_POST['email'];
$name = $_POST['fname'] . " " . $_POST['surname'];
$getUser = new SqlIt("SELECT * FROM user WHERE username=?","select",array($username));
if($getUser){
echo 'Account name already exists';
}else{
$insertUser = new SqlIt("INSERT INTO user (username,password,location,email,name) VALUES (?,?,?,?,?)","insert",array($username,$password,$location,$email,$name));
if($insertUser){
echo 'Account created!';
}else{
echo 'Account not created.';
}
Missing <?php at the beginning of one of your pages that contains that code with the first line of setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Categories