I have a dynamic drop down search bar which searches through the members of a data base inside of a form on my webpage. In order to view this webpage you must log in first. When I built the site on my domain everything works just fine. However when I transferred my files over to a different domain and configed it with an identical database everything works perfect, except my dynamic search in this form. If I type my name (sometime the odd different name with work) in the search everything works fine, but if i type anyone else it seems to stay on the page as it should, but it logs me out and reload the login form on top of everything else including my form I was typing on. I am using jQuery .post() to make the search dynamic. I will provide code below
index.php
<script>
// this is the jQuery function used to post to the search document on key up
function searchUserQ(){
var searchTxt = $("input[name='userSearch']").val();
console.log(searchTxt);
if (searchTxt != '') {
$.post("includes/search.php", {searchVal:searchTxt},
function(output){
$("#userResults").html(output);
});
}
}
</script>
<h1 class="editUser">Edit User</h1>
<form class="editUser" action="index.php" method="post">
<h1>Search For Employee</h1>
<input type="text" name="userSearch" id="userSearch" placeholder="Search For Employee By First Name" onkeyup="searchUserQ();" />
<submit type="submit" />
<div id="userResults">
</div>
</form>
Search.php
<?php
// Connect To Secure Login
$cfgProgDir = '../phpSecurePages/';
include($cfgProgDir . "secure.php");
//These are the includes needed to make the php page run
// this file connects to the database
include("connect.inc.php");
if(isset($_POST['searchVal'])){
// turn that the user searched into a varible
$searchQ = $_POST['searchVal'];
// delete any symbols for security
$searchQ = preg_replace("#[^0-9a-z]#i", "", $searchQ);
$output = "";
$link = "";
$searchArray = array();
$searchIndex = 0;
// Search through these columns inside the main database
$userSearchQuery = mysql_query("SELECT * FROM dealerEmployees WHERE
firstName LIKE '%$searchQ%'
");
// count the number of results
$userCount = mysql_num_rows($userSearchQuery);
if($userCount == 0){
// $output = "There Were No Search Results";
}else{
while($row = mysql_fetch_array($userSearchQuery)){
// define dynamic varibles for each loop iteration
$id = $row['id'];
$firstName = $row['firstName'];
$lastName = $row['lastName'];
$address = $row['address'];
$phone = $row['phone'];
$email = $row['email'];
$password = $row['password'];
$permission = $row['permission'];
$photo = "images/" . $row['profilePhoto'];
$output .= "<li><div class='employeeSearch' style=\"background: url('$photo'); width: 75px; height: 75px\"></div><h6>" . $firstName . "</h6>" . " " . "<h6>" . $lastName . "</h6><a href='#' class='employee' data-firstName='$firstName' data-lastName='$lastName' data-address='$address' data-phone='$phone' data-email='$email' data-password='$password' data-permission='$permission' data-id='$id'>Select Employee</a></li>";
}
}
}
echo $output;
Can you try this?
> "SELECT id, firstName, lastName, address, phone, email, password,
> permission profilePhone FROM dealerEmployees WHERE
> firstName = '".$searchQ."' Limit 1"
Maybe the like condition is giving more than 1 result.
Maybe you could make a select count(id) as id from dealerEmployees where firstName = '".$searchQ."' and check the count with an if clausule. Maybe the problem you have is too many users with the same firstName.
So After some testing i found out what was happening. When the search would load the search results it would change the password variable in the session to the password of the user coming up in the search since both variables had the same name, all I needed to do was change the var name of the password variable in the search results to be different than the sessions password.
Thanks for all the help!!!
Related
I am trying to use jQuery, AJAX, PHP, and MySQL to check if an email entered into a form already exists in a database.
This is my current jQuery code :
$.post('check-email.php', {'suEmail' : $suEmail}, function(data) {
if(data=='exists') {
validForm = false;
$suRememberMeCheckbox.css('top', '70px');
$suRememberMeText.css('top', '68px');
$signUpSubmit.css('top', '102px');
$tosppText.css('top', '115px');
$suBox.css('height', '405px');
$suBox.css('top', '36%');
$errorText.text('The email has been taken.');
return false;
};
});
And this is my PHP code:
<?php include("dbconnect.php") ?>
<?php
$sql = "SELECT email FROM users WHERE email = " .$_POST['suEmail'];
$select = mysqli_query($connection, $sql);
$row = mysqli_fetch_assoc($select);
if (mysqli_num_rows($row) > 0) {
echo "exists";
}
?>
When I go through with the sign up form, when I use an email already in the database, the error text never changes to what I specified, but instead to some other error cases I have coded. Why is this not working! Thanks so much!
Use This Code: Working Perfectly:
<?php
include("dbconnect.php");
$sql = "SELECT email FROM users WHERE email = '" .$_POST['suEmail']."' ";
$select = mysqli_query($connection, $sql);
$row = mysqli_fetch_assoc($select);
if (mysqli_num_rows($select) > 0) {
echo "exists";
}
?>
If its not changing that means you might have a error with your query. Check developer options on your browser under network. There you can see all ajax calls being made. Click on look at the response. Check to see if there was an error with your query.
Also you have to validate the form submission.
Something like.
if($_SERVER['REQUEST_METHOD'] = 'POST')
{
//maybe send a token over with the form to prevent form spoofing
if($_POST['token'] === $_SESSION['token'])
{
// all your code goes in here
// you provably want to check that is a real email also
// check email input against regular expression
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
//if valid email to variable and escape data
$e = sanitizeString($_POST['email']);
}else
{
/// if not a real email to errors array
$reg_errors['email'] = 'Please enter a valid email address!';
}
}
}
You have to use prepare statements in your queries.
Please bear with me; trying my best to learn more Ajax. I am trying to Validate whether the Name of Event field in my form already exists in my table, but only if both were created by the same User. For example, if User 1 already has an event called Event1, the validation would check if there was a duplicate event name ONLY under User1.
I have the following snippet in a PHP/HTML form:
<div>Event Name: </div>
<input type="text" name="eventname" id="eventname" onblur="checkeventname()" onkeyup="restrict('eventname')" size="50" maxlength="75" />
<span id="eventnamestatus"></span>
This is my checkeventname function:
function checkeventname(){
var nameofevent = _("eventname").value;
if(nameofevent != ""){
_("eventnamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "eventcreationpage.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("eventnamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+nameofevent);
}
}
And here is the Ajax I put at the top of the page, which I am having trouble with:
<?php
// Ajax calls this NAME CHECK code to execute
if(isset($_POST["eventnamecheck"])){
include_once("php_includes/db_conx.php");
$eventname = preg_replace('#[^a-z0-9]#i', '', $_POST['eventname']);
$sql = "SELECT id FROM users WHERE eventname='$eventname' && eventcreator='$eventcreator' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$eventname_check = mysqli_num_rows($query);
if ($eventname_check < 1) {
echo '<strong style="color:#009900;">' . $eventname . ' is not a duplicate name</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $eventname . ' is an event name already under your name</strong>';
exit();
}
}
?>
The webpage itself has the user variable carried over (eventcreationpage.php$eventcreator=User1) I am trying to send over the $eventcreator variable, which would be the User in this case, but I'm not quite sure how to do so.
Set
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
to show that this request will send form data. Next, on your server, you may use $_POST["userid"] to get the userid if you specified it via
ajax.send("userid=" + userid);
To send both userid and eventid, you may use
ajax.send("userid=" + userid + "&eventid=" + eventid);
If you get the userid only from PHP, you could render it into script. That would look like this:
ajax.send("userid=<?php echo $eventcreator; ?>&eventid=" + eventid);
which injects the user's name into the string. Make sure it is properly escaped though, if you allow special characters for user names though.
I have here a register HTML form with some elements. I need to validate the elements on server side and client side and I will explain why. For example, in HTML form I have:
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
User name:<input type="text" name="user_name"/><br/>
Email:<input type="text" name="user_email"/><br/>
Password:<input type="text" name="user_password"/><br/>
</form>
I use PHP to check if the email and user already exists in the database. And I can use PHP to identify if the input fields are empty too.
if (isset($_POST['submit']))
{
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$user_password = $_POST['user_password'];
$exists = "";
$sql = "SELECT user_name from users WHERE user_name = '{$user_name}' LIMIT 1";
$stmt = $connection->prepare($sql);
$stmt->execute();
$num = $stmt->rowCount();
if ($num == 1)
{
$exists .= "u";
}
$sql = "SELECT user_email from users WHERE user_email = '{$user_email}' LIMIT 1";
$stmt = $connection->prepare($sql);
$stmt->execute();
$num = $stmt->rowCount();
if ($num == 1)
{
$exists .= "e";
}
if (empty($user_name) || empty($user_email) || empty($user_password))
{
echo "<script>alert('Please fill all input fields to register!');</script>";
}
else if($exists == "u")
{
echo "<script>alert('This user is already registered in our system.');</script>";
}
else if($exists == "e")
{
echo "<script>alert('This email is already registered in our system.');</script>";
}
else if($exists == "ue")
{
echo "<script>alert('This user and this email are already registered in our system.');</script>";
}
else
{
//Here insert the values in database
}
}
Looks perfect, except for one thing: when I click submit the page is refreshed and all the input fields values are cleaned. This is bad because the user will have to enter all informations again because something was wrong. I know that the reason for this is because I am validating the form after sending it with PHP. To overcome this problem I need to validate the fields before sending the form, logically using JavaScript in the client side. But how about the check in the database? I will need to use PHP for that. If I did not have to check the database I could use JavaScript only. I would have to mix the validations with JavaScript and PHP, I think for that I should use AJAX, but do not know how.
Personally I would do the check at the client level (javascript) not in php but hey if you insists try this
if ($_POST["password_user"] != $_POST["confirm_password"])
echo "<script>alert('The entered passwords doesn't match. Try again.');
document.getElementByID('inputPassword').value = $_POST['password_user'];
document.getElementByID('inputConfirmPassword').value = $_POST['confirm_password'];
</script>";
Also update your HTML input to have ids
Password:<font color="red">*</font>
<input id="inputPassword" type="password" name="password_user"/><br/>
Confirm password:<font color="red">*</font>
<input id="inputConfirmPassword" type="password" name="confirm_password"/><br/>
Edit:
Added good AJAX tutorial:
without JQuery
with JQuery (I personally find this easier to use)
Edit2:
Sample code for PHP (server side) that returns a JSON to be fed back to the client (javascript)
<?php
$canLogin = false;
$responseArray = array();
// your logic here
// ....
if ($canLogin)
{
$responseArray["status"] = "Success";
} else
{
//Use the appropriate HTTP header (default 200), this is sometimes missed by developers
http_response_code(404);
$responseArray["status"] = "Error";
}
return json_encode($responseArray);
?>
I can't seem to work this one out. Been a few days and still no progress after re-writing it more times than I can count on my hands.
Here is the Javascript (On same page as html)
Summary: User types text into the input box. That gets sent off to be processed, which then gets sent back and displayed on the screen in the box ID'd as DisplayText on the html page.
<script type="text/javascript">
function SendText() {
if (document.getElementById("Text").innerHTML == "") {
return;
} else
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("DisplayText").innerHTML = xmlhttp.responseText;
}
}
Text = document.getElementById("Text").value;
xmlhttp.open("GET", "php/Test.php?Chat=" + Text, true);
xmlhttp.send();
}
}
</script>
Here is the HTML (Same page as the script)
<div>
<p>
<span id="DisplayText">
TEXT GOES HERE
</span>
</p>
</div>
<form action="" onsubmit="SendText();">
<input type="" name="" id="Text" />
<input type="submit" value="Send" name="Send" />
</form>
The PHP code is here
<?php
session_start();
include ("Connect.php");
$Connection = mysqli_connect("localhost", "root", "", "chatsystem");
$Create = "CREATE TABLE " . $_SESSION["Username"] . "Chat(Username VARCHAR(255), Chat VARCHAR(255))";
////////////////////////////////////////////////////////////////////////////////
$DatabaseExist = $Connection->query("SELECT 1 FROM " . $_SESSION["Username"] . "Chat");
if ($DatabaseExist !== false) {
echo "Database exists";
doSomething();
} else {
echo "Database does not exist";
mysqli_query($Connection, $Create);
doSomething();
}
////////////////////////////////////////////////////////////////////////////////
function doSomething() {
// Get the sent chat
$Input = $_REQUEST["Chat"];
// Insert into the database the new chat sent
mysqli_query($Connection, "INSERT INTO " . $_SESSION["Username"] . "chat (`Username`, `Chat`) VALUES ('$_SESSION[Username], '$Input')");
// Select everything from the database
$Result = $Connection->query("SELECT * FROM " . $_SESSION["Username"] . "Chat");
// Display everything from the database in an orderly fashion
// --
// For the length of the database
// Append to a variable the next table row
// --
while ($Row = $Result->fetch_array()) {
// Make Variable accessable
global $Input;
// Append username to the return value
$Input = $Input . $Row["Username"] . " : ";
// Append chat to the return value
$Input = $Input . $Row["Chat"] . "<br />";
}
}
// Will return the value
echo $Input;
?>
My connection to the Database is fine. I'm using it on other pages that work.
So lets assume that's not the problem. :P
Any help or insight from anyone who knows or can think of something that is wrong, I would be very grateful for.
I'm new to AJAX.
You do a wrong test with
if (document.getElementById("Text").innerHTML == "")
It should be the same way you use to get the text for sending in the AJAX
if (document.getElementById("Text").value == "")
So check its value property and not its innerHTML as input elements do not have html content..
Be careful though because your code is wide-open to SQL injection attacks.
1st : use input's value property instead innerHTML
eg. use
if (document.getElementById("Text").value == "")
instead of
if (document.getElementById("Text").innerHTML == "")
2nd : use return false; at the form's onsubmit event; to prevent current page to be refreshed as you are using ajax. Otherwise the page will get refreshed and it wont display the php page's output,
eg. use
onsubmit="SendText(); return false;"
instead of just
onsubmit="SendText();"
Try AJAX Long Polling technique for chat application. Here is example
http://portal.bluejack.binus.ac.id/tutorials/webchatapplicationusinglong-pollingtechnologywithphpandajax
First, is it possible for when I insert a record onto my mysql table, a page is automatically generated using the new record in some way. EXAMPLE: My column "image" is on autoincrement, so my image names are always numbers. Furthermore, is it possible for when I insert a record, I automatically generate a page with my image name. So basically, I submit record 367, the image name is 367, and my site will automatically generate mysite.com/367? I want to go in more details but you get the point. Is it possible? If not, what's the closest thing possible?
Also, is there someway to automatically update my page periodically. Such as I set it so at 5pm, it'll automatically insert a code. 5:30pm, it'll insert a different code, which I preprogrammed to do. This is useful, for say I'm on vacation but I still want to update my site regularly.
Can you guys point me to any specific tutorial/terminology/methods/programs/codes/anything? All help would be appreciated!
EDIT: Code I have so far (just want to show to Nick)
<html>
<head>
<title>tgh</title>
</head>
<body>
<?php
$objConnect = mysql_connect("localhost","root","") or die(mysql_error());
$objDB = mysql_select_db("thegoodhumor");
$strSQL = "SELECT * FROM gallery";
if (!isset($_GET['Page'])) $_GET['Page']='0';
$objQuery = mysql_query($strSQL);
$Num_Rows = mysql_num_rows($objQuery);
$Per_Page = 16; // Per Page
$Page = $_GET["Page"];
if(!$_GET["Page"])
{
$Page=1;
}
$Prev_Page = $Page-1;
$Next_Page = $Page+1;
$Page_Start = (($Per_Page*$Page)-$Per_Page);
if($Num_Rows<=$Per_Page)
{
$Num_Pages =1;
}
else if(($Num_Rows % $Per_Page)==0)
{
$Num_Pages =($Num_Rows/$Per_Page) ;
}
else
{
$Num_Pages =($Num_Rows/$Per_Page)+1;
$Num_Pages = (int)$Num_Pages;
}
$strSQL .=" order by GalleryID ASC LIMIT $Page_Start , $Per_Page";
$objQuery = mysql_query($strSQL);
$cell = 0;
echo '<table border="1" cellpadding="2" cellspacing="1"><tr>';
while($objResult = mysql_fetch_array($objQuery))
{
if($cell % 4 == 0) {
echo '</tr><tr>';
}
if($cell == 2) {
echo '<td>RESERVED</td>';
} elseif ($cell == 3) {
echo '<td>The other cell</td>';
} else {
echo '<td><img src="https://s3.amazonaws.com/imagetitle/' . $objResult["Picture"] . '" />' .
$objResult["GalleryName"] . '</td>'; }
$cell++;
}
echo '</tr></table>';
?>
<br>
view more:
<?php
if($Prev_Page)
{
echo " <a href='$_SERVER[SCRIPT_NAME]?Page=$Prev_Page'>prev</a> ";
}
{
echo "|";
}
if($Page!=$Num_Pages)
{
echo " <a href ='$_SERVER[SCRIPT_NAME]?Page=$Next_Page'>next</a> ";
}
?>
</body>
</html>
<?php
mysql_close($objConnect);
?>
It sounds like you want a dynamic web page. To make a dymaic webpage I'd suggest using PHP which would interact with the mysql server.
For example, a user would visit 'mysite.com/info.php?image=367' and the php script would get the information 'image=367'. Your PHP script could do a select query against the mysql database 'SELECT paragraph FROM table WHERE image_id = 367' and then write that data out to the user's web browser.
As far as the user is concerned they just visited 'mysite.com/info.php?image=367', but in the background, PHP dynamically created the webpage content after it got that request.
More basic info about dynamic webpages: http://way.clicktracks.com/help/en/pr650/index.html?dynamicwebsiteshowtheywork.htm
Simple Intro to PHP:
http://www.tizag.com/phpT/
http://www.w3schools.com/php/php_intro.asp
Here is a head start I wrote for you, feel free to use it.
<?php
if (!isset($_GET['imageNumber']))
die("You must specify an image number");
$image_requested = mysql_real_escape_string($_GET['imageNumber']); //sanitizes input
$dbhost = 'localhost'; //TODO: Set this to the ip address of your mysql server if it is not on the same machine
$dbuser = 'root'; //TODO: Set the username you use to access your mysql db here
$dbpass = 'password'; //TODO: Set the password you use to access your mysql db here
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'database_name_here'; //TODO: Set the database name here
mysql_select_db($dbname);
$query = "SELECT paragraph FROM table_name WHERE image_id = " . $image_requested; //TODO: Set table_name, column to get, and image_id to the correct column name
$result = mysql_query($query);
$row = mysql_fetch_array($result) or die(mysql_error());
echo "Here is the paragraph of text" . $row['paragraph']; //TODO: Set paragraph to the same column you retrieved 3 lines above.
mysql_close($conn);
?>
As for the second part of your question, it can also be done with PHP
<?php
$specifictime = strtotime("tuesday 3pm");
if (time("now") > $specifictime)
{
echo " its after 3pm on tuesday";
}
else {
echo " not 3pm on tuesday yet";
}
?>