PHP - Export CSV Function Goes to Blank Page - php

We are creating a function that exports data from a table to a CSV. However, the code seems to redirect to a blank page. I'm not certain what's going on as I have checked the database and table connections. I could be missing something simple, but staring at the code over and over is making it hard to figure out what's wrong.
<?php
require_once('connection.php');
session_start();
if (!$_SESSION['user']) {
header("Location: index.php"); // If session is not set that redirect to Login Page
}
//set successful imported rows count to 0
$successCount = 0;
if(isset($_POST['submit'])){
$skip = mysqli_real_escape_string($csvDatabase, $_POST['header']);
$colNumber = mysqli_real_escape_string($csvDatabase, $_POST['SUIDnumber']);
$colNumber = $colNumber - 1;
$filename = $_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0) {
for($i=0; $i<count($filename); $i++) {
$file = $filename[$i];
//open file in read only
$files = fopen($file, "r");
//skips first line
fgets($files);
//get data from csv & uses comma to find separate values
while (($getData = fgetcsv($files, 0, ",")) !== FALSE)
{
$fail = FALSE;
//store SUID from 2nd line in csv
$suid = $getData[$colNumber];
if (strlen($suid) === 9 && ctype_digit($suid) ) {
// start ldap look up
$basedn="***";
//Connect to server
$ds=ldap_connect("***");
if ($ds) {
//bind with our special account that retrieves more attributes
$ldaprdn = '***'; // ldap rdn or dn
$ldappass = '***'; // associated password
$r=ldap_bind($ds,$ldaprdn,$ldappass); // this is an authenticated bind
if (substr($suid, 0, 1) === ";" || is_numeric($suid)) {
if ($r) {
//filter to all objectclasses that the SUID we are looking for
$filter = "(&(objectClass=*)(syrEduSUID={$suid}))";
//We are only interested in retrieving these attributes
$justthese = array("displayName", "syrEduLevel", "syrEduProgramDesc", "syrEduProgram", "mail", "eduPersonPrimaryAffiliation", "eduPersonAffiliation" , "uid");
// Search SUID
$sr=ldap_search($ds, $basedn, $filter, $justthese );
//Need to test if the search succeeded. FALSE value means it failed
//if ($sr!==FALSE) {
//Search found something. Now return Attributes and their values - note, there can be multiple values per attribute. We need to make sure the search only returned one result
$entry = ldap_get_entries($ds, $sr);
// if we have only one result, return the values, if not, we have a problem
if ($entry["count"] == 1) {
// get student name and email from suid
$studentName = mysqli_real_escape_string($csvDatabase, $entry[0]['displayname'][0]);
$studentEmail = mysqli_real_escape_string($csvDatabase, $entry[0]['mail'][0]);
$studentAffiliation = mysqli_real_escape_string($csvDatabase, $entry[0]['edupersonprimaryaffiliation'][0]);
$studentProgram = mysqli_real_escape_string($csvDatabase, $entry[0]['syreduprogramdesc'][0]);
$studentEduLevel = mysqli_real_escape_string($csvDatabase, $entry[0]['syredulevel'][0]);
$netID = mysqli_real_escape_string($csvDatabase, $entry[0]['uid'][0]);
$successCount++;
// close ldap
ldap_close($ds);
} else {
$msg = "Ldap search returned 0 or more than one result";
$fail = TRUE;
}
//} else {
// $msg = "Search failed";
// $fail = TRUE;
//}
}
} else {
$msg = "Bind failed";
$fail = TRUE;
}
} else {
$msg = "LDAP connection failed";
$fail = TRUE;
}
//split full name
$studentName = trim($studentName);
$last_name = (strpos($studentName, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $studentName);
$first_name = trim( preg_replace('#'.$last_name.'#', '', $studentName ) );
//inserts data into import table
$sql = "INSERT into import (suid, firstName, lastName, studentEmail, studentAffiliation, studentProgram, studentEduLevel. netID) values ('$suid', '$first_name', '$last_name', '$studentEmail', '$studentAffiliation', '$studentProgram', '$studentEduLevel', '$netID')";
if (!$fail) {
if (mysqli_query($csvDatabase, $sql)) {
//once imported properly, export csv
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($csvDatabase);
}
}
}
}
}
//closes file
fclose($files);
$query = "SELECT suid, firstName, lastName, studentEmail, studentAffiliation, studentProgram, studentEduLevel, netID from import ORDER BY id DESC LIMIT {$successCount}";
$result = mysqli_query($csvDatabase, $query);
if ($result->num_rows > 0) {
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data-export.csv');
$output = fopen("php://output", "w");
$headers = array('SUID', 'First Name', 'Last Name', 'Student Email', 'Student Affiliation', 'studentProgram', 'Student Edu Level', 'NetID');
fputcsv($output, $headers);
while($row = mysqli_fetch_assoc($result))
{
fputcsv($output, $row);
}
fclose($output);
//then delete records in database
$deletesql = "DELETE FROM import ORDER BY id DESC LIMIT {$successCount}";
if (mysqli_query($csvDatabase, $deletesql)) {
//echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($csvDatabase);
}
}
} else {
echo "You did not upload a CSV file or the CSV file is blank.";
}
} else {
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CSV Import</title>
<link rel="stylesheet" href="css/foundation.min.css" />
<link rel="stylesheet" href="css/app.css" />
</head>
<body>
<!-- nav -->
<div class="top-bar">
<div class="top-bar-left">
<ul class="menu">
</ul>
</div>
<div class="top-bar-right">
</div>
</div>
<div class="row" style="margin-top: 5%;">
<div class="medium-12 columns">
<h3>Import CSVs for Student Data</h3>
<div class="callout secondary">
<form name="upload_excel" method="post" enctype="multipart/form-data">
<fieldset class="large-4 cell">
<legend>Does the CSV have a header in the first row?</legend>
<input type="radio" name="header" value="yes" id="yesHeader"><label for="yesHeader">Yes</label>
<input type="radio" name="header" value="no" id="noHeader"><label for="noHeader">No</label>
</fieldset>
<label for="SUIDnumber">
What number column is the SUID field in?
<input type="number" value="" id="SUIDnumber" name="SUIDnumber" required>
</label>
<p>Upload your CSV(s) with SUIDs. You will then be prompted to download the exported data.</p>
<input type="file" id="files" name="file[]" accept=".csv" multiple><br>
<input type="submit" class="button" id="submit" name="submit" value="Import CSV">
</form>
</div>
</div>
</div>
<script src="js/vendor/jquery.min.js"></script>
<script src="js/vendor/what-input.min.js"></script>
<script src="js/foundation.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
<?php } ?>

Was able to find the solution by moving the export CSV function. Thank you all for your help.

Related

PHP | LDAP | Live search in AD

I am using the live search function for my MySQL database data.
But to go directly to the source I do not want a file or db in between and I went directly to the Active Directory itself.
The searching is working but after you searched for something like username, it gives the correct output, the data resets after 2/3 seconds. So the input type text is still filled in but it's showing all the results.
Does anyone can help me with this or can optimize the code?
INDEX.PHP
<!DOCTYPE html>
<?php
session_start();
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Live Search</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<br />
<br />
<br />
<h2 align="center">Live Data Search Active Directory</h2><br />
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Search</span>
<input type="text" name="search_text" id="search_text" placeholder="Search by Customer Details" class="form-control" />
</div>
</div>
<br />
<div id="result"></div>
</div>
<div style="clear:both"></div>
<br />
<br />
<br />
<br />
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"post",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
My fetch.php file with all the links to AD. Ofcourse crendentials and server are filled in and binding is working.
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<div style="overflow-x:auto;">
</head>
</html>
<?php
$output = "";
$ldap_password = "<username>";
$ldap_username = "<password>";
$ldap_connection = ldap_connect("<ldapserver>");
if (FALSE === $ldap_connection){
echo "Unable to connect to the ldap server";
}
ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3) or die("Unable to set LDAP protocol version");
ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0);
if (TRUE === ldap_bind($ldap_connection, $ldap_username, $ldap_password))
{
if (isset($_POST["query"]))
{
$search = $_POST["query"];
$search_filter = "(&(objectCategory=person)(|(sAMAccountName=*".$search.")(sAMAccountName=".$search."*)(l=*".$search."*)))";
}
else
{
$search_filter = "(&(objectCategory=person)(|(sAMAccountName=*)))";
}
$output .= '<table id="customers"><tr><th>Username</th><th>Last Name</th><th>First Name</th><th>Company</th><th>Office</th><th>Department</th><th>Mobile</th><th>Telephone</th><th>E-Mail Address</th></tr>';
$ldap_base_dn = "OU=NL,DC=global,DC=com";
$result = ldap_search($ldap_connection, $ldap_base_dn, $search_filter);
if (FALSE !== $result){
$entries = ldap_get_entries($ldap_connection, $result);
//var_dump($entries);
//For each account returned by the search
for ($x=0; $x<$entries["count"]; $x++){
//Windows Username
$LDAP_samaccountname = "";
if (!empty($entries[$x]["samaccountname"][0])) {
$LDAP_samaccountname = $entries[$x]["samaccountname"][0];
if ($LDAP_samaccountname == "NULL"){
$LDAP_samaccountname= "";
}
} else {
//#There is no samaccountname s0 assume this is an AD contact record so generate a unique username
$LDAP_uSNCreated = $entries[$x]["usncreated"][0];
$LDAP_samaccountname= "CONTACT_" . $LDAP_uSNCreated;
}
//Last Name
$LDAP_LastName = "";
if (!empty($entries[$x]["sn"][0])) {
$LDAP_LastName = $entries[$x]["sn"][0];
if ($LDAP_LastName == "NULL"){
$LDAP_LastName = "";
}
}
//First Name
$LDAP_FirstName = "";
if (!empty($entries[$x]["givenname"][0])) {
$LDAP_FirstName = $entries[$x]["givenname"][0];
if ($LDAP_FirstName == "NULL"){
$LDAP_FirstName = "";
}
}
//Company
$LDAP_CompanyName = "";
if (!empty($entries[$x]["company"][0])) {
$LDAP_CompanyName = $entries[$x]["company"][0];
if ($LDAP_CompanyName == "NULL"){
$LDAP_CompanyName = "";
}
}
//Department
$LDAP_Department = "";
if (!empty($entries[$x]["department"][0])) {
$LDAP_Department = $entries[$x]["department"][0];
if ($LDAP_Department == "NULL"){
$LDAP_Department = "";
}
}
//Office
$LDAP_Office = "";
if (!empty($entries[$x]["l"][0])) {
$LDAP_Office = $entries[$x]["l"][0];
if ($LDAP_Office == "NULL"){
$LDAP_Office = "";
}
}
//Job Title
$LDAP_JobTitle = "";
if (!empty($entries[$x]["title"][0])) {
$LDAP_JobTitle = $entries[$x]["title"][0];
if ($LDAP_JobTitle == "NULL"){
$LDAP_JobTitle = "";
}
}
//Mobile Number
$LDAP_CellPhone = "";
if (!empty($entries[$x]["mobile"][0])) {
$LDAP_CellPhone = $entries[$x]["mobile"][0];
if ($LDAP_CellPhone == "NULL"){
$LDAP_CellPhone = "";
}
}
//Telephone Number
$LDAP_DDI = "";
if (!empty($entries[$x]["telephonenumber"][0])) {
$LDAP_DDI = $entries[$x]["telephonenumber"][0];
if ($LDAP_DDI == "NULL"){
$LDAP_DDI = "";
}
}
//Email address
$LDAP_InternetAddress = "";
if (!empty($entries[$x]["mail"][0])) {
$LDAP_InternetAddress = $entries[$x]["mail"][0];
if ($LDAP_InternetAddress == "NULL"){
$LDAP_InternetAddress = "";
}
}
$output .= '<tr><td><strong>' . $LDAP_samaccountname .'</strong></td><td>' .$LDAP_LastName.'</td><td>'.$LDAP_FirstName.'</td><td>'.$LDAP_CompanyName.'</td><td>'.$LDAP_Office.'</td><td>'.$LDAP_Department.'</td><td>'.$LDAP_CellPhone.'</td><td>'.$LDAP_DDI.'</td><td>'.$LDAP_InternetAddress.'</td></tr>';
} //END for loop
echo $output;
} //END FALSE !== $result
echo("</table>"); //close the table
}
?>
The loop is to display multiple results.
As you can see the result is good, but after 2/3 sec it resets and shows all data instead of the "sbx" value. (data is confidential so not shown, but it's corect)
Greets, Stef

PHP - Export CSV Function Doesn't Process All Data When Header Isn't Skipped

We are creating a function that exports data from a table to a CSV then deletes the data from the table. We have created the ability for the user to select if there is a header in the first row of the CSV (yes or no radio buttons). However, when no is selected, the function only runs for the very first row but doesn't continue to loop the other rows. Any ideas on what is missing?
<?php
require_once('connection.php');
session_start();
if (!$_SESSION['user']) {
header("Location: index.php"); // If session is not set that redirect to Login Page
}
//set successful imported rows count to 0
$successCount = 0;
if(isset($_POST['submit'])){
$skip = mysqli_real_escape_string($csvDatabase, $_POST['header']);
$colNumber = mysqli_real_escape_string($csvDatabase, $_POST['SUIDnumber']);
$colNumber = $colNumber - 1;
//get filename
$filename = $_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0) {
for($i=0; $i<count($filename); $i++) {
$file = $filename[$i];
//open file in read only
$files = fopen($file, "r");
//skips first line
if ($skip === "yes") {
fgetcsv($files, 10000, ",");
}
//get data from csv & uses comma to find separate values
while (($getData = fgetcsv($files, 10000, ",")) !== FALSE)
{
$fail = FALSE;
//store SUID from pre-set line in csv
$suid = $getData[$colNumber];
if (strlen($suid) === 9 && ctype_digit($suid) ) {
// start ldap look up
$basedn="***";
//Connect to server
$ds=ldap_connect("***");
if ($ds) {
//bind with our special account that retrieves more attributes
$ldaprdn = '***'; // ldap rdn or dn
$ldappass = '**'; // associated password
$r=ldap_bind($ds,$ldaprdn,$ldappass); // this is an authenticated bind
if (substr($suid, 0, 1) === ";" || is_numeric($suid)) {
if ($r) {
//filter to all objectclasses that the SUID we are looking for
$filter = "(&(objectClass=*)(syrEduSUID={$suid}))";
//We are only interested in retrieving these attributes
$justthese = array("displayName", "syrEduLevel", "syrEduProgramDesc", "syrEduProgram", "mail", "eduPersonPrimaryAffiliation", "eduPersonAffiliation", "uid" );
// Search SUID
$sr=ldap_search($ds, $basedn, $filter, $justthese );
$entry = ldap_get_entries($ds, $sr);
// if we have only one result, return the values, if not, we have a problem
if ($entry["count"] == 1) {
// get student name and email from suid
$studentName = mysqli_real_escape_string($csvDatabase, $entry[0]['displayname'][0]);
$studentEmail = mysqli_real_escape_string($csvDatabase, $entry[0]['mail'][0]);
$studentAffiliation = mysqli_real_escape_string($csvDatabase, $entry[0]['edupersonprimaryaffiliation'][0]);
$studentProgram = mysqli_real_escape_string($csvDatabase, $entry[0]['syreduprogramdesc'][0]);
$studentEduLevel = mysqli_real_escape_string($csvDatabase, $entry[0]['syredulevel'][0]);
$netID = mysqli_real_escape_string($csvDatabase, $entry[0]['uid'][0]);
$successCount++;
// close ldap
ldap_close($ds);
} else {
$msg = "Ldap search returned 0 or more than one result";
$fail = TRUE;
}
}
} else {
$msg = "Bind failed";
$fail = TRUE;
}
} else {
$msg = "LDAP connection failed";
$fail = TRUE;
}
//split full name
$studentName = trim($studentName);
$last_name = (strpos($studentName, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $studentName);
$first_name = trim( preg_replace('#'.$last_name.'#', '', $studentName ) );
//inserts data into import table
$sql = "INSERT into import (suid, firstName, lastName, studentEmail, studentAffiliation, studentProgram, studentEduLevel, netID) values ('$suid', '$first_name', '$last_name', '$studentEmail', '$studentAffiliation', '$studentProgram', '$studentEduLevel', '$netID')";
if (!$fail) {
if (mysqli_query($csvDatabase, $sql)) {
//once imported properly, export csv
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($csvDatabase);
}
}
}
}
//closes file
fclose($files);
$query = "SELECT suid, firstName, lastName, studentEmail, studentAffiliation, studentProgram, studentEduLevel from import ORDER BY id ASC LIMIT {$successCount}";
$result = mysqli_query($csvDatabase, $query);
if ($result->num_rows > 0) {
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data-export.csv');
$output = fopen("php://output", "w");
$headers = array('SUID', 'First Name', 'Last Name', 'Student Email', 'Student Affiliation', 'studentProgram', 'Student Edu Level');
fputcsv($output, $headers);
while($row = mysqli_fetch_assoc($result))
{
fputcsv($output, $row);
}
fclose($output);
//then delete records in database
$deletesql = "DELETE FROM import ORDER BY id DESC LIMIT {$successCount}";
if (mysqli_query($csvDatabase, $deletesql)) {
//echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($csvDatabase);
}
}
}
} else {
echo "You did not upload a CSV file or the CSV file is blank.";
}
} else {
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CSV Import</title>
<link rel="stylesheet" href="css/foundation.min.css" />
<link rel="stylesheet" href="css/app.css" />
</head>
<body>
<!-- nav -->
<div class="top-bar">
<div class="top-bar-left">
<ul class="menu">
</ul>
</div>
<div class="top-bar-right">
</div>
</div>
<div class="row" style="margin-top: 5%;">
<div class="medium-12 columns">
<form name="upload_excel" method="post" enctype="multipart/form-data">
<h3>Import CSVs for Student Data</h3>
<div class="callout secondary">
<fieldset class="large-4 cell">
<legend>Does the CSV have a header in the first row?</legend>
<input type="radio" name="header" value="yes" id="yesHeader"><label for="yesHeader">Yes</label>
<input type="radio" name="header" value="no" id="noHeader"><label for="noHeader">No</label>
</fieldset>
<label for="SUIDnumber">
What number column is the SUID field in?
<input type="number" value="" id="SUIDnumber" name="SUIDnumber" required>
</label>
<p>Upload your CSV(s) with SUIDs. You will then be prompted to download the exported data.</p>
<input type="file" id="files" name="file[]" accept=".csv" multiple><br>
<input type="submit" class="button" id="submit" name="submit" value="Import CSV">
</div>
</form>
</div>
</div>
<script src="js/vendor/jquery.min.js"></script>
<script src="js/vendor/what-input.min.js"></script>
<script src="js/foundation.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
<?php } ?>

Adding new record and updating record failing in mySQL table with jQuery

I'm following this article on how to do CRUD operations with jQuery dynamically and trying to integrate it with my PHP/MySQL application. However, the add and update record functions are not working and I'm unsure of where it is failing. My knowledge of AJAX and jQuery are limited.
Edit: Add and Update didn't work because I didn't have an ID attached to the carrier selects. Once I added the proper ID, everything started working again. Will update my staff.php to show what it should look like for anyone curious.
The MySQL table used for this is generated on the fly based, but the tables have the following rows:
id
email
mobilePhone
mobileCarrier
firstName
lastName
My code:
Staff.php
<?php
session_start();
require_once('../connection.php');
//get session variable, if empty, unset and logout
if(empty($_SESSION['department'])) {
session_unset();
session_destroy();
header("Location: index.php");
} else {
$dept = $_SESSION[department];
}
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Visitor Management</title>
<link rel="stylesheet" href="../css/foundation.min.css" />
<link rel="stylesheet" href="../css/app.css" />
<link type="text/css" rel="stylesheet" href="https://fast.fonts.net/cssapi/24365087-b739-4314-af6e-741946b60bef.css"/>
<link type="text/css" rel="stylesheet" href="https://fast.fonts.net/cssapi/b05259d9-ca62-44a8-8a19-d3facdbd64df.css"/>
<link type="text/css" rel="stylesheet" href="https://fast.fonts.net/cssapi/2603d516-f938-4b52-ae3a-11d25bb4c555.css"/>
<link type="text/css" rel="stylesheet" href="https://fast.fonts.net/cssapi/510266cf-74ab-4fa8-9b39-dd37b90d6ab0.css"/>
</head>
<body>
<?php
if (!$_SESSION['user']) {
header("Location: ../login.php"); // If session is not set that redirect to Login Page
}
?>
<!-- nav -->
<div class="top-bar admin">
<div class="top-bar-left">
<ul class="menu">
<li class="menu-text">Visitor Management</li>
</ul>
</div>
<div class="top-bar-right">
<ul class="menu">
<li>Logout</li>
</ul>
</div>
</div>
<div class="medium-2 columns dash">
<ul>
<li>Dashboard</li>
<li class="active">Staff</li>
<li>Reports</li>
</ul>
</div>
<div class="medium-10 columns">
<div class="row checkin">
<h2>Staff Profiles</h2>
<h3>All Staff</h3>
<button class="button success" data-open="addStaff">Add New Staff Member</button>
<div class="staff"></div>
<!-- Add Staff Modal -->
<div class="reveal" id="addStaff" data-reveal>
<h3>Add New Staff Member</h3>
<label>First Name
<input type="text" placeholder="" id="firstname">
</label>
<label>Last Name
<input type="text" placeholder="" id="lastname">
</label>
<label>Email Address
<input type="email" placeholder="" id="email">
</label>
<label>Mobile Phone Number
<input type="tel" placeholder="" id="phone">
</label>
<label>Mobile Phone Carrier
<select name="carrier" id="carrier">
<option value="None"> </option>
<option value="AT&T">AT&T</option>
<option value="Verizon">Verizon</option>
<option value="Sprint">Sprint</option>
<option value="TMobile">T-Mobile</option>
<option value="Metro PCS">Metro PCS</option>
</select>
</label>
<button class="button" type="button" onclick="addRecord()">Submit</button>
<button class="close-button" data-close aria-label="Close modal" type="button">
<span aria-hidden="true">×</span>
</button>
</div>
<!-- Edit Staff Modal -->
<div class="reveal" id="editStaff" data-reveal>
<h3>Edit Staff Member</h3>
<label>First Name
<input type="text" placeholder="" id="update_firstname">
</label>
<label>Last Name
<input type="text" placeholder="" id="update_lastname">
</label>
<label>Email Address
<input type="email" placeholder="" id="update_email">
</label>
<label>Mobile Phone Number
<input type="tel" placeholder="" id="update_phone">
</label>
<label>Mobile Phone Carrier
<select name="update_carrier" id="update_carrier">
<option value="None"> </option>
<option value="AT&T">AT&T</option>
<option value="Verizon">Verizon</option>
<option value="Sprint">Sprint</option>
<option value="TMobile">T-Mobile</option>
<option value="Metro PCS">Metro PCS</option>
</select>
</label>
<button class="button" type="button" onclick="UpdateUserDetails()">Submit</button>
<button class="close-button" data-close aria-label="Close modal" type="button">
<span aria-hidden="true">×</span>
</button>
<input type="hidden" id="hidden_user_id">
</div>
</div>
</div>
<script src="../js/vendor/jquery.min.js"></script>
<script src="../js/vendor/what-input.min.js"></script>
<script src="../js/foundation.min.js"></script>
<script src="../js/app.js"></script>
<script>
// Add Staff Member
function addRecord() {
// get values
var firstname = $("#firstname").val();
var lastname = $("#lastname").val();
var email = $("#email").val();
var phone = $("#phone").val();
var carrier = $("#carrier").val();
// Add record
$.post("addRecord.php", {
firstname: firstname,
lastname: lastname,
email: email,
phone: phone,
carrier: carrier
}, function (data, status) {
// close the popup
$("#addStaff").foundation("close");
// read records again
readRecords();
// clear fields from the popup
$("#firstname").val("");
$("#lastname").val("");
$("#email").val("");
$("#phone").val("");
$("#carrier").val("");
});
}
// READ staff members
function readRecords() {
$.get("readRecords.php", {}, function (data, status) {
$(".staff").html(data);
});
}
$(document).ready(function () {
// READ recods on page load
readRecords(); // calling function
});
// Delete staff member
function DeleteUser(id) {
var conf = confirm("Are you sure, do you really want to delete this staff member?");
if (conf == true) {
$.post("deleteUser.php", {
id: id
},
function (data, status) {
// reload Users by using readRecords();
readRecords();
}
);
}
}
// Get staff member details
function GetUserDetails(id) {
// Add User ID to the hidden field for furture usage
$("#hidden_user_id").val(id);
$.post("readUserDetails.php", {
id: id
},
function (data, status) {
// PARSE json data
var user = JSON.parse(data);
// Assing existing values to the modal popup fields
$("#update_firstname").val(user.firstName);
$("#update_lastname").val(user.lastName);
$("#update_email").val(user.email);
$("#update_phone").val(user.mobilePhone);
$("#update_carrier").val(user.mobileCarrier);
}
);
// Open modal popup
$("#editStaff").foundation("open");
}
function UpdateUserDetails() {
// get values
var firstname = $("#update_firstname").val();
var lastname = $("#update_lastname").val();
var email = $("#update_email").val();
var phone = $("#update_phone").val();
var carrier = $("#update_carrier").val();
// get hidden field value
var id = $("#hidden_user_id").val();
// Update the details by requesting to the server using ajax
$.post("updateUserDetails.php", {
id: id,
firstname: firstname,
lastname: lastname,
email: email,
phone: phone,
carrier: carrier
},
function (data, status) {
// hide modal popup
$("#editStaff").foundation("close");
// reload Users by using readRecords();
readRecords();
}
);
}
</script>
</body>
</html>
Connection.php
<?php
# FileName="connection.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_VisitorManagement = "localhost";
$database_VisitorManagement = "visitor-management";
$username_VisitorManagement = "***";
$password_VisitorManagement = "***";
$VisitorManagement = mysqli_connect($hostname_VisitorManagement, $username_VisitorManagement, $password_VisitorManagement, $database_VisitorManagement);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
date_default_timezone_set('America/New_York');
?>
addRecord.php
<?php
// include Database connection file
session_start();
require_once('../connection.php');
if(empty($_SESSION['department'])) {
session_unset();
session_destroy();
header("Location: ../index.php");
} else {
$dept = $_SESSION[department];
}
$staffTable = $dept . "_staff";
if(isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['email']) && isset($_POST['phone']) && isset($_POST['carrier']))
{
// get values
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$carrier = $_POST['carrier'];
$query = "INSERT INTO {$staffTable}(firstName, lastName, email, mobilePhone, mobileCarrier) VALUES('$firstname', '$lastname', '$email', '$phone', '$carrier')";
if (!$result = mysqli_query($VisitorManagement, $query)) {
exit(mysqli_error($VisitorManagement));
}
echo "Staff Member Has Been Added!";
}
?>
readRecords.php
<?php
// include Database connection file
session_start();
require_once('../connection.php');
if(empty($_SESSION['department'])) {
session_unset();
session_destroy();
header("Location: ../index.php");
} else {
$dept = $_SESSION[department];
}
$staffTable = $dept . "_staff";
// Design initial table header
$data = "<table id='staff'>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Mobile Phone</th>
<th>Mobile Carrier</th>
<th></th>
</tr>
</thead>";
$query = "SELECT * FROM {$staffTable} ORDER BY lastName";
if (!$result = mysqli_query($VisitorManagement, $query)) {
exit(mysqli_error($VisitorManagement));
}
// if query results contains rows then featch those rows
if(mysqli_num_rows($result) > 0)
{
$number = 1;
while($row = mysqli_fetch_assoc($result))
{
$data .= '<tbody>
<tr>
<td>'.$row['firstName'] . " " . $row['lastName'].'</td>
<td>'.$row['email'].'</td>
<td>'.$row['mobilePhone'].'</td>
<td>'.$row['mobileCarrier'].'</td>
<td>
<button onclick="GetUserDetails('.$row['id'].')" class="button secondary">Edit</button> <button onclick="DeleteUser('.$row['id'].')" class="button alert">Delete</button>
</td>
</tr>
</tbody>';
$number++;
}
}
else
{
// records now found
$data .= '<tr><td colspan="6">Records not found!</td></tr>';
}
$data .= '</table>';
echo $data;
?>
deleteUser.php
<?php
// include Database connection file
session_start();
require_once('../connection.php');
if(empty($_SESSION['department'])) {
session_unset();
session_destroy();
header("Location: ../index.php");
} else {
$dept = $_SESSION[department];
}
$staffTable = $dept . "_staff";
// check request
if(isset($_POST['id']) && isset($_POST['id']) != "")
{
// get user id
$user_id = $_POST['id'];
// delete User
$query = "DELETE FROM {$staffTable} WHERE id = '$user_id'";
if (!$result = mysqli_query($VisitorManagement, $query)) {
exit(mysqli_error($VisitorManagement));
}
}
?>
readUserDetails.php
<?php
// include Database connection file
session_start();
require_once('../connection.php');
if(empty($_SESSION['department'])) {
session_unset();
session_destroy();
header("Location: ../index.php");
} else {
$dept = $_SESSION[department];
}
$staffTable = $dept . "_staff";
// check request
if(isset($_POST['id']) && isset($_POST['id']) != "")
{
// get User ID
$user_id = $_POST['id'];
// Get User Details
$query = "SELECT * FROM {$staffTable} WHERE id = '$user_id'";
if (!$result = mysqli_query($VisitorManagement, $query)) {
exit(mysqli_error($VisitorManagement));
}
$response = array();
if(mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$response = $row;
}
}
else
{
$response['status'] = 200;
$response['message'] = "Data not found!";
}
// display JSON data
echo json_encode($response);
}
else
{
$response['status'] = 200;
$response['message'] = "Invalid Request!";
}
?>
updateUserDetails.php
<?php
// include Database connection file
session_start();
require_once('../connection.php');
if(empty($_SESSION['department'])) {
session_unset();
session_destroy();
header("Location: ../index.php");
} else {
$dept = $_SESSION[department];
}
$staffTable = $dept . "_staff";
// check request
if(isset($_POST))
{
// get values
$id = $_POST['id'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$carrier = $_POST['carrier'];
// Updaste User details
$query = "UPDATE {$staffTable} SET firstName = '$firstname', lastName = '$lastname', email = '$email', mobilePhone = '$phone', mobileCarrier = '$carrier' WHERE id = '$id'";
if (!$result = mysqli_query($VisitorManagement, $query)) {
exit(mysqli_error($VisitorManagement));
}
}
?>
Am I missing something? Has anyone used that article before to create add, update, and delete records functions before?
Thank you for your help.
The best you can do now is to debug your code (using developers function of your browser - check if your ajax script is called properly) and/or check your php error log.
anyway, remove curly brackets in the insert/update query, it may helps too

Mysqli and PDO combined with Javascript and Ajax... possible?

Simple question from a noob programer. Thinking of several different styles and features to a project i have for a social website. question is this...
can you combine mysqli and PDO style programs?
having difficulty inserting data into database with php, ajax and javascript modules. it says "success" but doesnt insert the info with mysqli. i HAVE used PDO successfully. but my code looks right... it has the same syntax as the tutorial i am looking at with mysqli. this is the code...
<!-- ********************************** -->
<!-- *********** signup.php *********** -->
<!-- ********************************** -->
<?php
session_start();
// If user is logged in, header them away
if(isset($_SESSION["username"])){
header("location: message.php?msg=NO to that weenis");
exit();
}
?><?php
// Ajax calls this NAME CHECK code to execute
if(isset($_POST["usernamecheck"])){
include_once("php_includes/db_conx.php");
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']);
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$uname_check = mysqli_num_rows($query);
if (strlen($username) < 3 || strlen($username) > 16) {
echo '<strong style="color:#F00;">3 - 16 characters please</strong>';
exit();
}
if (is_numeric($username[0])) {
echo '<strong style="color:#F00;">Usernames must begin with a letter</strong>';
exit();
}
if ($uname_check < 1) {
echo '<strong style="color:#009900;">' . $username . ' is OK</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $username . ' is taken</strong>';
exit();
}
}
?><?php
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once("php_includes/db_conx.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = $_POST['p'];
$g = preg_replace('#[^a-z]#', '', $_POST['g']);
$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$u_check = mysqli_num_rows($query);
// -------------------------------------------
$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$e_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if($u == "" || $e == "" || $p == "" || $g == "" || $c == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if ($e_check > 0){
echo "That email address is already in use in the system";
exit();
} else if (strlen($u) < 3 || strlen($u) > 16) {
echo "Username must be between 3 and 16 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else {
// END FORM DATA ERROR HANDLING
// Begin Insertion of data into the database
// Hash the password and apply your own mysterious unique salt
$cryptpass = crypt($p);
include_once ("php_includes/randStrGen.php");
$p_hash = randStrGen(20)."$cryptpass".randStrGen(20);
// Add user info into the database table for the main site table
$sql = "INSERT INTO users (username, email, password, gender, country, ip, signup, lastlogin, notescheck)
VALUES('$u','$e','$p_hash','$g','$c','$ip',now(),now(),now())";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
// Establish their row in the useroptions table
$sql = "INSERT INTO useroptions (id, username, background) VALUES ('$uid','$u','original')";
$query = mysqli_query($db_conx, $sql);
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
if (!file_exists("user/$u")) {
mkdir("user/$u", 0755);
}
// Email the user their activation link
$to = "$e";
$from = "auto_responder#yoursitename.com";
$subject = 'yoursitename Account Activation';
$message = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>yoursitename Message</title></head><body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;"><div style="padding:10px; background:#333; font-size:24px; color:#CCC;"><img src="http://www.yoursitename.com/images/logo.png" width="36" height="30" alt="yoursitename" style="border:none; float:left;">yoursitename Account Activation</div><div style="padding:24px; font-size:17px;">Hello '.$u.',<br /><br />Click the link below to activate your account when ready:<br /><br />Click here to activate your account now<br /><br />Login after successful activation using your:<br />* E-mail Address: <b>'.$e.'</b></div></body></html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "signup_success";
exit();
}
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="css/style.css">
<style type="text/css">
</style>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "email"){
rx = /[' "]/gi;
} else if(elem == "username"){
rx = /[^a-z0-9]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
_(x).innerHTML = "";
}
function checkusername(){
var u = _("username").value;
if(u != ""){
_("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("unamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
}
function signup(){
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var c = _("country").value;
var g = _("gender").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else if( _("terms").style.display == "none"){
status.innerHTML = "Please view the terms of use";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g);
}
}
function openTerms(){
_("terms").style.display = "block";
emptyElement("status");
}
/* function addEvents(){
_("elemID").addEventListener("click", func, false);
}
window.onload = addEvents; */
</script>
</head>
<body>
<?php include_once("includes/template_header.php"); ?>
<div id="pageMiddle">
<h3>Sign Up Here</h3>
<form name="signupform" id="signupform" onsubmit="return false;">
<div>Username: </div>
<input id="username" type="text" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16">
<span id="unamestatus"></span>
<div>Email Address:</div>
<input id="email" type="text" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">
<div>Create Password:</div>
<input id="pass1" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Confirm Password:</div>
<input id="pass2" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Gender:</div>
<select id="gender" onfocus="emptyElement('status')">
<option value=""></option>
<option value="m">Male</option>
<option value="f">Female</option>
</select>
<div>Country:</div>
<select id="country" onfocus="emptyElement('status')">
<?php include_once("includes/template_country_list.php"); ?>
</select>
<div>
<a href="#" onclick="return false" onmousedown="openTerms()">
View the Terms Of Use
</a>
</div>
<div id="terms" style="display:none;">
<h3>Web Intersect Terms Of Use</h3>
<p>1. Play nice here.</p>
<p>2. Take a bath before you visit.</p>
<p>3. Brush your teeth before bed.</p>
</div>
<br /><br />
<button id="signupbtn" onclick="signup()">Create Account</button>
<span id="status"></span>
</form>
</div>
<?php include_once("includes/template_bottom.php"); ?>
</body>
</html>
<!-- ********************************** -->
<!-- *********** activation.php ******* -->
<!-- ********************************** -->
<?php
if (isset($_GET['id']) && isset($_GET['u']) && isset($_GET['e']) && isset($_GET['p'])) {
// Connect to database and sanitize incoming $_GET variables
include_once("php_includes/db_conx.php");
$id = preg_replace('#[^0-9]#i', '', $_GET['id']);
$u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
$e = mysqli_real_escape_string($db_conx, $_GET['e']);
$p = mysqli_real_escape_string($db_conx, $_GET['p']);
// Evaluate the lengths of the incoming $_GET variable
if($id == "" || strlen($u) < 3 || strlen($e) < 5 ){
// Log this issue into a text file and email details to yourself
header("location: message.php?msg=activation_string_length_issues");
exit();
}
// Check their credentials against the database
$sql = "SELECT * FROM users WHERE id='$id' AND username='$u' AND email='$e' AND password='$p' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
// Evaluate for a match in the system (0 = no match, 1 = match)
if($numrows == 0){
// Log this potential hack attempt to text file and email details to yourself
header("location: message.php?msg=Your credentials are not matching anything in our system");
exit();
}
// Match was found, you can activate them
$sql = "UPDATE users SET activated='1' WHERE id='$id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
// Optional double check to see if activated in fact now = 1
$sql = "SELECT * FROM users WHERE id='$id' AND activated='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
// Evaluate the double check
if($numrows == 0){
// Log this issue of no switch of activation field to 1
header("location: message.php?msg=activation_failure");
exit();
} else if($numrows == 1) {
// Great everything went fine with activation!
header("location: message.php?msg=activation_success");
exit();
}
else {
// Log this issue of missing initial $_GET variables
header("location: message.php?msg=missing_GET_variables");
exit();
}}
?>
<!-- ********************************** -->
<!-- *********** message.php ********** -->
<!-- ********************************** -->
<?php
$message = "";
$msg = preg_replace('#[^a-z 0-9.:_()]#i', '', $_GET['msg']);
if($msg == "activation_failure"){
$message = '<h2>Activation Error</h2> Sorry there seems to have been an issue activating your account at this time. We have already notified ourselves of this issue and we will contact you via email when we have identified the issue.';
} else if($msg == "activation_success"){
$message = '<h2>Activation Success</h2> Your account is now activated. Click here to log in';
} else {
$message = $msg;
}
?>
<div><?php echo $message; ?></div>
<!-- ********************************** -->
<!-- ********* randStrGen.php ********* -->
<!-- ********************************** -->
<?php
function randStrGen($len){
$result = "";
$chars = "abcdefghijklmnopqrstuvwxyz0123456789$$$$$$$1111111";
$charArray = str_split($chars);
for($i = 0; $i < $len; $i++){
$randItem = array_rand($charArray);
$result .= "".$charArray[$randItem];
}
return $result;
}
?>
is it possible to rewrite so different modules interact?

I have a csv create script working on my local host but when uploaded to my web server the page doesnt load

Basically I have the following code in my folder. So I have my signup.php which is like my index.php(main page) and I have my cvs_func.php that holds the functions for creating the cvs file. It all works fine on my localhost but when I upload it to my webserver(BlueHost) nothing appears on the page.
Here is my signup.php
<?php
//session_start();
include_once('includes/connection.php');
include_once('includes/csv_func.php');
//give file path of csv file below
$data = read_csv('test.csv');
$data[] = array('5','Gareth','Bale','7/27/14');
write_csv('test_2.csv', $data);
//display add page
if(isset($_POST['fname'], $_POST['lname']))
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$show_modal = false;
if(empty($fname) or empty($lname))
{
$error = true;
}else
{
$thank_you = true;
$query = $pdo->prepare('INSERT INTO signin_form (cust_fname, cust_lname, cust_timestamp) VALUES (?, ?, ?)');
$query->bindValue(1, $fname);
$query->bindValue(2, $lname);
$query->bindValue(3, time());
$query->execute();
}
}
?>
<html>
<head>
<title>Alva Sign In</title>
<link href="styles/style.css" rel="stylesheet">
</head>
<body>
<div class="container">
<?php
date_default_timezone_set("America/Los_Angeles");
?>
Admin<br/>
<h1>Welcome to Alva Dynamics!</h1>
<h2>Please sign in below.</h2>
<form action="signup.php" method="POST" autocomplete="off">
<center><input type="text" name="fname" placeholder="First Name"></center>
<center><input type="text" name="lname" placeholder="Last Name"></center>
<center><input type="submit" value="Sign In" class="btn" /></center>
</form>
<?php
if(isset($error))
{
echo "<h3>Please enter your first and last name!</h3>";
}
?>
<?php
if(isset($thank_you))
{
echo '<h3 class="ty">Thank you for signing in!</h3>';
}
?>
</div>
</body>
</html>
And this is my csv_func.php
<?php
//reads a csv file returning an array of rows
function read_csv($filename)
{
$rows = array();
foreach(file($filename, FILE_IGNORE_NEW_LINES) as $line)
{
$rows[] = str_getcsv($line);
}
return $rows;
}
//writes the given array of rows to a csv file
function write_csv($filename, $rows)
{
$file = fopen($filename, 'w');
foreach($rows as $row)
{
fputcsv($file, $row);
}
fclose($file);
}
?>
So it wont display anything on the webpage but I should still see a form to input a first and last name. But when I load the code I get a blank page. Any ideas?

Categories