Got everything loading and saving correctly using PDO for slightly better security.

Still need to work on creating new dictionaries and switching between them.
This commit is contained in:
Robbie Antenesse 2015-11-25 16:08:24 -07:00
parent 6e88e55e12
commit 8a025d14b5
8 changed files with 270 additions and 191 deletions

32
LOGIN.form Normal file
View File

@ -0,0 +1,32 @@
<div class="settingsCol"><form id="loginForm" method="post" action="?login">
<h2>Log In</h2>
<label><span>Email</span>
<input type="email" id="loginEmailField" name="email" />
</label>
<label><span>Password</span>
<input type="password" id="loginPasswordField" name="password" />
</label>
<div id="loginError" style="font-weight:bold;color:red;"></div>
<button type="submit" id="loginSubmitButton" onclick="ValidateLogin(); return false;">Log In</button>
</form></div>
<div class="settingsCol"><form id="createAccountForm" method="post" action="?createaccount">
<h2>Create a New Account</h2>
<p>Creating an account allows you to save and switch between up to 10 dictionaries and access them from any device for free! Plus if you allow us to send you emails, you'll be the first to hear about any new features that get added or if any of our policies change for any reason.</p>
<label><span>Email</span>
<input type="email" id="createAccountEmailField" name="email" />
</label>
<label><span>Password</span>
<input type="password" id="createAccountPasswordField" name="password" />
</label>
<label><span>Confirm Password</span>
<input type="password" id="createAccountPasswordConfirmField" name="confirmpassword" />
</label>
<label><span>Public Name <span class="clickable" onclick="alert(\'This is the name we greet you with. It is also the name displayed if you ever decide to share any of your dictionaries.\n\nNote: this is not a username, and as such may not be unique. Use something people will recognize you as to differentiate from other people who might use the same name!\')">?</span></span>
<input type="text" id="createAccountPublicNameField" name="publicname" />
</label>
<label><b>Allow Emails</b>
<input type="checkbox" id="createAccountAllowEmailsField" name="allowemails" checked="checked" />
</label>
<div id="createAccountError" style="font-weight:bold;color:red;"></div>
<button type="submit" id="createAccountSubmitButton" onclick="ValidateCreateAccount(); return false;">Create Account</button>
</form></div>

View File

@ -222,6 +222,12 @@ elseif (isset($_GET['loggedout']) && $current_user <= 0) {
<b>Total Entries:</b> <i id="numberOfWordsInDictionary"></i>
</label>
<label><button type="button" onclick="ExportDictionary()" style="cursor:pointer;">Export Current Dictionary</button></label>
<?php if ($current_user > 0) { //If logged in, show the log out button. ?>
<label><span>Change Dictionaries</span>
<select id="userDictionaries" onchange="LoadOtherDictionary();"></select>
</label>
<label><button type="button" onclick="CreateNewDictionary()" style="cursor:pointer;">Create a New Dictionary</button></label>
<?php } ?>
<label>
<span>Import Dictionary</span>
<input type="file" id="importFile" />
@ -261,7 +267,6 @@ elseif (isset($_GET['loggedout']) && $current_user <= 0) {
</body>
</html>
<?php
}
function get_include_contents($filename) {
if (is_file($filename)) {

View File

@ -16,135 +16,18 @@ var currentDictionary = {
partsOfSpeech: "Noun,Adjective,Verb,Adverb,Preposition,Pronoun,Conjunction",
sortByEquivalent: false,
isComplete: false
}
},
externalID: 0
}
var defaultDictionaryJSON = JSON.stringify(currentDictionary); //Saves a stringifyed default dictionary.
var previousDictionary = {};
var savedScroll = {
x: 0,
y: 0
}
window.onload = function () {
LoadDictionary();
ClearForm();
GetTextFile("README.md");
GetTextFile("TERMS.md");
GetTextFile("PRIVACY.md");
}
var aboutText, termsText, privacyText, loginForm, createAccountForm;
loginForm = '<div class="settingsCol"><form id="loginForm" method="post" action="?login"> \
<h2>Log In</h2> \
<label><span>Email</span> \
<input type="email" id="loginEmailField" name="email" /> \
</label> \
<label><span>Password</span> \
<input type="password" id="loginPasswordField" name="password" /> \
</label> \
<div id="loginError" style="font-weight:bold;color:red;"></div> \
<button type="submit" id="loginSubmitButton" onclick="ValidateLogin(); return false;">Log In</button> \
</form></div> \
<div class="settingsCol"><form id="createAccountForm" method="post" action="?createaccount"> \
<h2>Create a New Account</h2> \
<p>Creating an account allows you to save and switch between up to 10 dictionaries and access them from any device for free! Plus if you allow us to send you emails, you\'ll be the first to hear about any new features that get added or if any of our policies change for any reason.</p> \
<label><span>Email</span> \
<input type="email" id="createAccountEmailField" name="email" /> \
</label> \
<label><span>Password</span> \
<input type="password" id="createAccountPasswordField" name="password" /> \
</label> \
<label><span>Confirm Password</span> \
<input type="password" id="createAccountPasswordConfirmField" name="confirmpassword" /> \
</label> \
<label><span>Public Name <span class="clickable" onclick="alert(\'This is the name we greet you with. It is also the name displayed if you ever decide to share any of your dictionaries.\n\nNote: this is not a username, and as such may not be unique. Use something people will recognize you as to differentiate from other people who might use the same name!\')">?</span></span> \
<input type="text" id="createAccountPublicNameField" name="publicname" /> \
</label> \
<label><b>Allow Emails</b> \
<input type="checkbox" id="createAccountAllowEmailsField" name="allowemails" checked="checked" /> \
</label> \
<div id="createAccountError" style="font-weight:bold;color:red;"></div> \
<button type="submit" id="createAccountSubmitButton" onclick="ValidateCreateAccount(); return false;">Create Account</button> \
</form></div>';
function ValidateLogin() {
var errorMessage = document.getElementById("loginError");
var emailValue = document.getElementById("loginEmailField").value;
var passwordValue = document.getElementById("loginPasswordField").value;
if (emailValue == "") {
errorMessage.innerHTML = "Email cannot be blank!";
return false;
} else if (!(/[^\s@]+@[^\s@]+\.[^\s@]+/.test(emailValue))) {
errorMessage.innerHTML = "Your email address looks fake. Email addresses look like this: name@email.com."
return false;
} else if (passwordValue == "") {
errorMessage.innerHTML = "Password cannot be blank!";
return false;
} else {
document.getElementById("loginForm").submit();
}
}
function ValidateCreateAccount() {
var errorMessage = document.getElementById("createAccountError");
var emailValue = document.getElementById("createAccountEmailField").value;
var passwordValue = document.getElementById("createAccountPasswordField").value;
var passwordConfirmValue = document.getElementById("createAccountPasswordConfirmField").value;
var publicNameValue = document.getElementById("createAccountPublicNameField").value;
if (emailValue == "") {
errorMessage.innerHTML = "Email cannot be blank!";
return false;
} else if (!(/[^\s@]+@[^\s@]+\.[^\s@]+/.test(emailValue))) {
errorMessage.innerHTML = "Your email address looks fake. Email addresses look like this: name@email.com."
return false;
} else if (passwordValue == "") {
errorMessage.innerHTML = "Password cannot be blank!";
return false;
} else if (passwordValue != passwordConfirmValue) {
errorMessage.innerHTML = "Passwords do not match!";
return false;
} else if (publicNameValue == "") {
errorMessage.innerHTML = "Public Name cannot be blank!";
return false;
} else {
var emailCheck = new XMLHttpRequest();
emailCheck.open('GET', "php/ajax_createaccountemailcheck.php?email=" + emailValue);
emailCheck.onreadystatechange = function() {
if (emailCheck.readyState == 4 && emailCheck.status == 200) {
if (emailCheck.responseText != "ok") {
errorMessage.innerHTML = "The email address entered is already being used. Try logging in or using a different email address instead.";
return false;
} else {
document.getElementById("createAccountForm").submit();
}
}
}
emailCheck.send();
}
}
function GetTextFile(filename) {
var readmeFileRequest = new XMLHttpRequest();
readmeFileRequest.open('GET', filename);
readmeFileRequest.onreadystatechange = function() {
if (readmeFileRequest.readyState == 4 && readmeFileRequest.status == 200) {
if (filename == "TERMS.md") {
termsText = markdown.toHTML(readmeFileRequest.responseText);
} else if (filename == "PRIVACY.md") {
privacyText = markdown.toHTML(readmeFileRequest.responseText);
} else {
aboutText = markdown.toHTML(readmeFileRequest.responseText);
}
}
}
readmeFileRequest.send();
}
function AddWord() {
var word = htmlEntities(document.getElementById("word").value).trim();
var pronunciation = htmlEntities(document.getElementById("pronunciation").value).trim();
@ -261,7 +144,7 @@ function SaveAndUpdateDictionary(keepFormContents) {
} else {
currentDictionary.words.sort(dynamicSort("simpleDefinition"));
}
SaveDictionary();
SaveDictionary(true, true);
ShowDictionary();
if (!keepFormContents) {
ClearForm();
@ -402,6 +285,7 @@ function SaveSettings() {
currentDictionary.description = htmlEntities(document.getElementById("dictionaryDescriptionEdit").value);
CheckForPartsOfSpeechChange();
LoadUserDictionaries();
currentDictionary.settings.allowDuplicates = document.getElementById("dictionaryAllowDuplicates").checked;
currentDictionary.settings.caseSensitive = document.getElementById("dictionaryCaseSensitive").checked;
@ -433,11 +317,11 @@ function EmptyWholeDictionary() {
}
}
function SaveDictionary() {
function SaveDictionary(sendToDatabase, sendWords) {
localStorage.setItem('dictionary', JSON.stringify(currentDictionary));
//Always save local copy of current dictionary, but if logged in also send to database.
if (currentUser > 0 && sendToDatabase) {
if (sendToDatabase) {
sendWords = (typeof sendWords !== 'undefined') ? sendWords : false;
SendDictionary(sendWords);
}
@ -504,6 +388,9 @@ function DataToSend(doSendWords) {
if (currentDictionary.settings.partsOfSpeech != previousDictionary.partsOfSpeech) {
data += ((data=="") ? "" : "&") + "partsofspeech=" + encodeURIComponent(currentDictionary.settings.partsOfSpeech);
}
if (currentDictionary.settings.sortByEquivalent != previousDictionary.sortByEquivalent) {
data += ((data=="") ? "" : "&") + "sortbyequivalent=" + ((currentDictionary.settings.sortByEquivalent) ? "1" : "0");
}
if (currentDictionary.settings.isComplete != previousDictionary.isComplete) {
data += ((data=="") ? "" : "&") + "iscomplete=" + ((currentDictionary.settings.isComplete) ? "1" : "0");
}
@ -514,17 +401,14 @@ function DataToSend(doSendWords) {
function LoadDictionary() {
LoadLocalDictionary();
if (currentUser > 0) { //If logged in, load the dictionary from database
var loadDictionary = new XMLHttpRequest();
loadDictionary.open('GET', "php/ajax_dictionarymanagement.php?action=load");
loadDictionary.onreadystatechange = function() {
if (loadDictionary.readyState == 4 && loadDictionary.status == 200) {
if (loadDictionary.responseText == "no dictionaries") {
SendDictionary();
SendDictionary(false);
console.log(loadDictionary.responseText);
} else if (loadDictionary.responseText == "could not load" ||
loadDictionary.responseText == "not signed in" ||
loadDictionary.responseText == "no info provided") {
} else if (loadDictionary.responseText.length < 20) {
console.log(loadDictionary.responseText);
} else {
currentDictionary = JSON.parse(loadDictionary.responseText);
@ -537,9 +421,6 @@ function LoadDictionary() {
}
}
loadDictionary.send();
} else {
ProcessLoad();
}
}
function LoadLocalDictionary() {
@ -579,6 +460,7 @@ function SavePreviousDictionary () {
allowDuplicates: currentDictionary.settings.allowDuplicates,
caseSensitive: currentDictionary.settings.caseSensitive,
partsOfSpeech: currentDictionary.settings.partsOfSpeech,
sortByEquivalent: currentDictionary.settings.sortByEquivalent,
isComplete: currentDictionary.settings.isComplete
};
}

121
js/ui.js
View File

@ -1,3 +1,122 @@
var aboutText, termsText, privacyText, loginForm, createAccountForm;
window.onload = function () {
LoadDictionary();
ClearForm();
LoadUserDictionaries();
GetTextFile("README.md");
GetTextFile("TERMS.md");
GetTextFile("PRIVACY.md");
GetTextFile("LOGIN.form");
}
function LoadUserDictionaries() {
var getDictionariesRequest = new XMLHttpRequest();
getDictionariesRequest.open('GET', "php/ajax_dictionarymanagement.php?action=getall");
getDictionariesRequest.onreadystatechange = function() {
if (getDictionariesRequest.readyState == 4 && getDictionariesRequest.status == 200) {
console.log()
var userDictionariesSelect = document.getElementById("userDictionaries");
if (userDictionariesSelect.options.length > 0) {
for (var i = userDictionariesSelect.options.length - 1; i >= 0; i--) {
userDictionariesSelect.removeChild(userDictionariesSelect.options[i]);
}
}
var dictionaries = getDictionariesRequest.responseText.split("_DICTIONARYSEPARATOR_");
for (var j = 0; j < dictionaries.length; j++) {
var dictionaryOption = document.createElement('option');
var dictionaryValues = dictionaries[j].split("_IDNAMESEPARATOR_");
dictionaryOption.appendChild(document.createTextNode(dictionaryValues[1]));
dictionaryOption.value = dictionaryValues[0];
userDictionariesSelect.appendChild(dictionaryOption);
}
if (dictionaries.length > 1) {
userDictionariesSelect.value = "";
}
}
}
getDictionariesRequest.send();
}
function GetTextFile(filename) {
var readmeFileRequest = new XMLHttpRequest();
readmeFileRequest.open('GET', filename);
readmeFileRequest.onreadystatechange = function() {
if (readmeFileRequest.readyState == 4 && readmeFileRequest.status == 200) {
if (filename == "TERMS.md") {
termsText = markdown.toHTML(readmeFileRequest.responseText);
} else if (filename == "PRIVACY.md") {
privacyText = markdown.toHTML(readmeFileRequest.responseText);
} else if (filename == "LOGIN.form") {
loginForm = readmeFileRequest.responseText;
} else {
aboutText = markdown.toHTML(readmeFileRequest.responseText);
}
}
}
readmeFileRequest.send();
}
function ValidateLogin() {
var errorMessage = document.getElementById("loginError");
var emailValue = document.getElementById("loginEmailField").value;
var passwordValue = document.getElementById("loginPasswordField").value;
if (emailValue == "") {
errorMessage.innerHTML = "Email cannot be blank!";
return false;
} else if (!(/[^\s@]+@[^\s@]+\.[^\s@]+/.test(emailValue))) {
errorMessage.innerHTML = "Your email address looks fake. Email addresses look like this: name@email.com."
return false;
} else if (passwordValue == "") {
errorMessage.innerHTML = "Password cannot be blank!";
return false;
} else {
document.getElementById("loginForm").submit();
}
}
function ValidateCreateAccount() {
var errorMessage = document.getElementById("createAccountError");
var emailValue = document.getElementById("createAccountEmailField").value;
var passwordValue = document.getElementById("createAccountPasswordField").value;
var passwordConfirmValue = document.getElementById("createAccountPasswordConfirmField").value;
var publicNameValue = document.getElementById("createAccountPublicNameField").value;
if (emailValue == "") {
errorMessage.innerHTML = "Email cannot be blank!";
return false;
} else if (!(/[^\s@]+@[^\s@]+\.[^\s@]+/.test(emailValue))) {
errorMessage.innerHTML = "Your email address looks fake. Email addresses look like this: name@email.com."
return false;
} else if (passwordValue == "") {
errorMessage.innerHTML = "Password cannot be blank!";
return false;
} else if (passwordValue != passwordConfirmValue) {
errorMessage.innerHTML = "Passwords do not match!";
return false;
} else if (publicNameValue == "") {
errorMessage.innerHTML = "Public Name cannot be blank!";
return false;
} else {
var emailCheck = new XMLHttpRequest();
emailCheck.open('GET', "php/ajax_createaccountemailcheck.php?email=" + emailValue);
emailCheck.onreadystatechange = function() {
if (emailCheck.readyState == 4 && emailCheck.status == 200) {
if (emailCheck.responseText != "ok") {
errorMessage.innerHTML = "The email address entered is already being used. Try logging in or using a different email address instead.";
return false;
} else {
document.getElementById("createAccountForm").submit();
}
}
}
emailCheck.send();
}
}
function CloseUpdateConflictArea() {
document.getElementById("updateConflict").style.display = "none";
}
@ -34,6 +153,8 @@ function ShowInfo(text) {
document.getElementById("infoText").innerHTML = termsText;
} else if (text == "privacy") {
document.getElementById("infoText").innerHTML = privacyText;
} else if (text == "login") {
document.getElementById("infoText").innerHTML = loginForm;
} else {
document.getElementById("infoText").innerHTML = aboutText;
}

View File

@ -27,13 +27,15 @@ function Get_Dictionaries() {
if ($dictionaries) {
if (num_rows($dictionaries) > 0) {
while ($dict = fetch_assoc($dictionaries)) {
$list = "";
$_SESSION['dictionaries'] = [];
while ($dict = fetch($dictionaries)) {
$_SESSION['dictionaries'][] = $dict['id']; // Save a list of all dictionaries user has.
//list for the switch dictionaries dropdown.
$list = $dict['id'] . '_IDNAMESEPARATOR_' . $dict['name'] . '_DICTIONARYSEPARATOR_';
$list .= $dict['id'] . '_IDNAMESEPARATOR_' . $dict['name'] . '_DICTIONARYSEPARATOR_';
}
echo $list;
return true;
}
} else {
echo "no dictionaries";
}
@ -58,7 +60,7 @@ function Load_Current_Dictionary() {
if ($dictionary) {
if (num_rows($dictionary) > 0) {
if (num_rows($dictionary) === 1) {
while ($dict = fetch_assoc($dictionary)) {
while ($dict = fetch($dictionary)) {
$_SESSION['dictionary'] = $dict['id'];
$json = '{"name":"' . $dict['name'] . '",';
$json .= '"description":"' . $dict['description'] . '",';
@ -68,9 +70,9 @@ function Load_Current_Dictionary() {
$json .= '"allowDuplicates":' . (($dict['allow_duplicates'] == 1) ? 'true' : 'false') . ',';
$json .= '"caseSensitive":' . (($dict['case_sensitive'] == 1) ? 'true' : 'false') . ',';
$json .= '"partsOfSpeech":"' . $dict['parts_of_speech'] . '",';
$json .= '"sortByEquivalent":' . (($dict['sort_by_equivalent'] == 1) ? 'true' : 'false') . ',';
$json .= '"isComplete":' . (($dict['is_complete'] == 1) ? 'true' : 'false') . '},';
$json .= '"externalID":' . $dict['id'] . ',';
$json .= '"fileIdentifier":"Lexiconga Dictionary"}';
$json .= '"externalID":' . $dict['id'] . '}';
echo $json;
return true;
}
@ -91,18 +93,25 @@ function Load_Current_Dictionary() {
function Save_Current_DictionaryAsNew() {
if (isset($_SESSION['user'])) {
$conn = connection();
$query = "INSERT INTO `dictionaries`(`user`, `is_current`, `name`, `description`, `words`, `allow_duplicates`, `case_sensitive`, `parts_of_speech`, `is_complete`, `is_public`) ";
$query .= "VALUES (" . $_SESSION['user'] . ",1,'" . $_POST['name'] . "','" . $_POST['description'] . "','" . $_POST['words'] . "'," . $_POST['allowduplicates'] . "," . $_POST['casesensitive'] . ",'" . $_POST['partsofspeech'] . "'," . $_POST['iscomplete'] . "," . $_POST['ispublic'] . ")";
$update = mysqli_query($conn, $query);
$dbconnection = new PDO('mysql:host=' . DATABASE_SERVERNAME . ';dbname=' . DATABASE_NAME . ';charset=utf8', DATABASE_USERNAME, DATABASE_PASSWORD);
$dbconnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbconnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbconnection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
if ($update) {
$_SESSION['dictionary'] = mysqli_insert_id($conn);
$query = "INSERT INTO `dictionaries`(`user`, `is_current`, `name`, `description`, `words`, `allow_duplicates`, `case_sensitive`, `parts_of_speech`, `sort_by_equivalent`, `is_complete`, `is_public`) ";
$query .= "VALUES (" . $_SESSION['user'] . ",1,'" . $_POST['name'] . "','" . $_POST['description'] . "','" . $_POST['words'] . "'," . $_POST['allowduplicates'] . "," . $_POST['casesensitive'] . ",'" . $_POST['partsofspeech'] . "'," . $_POST['sortbyequivalent'] . "," . $_POST['iscomplete'] . "," . $_POST['ispublic'] . ")";
try {
$update = $dbconnection->prepare($query);
$update->execute();
$_SESSION['dictionary'] = $conn->lastInsertId;
$_SESSION['dictionaries'][] = $_SESSION['dictionary']; //Add new id to valid dictionaries.
echo $_SESSION['dictionary'];
return true;
} else {
echo "could not update:\n" . mysqli_error($conn) . "\n" . $query;
}
catch (PDOException $ex) {
$errorMessage = $dbconnection->errorInfo();
echo "could not update:\n" . $errorMessage[2] . "\n" . $query;
}
} else {
echo "no info provided";
@ -132,6 +141,9 @@ function Update_Current_Dictionary() {
if (isset($_POST['partsofspeech'])) {
$query .= "`parts_of_speech`='" . $_POST['partsofspeech'] . "', ";
}
if (isset($_POST['sortbyequivalent'])) {
$query .= "`sort_by_equivalent`='" . $_POST['sortbyequivalent'] . "', ";
}
if (isset($_POST['iscomplete'])) {
$query .= "`is_complete`=" . $_POST['iscomplete'] . ", ";
}
@ -161,7 +173,7 @@ function Switch_Current_Dictionary() {
//Clear is_current from all user's dictionaries and then update the one they chose, only if the chosen dictionary is valid.
$query = "UPDATE `dictionaries` SET `is_current`=0 WHERE `user`=" . $_SESSION['user'] . ";";
$query .= "UPDATE `dictionaries` SET `is_current`=1 WHERE `id`=" . $_POST['newdictionaryid'] . " AND `user`=" . $_SESSION['user'] . ";";
$update = multi_query($query);
$update = query($query);
if ($update) {
Load_Current_Dictionary();

View File

@ -1,24 +1,41 @@
<?php
define("ROOT", $_SERVER["DOCUMENT_ROOT"]);
define("SITE_NAME", "PHP Project");
define("SITE_LOCATION", ROOT . ""); // For absolute file paths: SITE_LOCATION . "/whatever.php"
define("SITE_NAME", "Lexiconga");
define("SITE_LOCATION", ROOT . "/.Lexiconga"); // For absolute file paths: SITE_LOCATION . "/whatever.php"
define("DATABASE_TYPE", "mysql"); //sqlite, mysql, pgsql
function connection() {
define("DATABASE_SERVERNAME", "host");
define("DATABASE_USERNAME", "username");
define("DATABASE_PASSWORD", "password");
define("DATABASE_NAME", "databasename");
$dbconnection = new PDO('mysql:host=' . DATABASE_SERVERNAME . ';dbname=' . DATABASE_NAME . ';charset=utf8', DATABASE_USERNAME, DATABASE_PASSWORD);
$dbconnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbconnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbconnection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
define("DATABASE_CONNECTION", $dbconnection);
/*function connection() {
// Fill this with relevant data.
$servername = "host";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new PDO('mysql:host=' . DATABASE_SERVERNAME . ';dbname=' . DATABASE_NAME . ';charset=utf8', DATABASE_USERNAME, DATABASE_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// $conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// if (!$conn) {
// die("Connection failed: " . mysqli_connect_error());
// }
return $conn;
}
}*/
?>

View File

@ -1,23 +1,35 @@
<?php
// Simplified PHP functions
function query ($query_string) {
$query = mysqli_query(connection(), $query_string);
return $query;
$dbconnection = new PDO('mysql:host=' . DATABASE_SERVERNAME . ';dbname=' . DATABASE_NAME . ';charset=utf8', DATABASE_USERNAME, DATABASE_PASSWORD);
$dbconnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbconnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbconnection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
try {
$queryResults = $dbconnection->prepare($query_string);
$queryResults->execute();
return $queryResults;
}
catch (PDOException $ex) {
return false;
}
function multi_query ($query_string) {
$query = mysqli_multi_query(connection(), $query_string);
return $query;
}
function num_rows ($query_results) {
$num_rows = mysqli_num_rows($query_results);
return $num_rows;
try {
$rowcount = $query_results->rowcount();
return $rowcount;
}
catch (PDOException $ex) {
return false;
}
}
function fetch ($query_results) {
try {
$fetchassoc = $query_results->fetch();
return $fetchassoc;
}
catch (PDOException $ex) {
return false;
}
function fetch_assoc ($query_results) {
$results = mysqli_fetch_assoc($query_results);
return $results;
}
?>

View File

@ -28,9 +28,8 @@ function Get_User_Id($email) {
if ($users && num_rows($users) > 0) {
if (num_rows($users) === 1) {
while($user = fetch_assoc($users)) {
$user = fetch($users);
return $user["id"];
}
} else {
return "More than one user id returned!";
}
@ -45,9 +44,8 @@ function Get_Public_Name($id) {
if ($users && num_rows($users) > 0) {
if (num_rows($users) === 1) {
while($user = fetch_assoc($users)) {
$user = fetch($users);
return $user["public_name"];
}
} else {
return "More than one public name returned!";
}