PHP | LDAP | Live search in AD - php

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

Related

PHP - Export CSV Function Goes to Blank Page

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.

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 } ?>

duplicate page content after ajax to the same page

I have simple registration formulae and I want I want to firstly send with ajax and without refreshing the page to control if I insert correct data and then just redirect to some other page. The problem is that after I send it through ajax to the same page everything is working but content of my page is being duplicate, I can see it twice...
here is my ajax
function registruj () {
var name = $('#meno').val();
var priez = $('#priezvisko').val();
var log = $('#login').val();
var mail = $('#mail').val();
var cisloTel = $('#cislo').val();
var heslo = $('#heslo').val();
var heslo1 = $('#heslo1').val();
$.post( "", {
'meno': name,
'priezvisko': priez,
'login':log,
'mail':mail,
'cislo':cisloTel,
'heslo':heslo,
'heslo1':heslo1,
}, function (data) {
$('#result').html(data);
}
);
$('#nove').load(document.URL + ' #nove');
}
and this is my php file
<?php
session_start();
if(isset($_POST["meno"]) ) {
echo "kokot";
echo $_POST['meno'];
require "pripojenie.php";
$meno = $_POST["meno"];
$priezvisko = $_POST["priezvisko"];
$login = $_POST["login"];
$heslo = $_POST["heslo"];
$hesloZnovu = $_POST["heslo1"];
if(isset($_POST["pohlavie"]))
$pohlavie = $_POST["pohlavie"];
$mail = $_POST['mail'];
$cislo = $_POST['cislo'];
//$id = $_SESSION['id'];
}
?>
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8" />
<title>blblblbl</title>
<link rel="stylesheet" type="text/css" href="./fancybox/jquery.fancybox-1.3.4.css" media="screen" />
<script src="jquery-1.4.3.min.js"></script>
<script type="text/javascript" src="./fancybox/jquery.mousewheel-3.0.4.pack.js"></script>
<script type="text/javascript" src="./fancybox/jquery.fancybox-1.3.4.pack.js"></script>
<script>$(function(){$('.img').fancybox();});</script>
<style type="text/css"> </style>
<script type="text/javascript" src="mojskript.js"></script>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" type="text/css" href="css/style1.css" />
</head>
<body class="registracia">
<div class="container">
<div id="nove">
<form >
<table >
<tr><td><label for="napdis">Vyplňte nasledujúci formulár:</label></td></tr>
<tr><td><input type="radio" name="pohlavie" value="zena" id="zena" >Žena</td></tr>
<br>
<tr><td><input type="radio" name="pohlavie" value="muz" id="muz">Muž</td></tr>
<br>
<tr><td><label for="meno">Meno :</label></td><td><input type = "text" id="meno" name="meno"></td></tr><br>
<tr><td><label for="priezvisko">Priezvisko :</label></td><td><input type = "text" id="priezvisko" name="priezvisko"></td></tr><br>
<tr><td><label for="login">Login :</label></td>
<td><input type = "text" id="login" name="login"></td></tr><br>
<?php
if(isset($heslo)) {
if (($heslo != "" && $hesloZnovu != "") && ($heslo == $hesloZnovu)) {
$hesloOk = 1;
}
else {
echo '<tr><td><label for="heslo">Heslo :</label><td><input type = "password" name="heslo"></td><td><label for="zleHeslo">Heslá sa nezhodujú</label></td></tr>';
$pocet = 1;
}
}
?>
<?php
if(!isset($pocet)) {
echo'<tr ><td ><label for="heslo" > Heslo :</label ></td >
<td ><input type = "password" id="heslo" name = "heslo" ></td ></tr ><br >';
}
?>
<tr><td><label for="heslo2">Heslo znovu :</label></td>
<td><input type = "password" id="heslo1" name="heslo1"></td></tr><br>
<?php
if(isset($mail)) {
if (!stristr($mail, "#") OR !stristr($mail, ".")) {
echo '<tr><td><label for="email">E-mail :</label></td>
<td><input type = "text" name="email"></td><td><label for="zlyMail">Zlý formát emailu</label></td></rd></tr><br>';
} else {
$mailOk = 1;
}
}
else {
echo '<tr><td><label for="email">E-mail :</label></td>
<td><input type = "text" id="mail" name="email"></td></tr><br>';
}
?>
<tr><td><label for="cislo">Telefónne číslo :</label></td>
<td><input type = "text" id="cislo" name="cislo"></td></tr><br>
<tr><td><input type="button" value="Zaregistrovať" onclick="registruj()" ></td></tr>
</table>
</form>
<?php
if(isset($mailOk) && isset($hesloOk)) {
$length = 20;
$randomString = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
$zasifrovane = crypt($heslo,$randomString);
echo $zasifrovane;
mysql_query("INSERT INTO uzivatelia (Meno,Priezvisko,Login,Heslo,mail,pohlavie,cislo) VALUES ('$meno','$priezvisko','$login','$zasifrovane','$mail','$pohlavie','$cislo')");
header("location:index.php");
}
?>
</div>
<div id="result"></div>
</div>
</body>
How should I do that ?
Try to use exit(); like :
session_start();
if(isset($_POST["meno"]) ) {
echo "kokot";
echo $_POST['meno'];
require "pripojenie.php";
$meno = $_POST["meno"];
$priezvisko = $_POST["priezvisko"];
$login = $_POST["login"];
$heslo = $_POST["heslo"];
$hesloZnovu = $_POST["heslo1"];
if(isset($_POST["pohlavie"]))
$pohlavie = $_POST["pohlavie"];
$mail = $_POST['mail'];
$cislo = $_POST['cislo'];
//$id = $_SESSION['id'];
exit();
}
Use exit(); or die(); when ajax processing done otherwise it will return all page content.
Change success function to:
function (data) {
$('#result').empty().html(data);
}

Not able to randomise questions rows in mysql

Im trying to get random questions from my sql table.The rand() function is not working. The rand() function for 'answers' is working but not for 'questions' row. Where am I going wrong? . Can anyone give a solution to this?
index.php
<?php
$msg = "";
if(isset($_GET['msg'])){
$msg = $_GET['msg'];
$msg = strip_tags($msg);
$msg = addslashes($msg);
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Quiz Tut</title>
<script>
function startQuiz(url){
window.location = url;
}
</script>
</head>
<body>
<?php echo $msg; ?>
<h3>Click below when you are ready to start the quiz</h3>
<button onClick="startQuiz('quiz.php?question=1')">Click Here To Begin</button>
</body>
</html>
questions.php
<?php
session_start();
require_once("scripts/connect_db.php");
$arrCount = "";
if(isset($_GET['question'])){
$question = preg_replace('/[^0-9]/', "", $_GET['question']);
$output = "";
$answers = "";
$q = "";
$sql = mysql_query("SELECT id FROM questions");
$numQuestions = mysql_num_rows($sql);
if(!isset($_SESSION['answer_array']) || $_SESSION['answer_array'] < 1){
$currQuestion = "1";
}else{
$arrCount = count($_SESSION['answer_array']);
}
if($arrCount > $numQuestions){
unset($_SESSION['answer_array']);
header("location: index.php");
exit();
}
if($arrCount >= $numQuestions){
echo 'finished|<p>There are no more questions. Please enter your first and last name and click next</p>
<form action="userAnswers.php" method="post">
<input type="hidden" name="complete" value="true">
<input type="text" name="username">
<input type="text" name="email">
<input type="submit" value="Finish">
</form>';
exit();
}
$singleSQL = mysql_query("SELECT * FROM questions WHERE id='$question' order by RAND() LIMIT 1");
while($row = mysql_fetch_array($singleSQL)){
$id = $row['id'];
$thisQuestion = $row['question'];
$type = $row['type'];
$question_id = $row['question_id'];
$q = '<h2>'.$thisQuestion.'</h2>';
$sql2 = mysql_query("SELECT * FROM answers WHERE question_id='$question' ORDER BY rand()");
while($row2 = mysql_fetch_array($sql2)){
$answer = $row2['answer'];
$correct = $row2['correct'];
$answers .= '<label style="cursor:pointer;"><input type="checkbox" name="rads" value="'.$correct.'">'.$answer.'</label>
<input type="hidden" id="qid" value="'.$id.'" name="qid"><br /><br />
';
}
$output = ''.$q.','.$answers.',<span id="btnSpan"><button onclick="post_answer()">Submit</button></span>';
echo $output;
}
}
?>
quiz.php
<?php
session_start();
if(isset($_GET['question'])){
$question = preg_replace('/[^0-9]/', "", $_GET['question']);
$next = $question + 1;
$prev = $question - 1;
if(!isset($_SESSION['qid_array']) && $question != 1){
$msg = "Sorry! No cheating.";
header("location: index.php?msg=$msg");
exit();
}
if(isset($_SESSION['qid_array']) && in_array($question, $_SESSION['qid_array'])){
$msg = "Sorry, Cheating is not allowed. You will now have to start over. Haha.";
unset($_SESSION['answer_array']);
unset($_SESSION['qid_array']);
session_destroy();
header("location: index.php?msg=$msg");
exit();
}
if(isset($_SESSION['lastQuestion']) && $_SESSION['lastQuestion'] != $prev){
$msg = "Sorry, Cheating is not allowed. You will now have to start over. Haha.";
unset($_SESSION['answer_array']);
unset($_SESSION['qid_array']);
session_destroy();
header("location: index.php?msg=$msg");
exit();
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Quiz Page</title>
<script type="text/javascript">
function countDown(secs,elem) {
var element = document.getElementById(elem);
element.innerHTML = "You have "+secs+" seconds remaining.";
if(secs < 1) {
var xhr = new XMLHttpRequest();
var url = "userAnswers.php";
var vars = "checkbox=0"+"&qid="+<?php echo $question; ?>;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert("You did not answer the question in the allotted time. It will be marked as incorrect.");
clearTimeout(timer);
}
}
xhr.send(vars);
document.getElementById('counter_status').innerHTML = "";
document.getElementById('btnSpan').innerHTML = '<h2>Times Up!</h2>';
document.getElementById('btnSpan').innerHTML += 'Click here now';
}
secs--;
var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000);
}
</script>
<script>
function getQuestion(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function(){
if (hr.readyState==4 && hr.status==200){
var response = hr.responseText.split("|");
if(response[0] == "finished"){
document.getElementById('status').innerHTML = response[1];
}
var nums = hr.responseText.split(",");
document.getElementById('question').innerHTML = nums[0];
document.getElementById('answers').innerHTML = nums[1];
document.getElementById('answers').innerHTML += nums[2];
}
}
hr.open("GET", "questions.php?question=" + <?php echo $question; ?>, true);
hr.send();
}
function x() {
var rads = document.getElementsByName("rads");
for ( var i = 0; i < rads.length; i++ ) {
if ( rads[i].checked ){
var val = rads[i].value;
return val;
}
}
}
function post_answer(){
var p = new XMLHttpRequest();
var id = document.getElementById('qid').value;
var url = "userAnswers.php";
var vars = "qid="+id+"&checkbox="+x();
p.open("POST", url, true);
p.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
p.onreadystatechange = function() {
if(p.readyState == 4 && p.status == 200) {
document.getElementById("status").innerHTML = '';
alert("Thanks, Your answer was submitted"+ p.responseText);
var url = 'quiz.php?question=<?php echo $next; ?>';
window.location = url;
}
}
p.send(vars);
document.getElementById("status").innerHTML = "processing...";
}
</script>
<script>
window.oncontextmenu = function(){
return false;
}
</script>
</head>
<body onLoad="getQuestion()">
<div id="status">
<div id="counter_status"></div>
<div id="question"></div>
<div id="answers"></div>
<div id="status">
<div id="counter_status"></div>
<div id="question"></div>
<div id="answers"></div>
<h1>PONG</h1>
</div>
<script type="text/javascript">countDown(20,"counter_status");</script>
</body>
</html>
SELECT * FROM questions WHERE id='$question'
Seems that you're selecting exactly one question at a time, so there's nothing to sort randomly.
If you want to select a random question, query probably should look like this:
SELECT * FROM questions WHERE 1=1 order by RAND() LIMIT 1
... but that would require rewriting some of related code: for example, you won't need mandatory question get parameter every time.

PHP and AJAX registration form for start page

I am learning to create a social ntwk. I hv used an AJAX framework for the signup page and it wked. Now I am trying to use the same framewk for the start page . Its nt wking. The problems are with the gender conditionals. The submit button does nt click.Hw cn I fix this code so that form submits whn user is either male or female
}
$sql = "SELECT * FROM users WHERE username='$u' AND activated='1' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
// Fetch the user row from the query above
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$gender = $row["gender"];
}
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["f"])){
// CONNECT TO THE DATABASE
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$f = preg_replace('#[^a-z0-9]#i', '', $_POST['f']);
$l = preg_replace('#[^a-z0-9]#i', '', $_POST['l']);
$wt= preg_replace('#[^a-z ]#i', '', $_POST['wt']);
$a= preg_replace('#[^a-z ]#i', '', $_POST['a']);
$ws= preg_replace('#[^a-z ]#i', '', $_POST['ws']);
$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
// FORM DATA ERROR HANDLING
if($f == "" || $l == "" || $wt || $a == "" || $ws || $c == "" ){
echo "The form submission is missing values.";
exit();
} else {
// Add user info into the database table for the main site table
$sql = "UPDATE users SET firstname='$f', lastname ='$l', wagsbooty ='$wt', abs ='$a', wagsboobs ='$ws', crash ='$c' WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
echo "startup_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="style/style.css">
<style type="text/css">
#startupform{
margin-top:24px;
}
#startupform > div {
margin-top: 12px;
}
#startupform > input,select {
width: 200px;
padding: 3px;
background: #F3F9DD;
}
#startupbtn {
font-size:18px;
padding: 12px;
}
</style>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function emptyElement(x){
_(x).innerHTML = "";
}
function startup(){
var f = _("firstname").value;
var l = _("lastname").value;
var wt = _("wagsbooty").value;
var a = _("abs").value;
var ws = _("wagsboobs").value;
var c = _("crash").value;
var status = _("status");
if(f == "" || l == "" wt || a == "" || ws || c == "" ){
status.innerHTML = "Fill out all of the form data";
} else {
_("startupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "start_page1.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "startup_success"){
status.innerHTML = ajax.responseText;
_("startupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("startupform").innerHTML = "OK!";
}
}
}
ajax.send("f="+f+"&l="+l+"&wt="+wt+"&a="+a+"&ws="+ws+"&c="+c);
}
}
</script>
</head>
<body>
<?php include_once("template_pageTop.php"); ?>
<div id="pageMiddle">
<h3>Fill in this form to create your profile!</h3>
<form name="startupform" id="startupform" onsubmit="return false;">
<div>Firstname: </div>
<input id="firstname" type="text" onfocus="emptyElement('status')" maxlength="16">
<br /><br />
<div>Lastname: </div>
<input id="lastname" type="text" onfocus="emptyElement('status')" maxlength="16">
<br /><br />
<div>
<?php
if($gender === 'm'){
echo "WAG with hottest booty :";?></br>
<select id="wagsbooty" onfocus="emptyElement('status')" maxlength="255">
<?php include_once("template_wags_list.php");
}else{
echo "Star with hottest abs:";?></br>
<select id="abs" onfocus="emptyElement('status')" maxlength="255">
<?php include_once("template_abs_list.php");
}
?>
</select>
</div>
</br>
<div>
<?php
if($gender === 'm'){
echo "WAG with hottest boobs :";?></br>
<select id="wagsboobs" onfocus = "emptyElement('status')" maxlength="255">
<?php include_once("template_boobs_list.php");
}else{
echo "I have a crash on :";?></br>
<select id="crash" onfocus ="emptyElement('status')" maxlength="255">
<?php include_once("template_crash_list.php");
}
?>
</div>
</select>
</br>
</br>
<button id="startupbtn" onclick="startup()">Create Profile</button>
<span id="status"></span>
</form>
</div>
<?php include_once("template_pageBottom.php"); ?>
</body>
</html>
You don't have anywhere on the page for the user to select their gender within the page - you should add either a radio button or a select box to the page and pass that info to the startup() function.

Categories