Showing posts with label how to connect with mysqli. Show all posts
Showing posts with label how to connect with mysqli. Show all posts

06 May, 2013

PHP MySQLi secure login page with session set


I'll be teaching you how to make a secure login page with PHP with simple mysqli connection and will set variable to return error on the form. I'll set session that'll save your login credentials and login expiration time.

<?php
define("DB_HOST","your-mysql-hostname");
define("DB_USER","your-mysql-account-username");
define("DB_PASS","your-mysql-account-password");
define("DB_NAME","your-mysql-database-name");

// CONNECT TO MYSQLI
$sqli = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME) or die(mysqli_errno());

// FETCH DATA FROM FORM USING METHOD POST
// IF BUTTON NAME "LOGIN" IS SET
if (isset($_POST['login'])) {




// FETCH DATA FROM INPUT FIELD
$user = mysqli_real_escape_string($sqli, $_POST['user']);
$pass = mysqli_real_escape_string($sqli, $_POST['pass']);

// CHECK ALL FIELD HAS BEEN FILLED UP
if ($user && $pass) {

// QUERY FROM DATABASE
$query= mysqli_query($sqli, "SELECT * FROM member WHERE user='".$user."'");
$checkuser= mysqli_num_rows($query);

// CHECK IF USERNAME EXIST ON DATABASE
if($checkuser != 1) {

// I'LL BE SETTING A VARIABLE IF YOUR DOESN'T EXIST
$error = "Username doesn't exist in our database!";
}

// FETCHING PASSWORD IN DATABASE WHERE USERNAME COINCIDES
while ($row = mysqli_fetch_array($user)) {
$checkpass= $row['pass'];


// CHECK IF ENTERED PASSWORD MEETS THE USERNAME PASSWORD
if ($pass== $checkpass) {

// IF ALL OKAY SET SESSION
setcookie("user", $user, time()+7200);
$_SESSION['user'] = $user;
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + (60 * 60 * 60);
header("Location: ".$_SERVER['PHP_SELF']);
exit();
} else {

// SET VARIABLE THAT'LL SHOW IF USER PASSWORD IS INCORRECT
$error = "Incorrect password!";
}
}
} else {

// SET VARIABLE IF ALL FIELD ARE NOT FILLED UP
$error = "Please enter a username and password.";
}
}

?>

<div style="text-align: center;">
<span class="error"><?php if(isset($error)) { echo $error; } ?></span>
<form action="" method="post" id="loginForm">
<span class="input">Username: <input type="text" name="user" maxlength="16"></span>
<span class="input">Password: <input type="password" name="pass"

12 April, 2013

PHP MySQLi - MySQL Improved connection


Since MySQL extension is deprecated and will be removed as of PHP 5.5 onwards, I'll be teaching you how to connect to a mysql database using the new method, MySQL Improved or MySQLi. I'll be writing 2 methods on how to connect and query on MySQLi.

1) Simple connection

//First I'll  define variables
define("HOST","YOUR_MYSQL_HOST");
define("USER","YOUR_MYSQL_USERNAME");
define("PASS","YOUR_MYSQL_PASSWORD");
define("DBASE","YOUR_MYSQL_DATABASE");