Last active
August 29, 2015 14:19
-
-
Save elrok123/f0d15ac0f9ec9b1b9609 to your computer and use it in GitHub Desktop.
Small excerpt from my dev CMS system showing basic PHP data object manipulations to store information in a MySQL database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* This section of code is used to save user information to the database using PHP Data Objects, it also verifies that the user is signed in | |
* | |
*/ | |
//Start session to allow manipulation of session data | |
session_start(); | |
//Main database access information include | |
include('../../../../dbaccess/index.php'); | |
//Prewritten modules include (to make life easier) | |
include('../../../../dbaccess/modules.php'); | |
$username = $_SESSION['username']; | |
//Remove session data already stored | |
unset($_SESSION['userToEdit']); | |
//Check if username is stored in the session, if not, then the user is not logged in and should return to the login | |
if(isset($_SESSION["username"]) == false) | |
{ | |
# Redirect the user back a directory to the index | |
header("Location: ../"); | |
} | |
//Try to create a new user, if it fails to create then print the error on the page regarding the database | |
try | |
{ | |
//Check to see if all appropriate parameters have been sent | |
if($_POST['userPass'] == $_POST['userPassVerify'] && $_POST['userUsername'] != "" && $_POST['userFirstname'] != "" && $_POST['userSurname'] != "" && $_POST['userEmail'] != "" && $_POST['userSurname'] != "") | |
{ | |
//Prepare the MySQL statment to be binded with data, and use appropriate placeholders | |
$statement = $conn->prepare("INSERT INTO users (username, firstname, surname, email, password, userRole) VALUES (:username, :firstname, :surname, :email, :password, 1)"); | |
//Bind strings to the MySQL statement using respective placeholders | |
$statement->bindParam(":username", $_POST['userUsername']); | |
$statement->bindParam(":firstname", $_POST['userFirstname']); | |
$statement->bindParam(":surname", $_POST['userSurname']); | |
$statement->bindParam(":email", $_POST['userEmail']); | |
//This is slightly different as the users password must be hashed and salted for security | |
$statement->bindParam(":password", crypt($_POST['userPass'], "\$thisIsAsecret\$")); | |
$statement->execute(); | |
//Return user back to the main page | |
header("Location: ../"); | |
} | |
else | |
{ | |
//Show error if there was a problem with the data sent | |
echo "There was an error saving, check your form data..."; | |
} | |
} | |
catch(PDOException $e) | |
{ | |
//Print error to page | |
echo $e; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment