Having trouble with inserting query after program checks username availability using ajax - php

I'm having trouble inserting my query into the database after the program checks the username availability on blur using ajax to check if the username is available for register or not. After it checks the username availability, it always insert some empty queries in my database.
Here is the sample output for more details:
But the problem is when it displays username available it will automatically inserts an empty query into the database.
This will insert into the database after it checks the availability of the user:
I want the insert query to be inserted when the user submits or when he/she clicks the register button. The availability of the username is for checking only. Is there a problem with my code?
Here is the code:
Sample.php FILE
<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<input type="text" placeholder="Username" id="username" name="username" class="form-control" >
<span id="availability" style="color:green;"></span>
<input class="form-control" placeholder="First Name" name="firstname" type="text" >
<input type="submit" id="signup" name="signupsubmit" class="btn btn-info form-control" value="Register">
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
//Check Username availability
$(document).ready(function()
{
$('#username').blur(function()
{
var username = $(this).val();
$.ajax({
url:"SampleProcess.php",
method:"POST",
data:{username:username},
dataType:"text",
success:function(html)
{
$('#availability').html(html);
}
})
});
});
</script>
</html>
I use ajax for checking the username availability inside the script here:
<script>
//Check Username availability
$(document).ready(function()
{
$('#username').blur(function()
{
var username = $(this).val();
$.ajax({
url:"SampleProcess.php",
method:"POST",
data:{username:username},
dataType:"text",
success:function(html)
{
$('#availability').html(html);
}
})
});
});
</script>
The process file for checking username and inserting a query.
SampleProcess.php FILE
<?php
//This is an external file DBController for creating a connection to DB
require_once("DBController.php");
//DBHandler handles the DBController class
$DBHandler = new DBController();
//Call the function mainConnect()
$connect = $DBHandler->mainConnect();
//Check Username Availability
if(isset($_POST["username"]))
{
$sql = "SELECT * FROM tablereminders WHERE username ='".$_POST["username"]."'";
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0 )
{
echo"<span class=\"text-danger\">Username not available</span>";
echo'<script>document.getElementById("username").focus();</script>';
}
else
{
//In this else condition the query will be inserted in the
//database after the user clicks the register button, but it will insert right
//after the program check the availability
echo"<span class=\"text-success\">Username available</span>";
//Problem inserting my query here
$Username = isset($_POST['username']);
$FirstName = isset($_POST['firstname']);
//Query Insert into tablereminders
$query = mysqli_query($connect, "INSERT INTO `tablereminders`(`username` , `firstname`)
VALUES ('$Username' , '$FirstName')");
if($connect->query($query) == TRUE)
{
echo "<script type='text/javascript'>alert('New record created successfully');</script> ";
echo "<script>setTimeout(\"location.href = 'LoginReminder.php'\", 0)</script>";
}
}
}
?>
In the else condition after checking mysqli_num_rows I put my insert query there to perform when the user clicks the register buton. Is there a problem with my if-else condition or is it about the AJAX function inside the Sample.php file, Should I use GET or POST method? Either way I tried it but it doesn't correct my problem here. Please help.

Try this ;)
There are two things
Check username availability.
Submit the form and create a record.
1. Check username availability.
For this, you have done all the code you need to modify code like this:
<?php
//This is an external file DBController for creating a connection to DB
require_once("DBController.php");
//DBHandler handles the DBController class
$DBHandler = new DBController();
//Call the function mainConnect()
$connect = $DBHandler->mainConnect();
//Check Username Availability
if(isset($_POST["username"])){
$sql = "SELECT * FROM tablereminders WHERE username ='" . $_POST["username"] . "'";
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0){
echo '<span class="text-danger">Username not available</span>';
echo '<script>document.getElementById("username").focus();</script>';
}else{
echo '<span class="text-success">Username available</span>';
}
}
2. Submit the form and create a record.
Now create new ajax call to some other file to insert record which submits form data on some button click event.
This you can do same you done in case of username availability.
Code sample to insert record:
$Username = isset($_POST['username']);
$FirstName = isset($_POST['firstname']);
//Query Insert into tablereminders
$query = mysqli_query($connect, "INSERT INTO `tablereminders`(`username` , `firstname`)
VALUES ('$Username' , '$FirstName')");
if($connect->query($query) == TRUE){
echo '<script type="text/javascript">alert("New record created successfully");</script>';
echo '<script>setTimeout(function(){ location.href = "LoginReminder.php"}, 0);</script>';
}
Remember 2 things before inserting new record in database:
Validate user data.
Escape user data may be with this function mysqli_real_escape_string OR you can use prepared statement and bind params.

Related

Check a Promo Code from MYSQL Table on Website

I'm trying to create a system on my HTML website where you can enter a code which then gets checked by a php-file. The php shall compare the code with codes that are in my MYSQL Table. The php shall also check whether the code was allready used or not. After the check is completed a message shall appear on the Website that tells the user if his code is valid or not.
If the Code is valid, it shall inform me somehow that somebody entered a code.
I've wrote some code but when I press the button it's not working at all.Here my HTML code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11/jquery.min.js">
</script>
<script>
$(document).ready(function() {
//the min chars for promo-code
var min_chars = 6;
//result texts
var checking_html = 'Checking...';
//when keyup
$('#code').keyup(function(event){
//run the character number check
if($('#code').val().length == min_chars){
//show the checking_text and run the function to check
$('#Promo_code_status').html(checking_html);
check_code();
}
});
});
//function to check the promo code
function check_code(){
//get code
var code = $('#code').val();
//use ajax to run the check
$.post("check_code.php", { code: code },
function(result){
//if the result is 0
if(result == 0){
//show that the code is correct
$('#Promo_code_status').html(code + ' is correct.');
}else if(result == 1){
//show that the code is correct, but already has been used
$('#Promo_code_status').html(code + ' has allready been used.');
}else{
//show that the code is not correct
$('#Promo_code_status').html(code + ' is not correct.');
}
});
}
</script>
</head>
<body>
<center><h1>Enter Promo Code</h1>
<form method="post" action="check_code.php">
<input type="text" id="code" name="code" maxlength="6" />
<div id="promo_code_status"></div>
<br>
<input type="submit" value="Let's go"></center>
</form>
</body>
</html>
And here you have my PHP File:
<?php
//connect to database
$user = "***"; //Username
$pass = "***"; //Password
$host = "localhost"; //Host
$dbdb = "***"; //Database name
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
//get the code
mysqli_real_escape_string($connect, $_POST['code']);
//mysql query to select field code if it's equal to the code that we checked '
$result = mysqli_query($connect, 'select Code from Codes where Code = "'. $code .'"');
$record = mysqli_fetch_array($result);
//if number of rows fields is bigger them 0 that means the code in the database'
if(mysqli_num_rows($result) > 0){
if($record['used'] == 0) {
//and we send 0 to the ajax request
echo 0;
} else{
//and we send 1 to the ajax request
echo 1;
}
}else{
//else if it's not bigger then 0, then the code is not in the DB'
//and we send 2 to the ajax request
echo 2;
}
?>
By pressing the Button "Let's go" the PHP shall do it's Job and afterwards it shall give the user the information about his code.
What do I have to change?
I thing you not assign the post value in $code, that's reason.
$code = mysqli_real_escape_string($connect, $_POST['code']);
make sure the jquery CDN that you are using can be accessed. because it looks like wrong CDN.
in the checkcode() function, you use #Promo_code_status, P is uppercase, while in html you use promo_code_status with p is lowercase.
in php file you forget to assign values to the $code
I hope this helps

How do I validate this php form?

I have a simple html form that looks like this
<form action="insert.php" method="post">
Name: <input type="text" name="name"><br>
Password: <input type="text" name="pw"><br>
<input type="submit" value="log in">
</form>
What I need to do with this is check the values that are submitted in this form against those in a simple database I have created. The database is name is userdb, and in it I have created a simple table called 'users', with two columns called name and password.
I am able to connect to the database correctly with
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
Now I'm confused with (probably the most important bit) where I have to validate the form against some values in the database.
I have created a name and password entry in phpmyadmin, for name='eric' and password='123456'.
I'm just not sure how to check it using the form?
Is it something like this?
$sql = "INSERT INTO `userdb`.`users` (`name`, `password`) VALUES ($name, $pw);";
$name and $pw are values that I got from the form name attributes.
It tells me I have undefined variables though so obviously I've got it wrong here.
Any help?
*edit here is the full code:
index.php
<html>
<head>
<style>
#main
{
width: 700px;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
<div id="main">
<?php
$name = "";
$pw = "";
?>
<form action="insert.php" method="post">
Name: <input type="text" name="name"><br>
Password: <input type="text" name="pw"><br>
<input type="submit" value="log in">
</form>
</div>
</body>
</html>
insert.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
$con=mysqli_connect("localhost","userdb","","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "you are connnected";
}
$sql = "INSERT INTO `userdb`.`users` (`name`, `password`) VALUES ($name, $pw);";
?>
</body>
</html>
Your POST variables are in the wrong file. Take them out of index.php and place them in insert.php as so:
You're also storing passwords in plain text, which is not recommended. Use PHP's password_hash() function if your PHP version is 5.5. Otherwise, use crypt() or bcrypt()
Sidenote: There is a password compatibility pack available here for the password_* functions.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
$con=mysqli_connect("localhost","userdb","","");
$name=$_POST['name']; // <-- right there
$pw = $_POST['pw']; // <-- right there
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "you are connnected";
}
$sql = "INSERT INTO `userdb`.`users` (`name`, `password`) VALUES ('$name', '$pw')";
?>
</body>
</html>
If you want to check for successful insert, do:
$sql = "INSERT INTO `userdb`.`users` (`name`, `password`) VALUES ('$name', '$pw')";
if (mysqli_query($con,$sql))
{
echo "Database updated successfully";
}
else
{
echo "Error: " . mysqli_error($con);
}
Footnotes:
For added security, change:
$name=$_POST['name']; // <-- right there
$pw = $_POST['pw']; // <-- right there
to:
$name=mysqli_real_escape_string($con,$_POST['name']);
$pw = mysqli_real_escape_string($con,$_POST['pw']);
Login method: (Sidenote: Use the password storage methods shown at the top if possible).
If you want to use it as a login method, you can use something to the effect of:
$con = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die("could not connect");
$user = mysqli_real_escape_string($con,$_POST['name']);
$pass = mysqli_real_escape_string($con,$_POST['pw']);
$query = "SELECT * FROM your_table WHERE name='$user' AND password='$pass'";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_array($result);
if($row["name"]==$user && $row["password"]==$pass){
echo "You are a validated user.";
}
else{
die("Sorry.");
}
$sql="SELECT * FROM userdb WHERE name='$name' LIMIT 1";
Then fetch the result and check if the password is equal to the password you have.
Next thing you want is to return something, and also to actually log the user in do:
$_SESSION['userid'] = $userid;
Or store whatever you want^. Then check if that exists in all your other pages to determine if the user is logged in.
EDIT: Also it seems like it's needed to add - you're not storing your passwords securely, and you're also not sanitizing your strings properly (against SQL injections). Might want to look into that ^_^.
EDIT 2: Oh yeah, for your problems - variables are undefined because you have to get them using $_POST['']. Inside the '', put the name of the variable you're expecting. $_POST['name'] to get the name, for example.
I would recommend you to use the PHP Data Objects handle the data.
I am not quite sure what exactly you want. You want to make a login page or a signup page?
//connect database
$dsn='mysql:dbname=userdb;host=localhost';
$dbu=''; //YOUR DATABASE USERNAME GOES HERE
$dbp=''; //YOUR DATABASE PASSWORD GOES HERE
try {
$dbh=new PDO($dsn,$dbu,$dbp);
} catch (PDOException $e) {
echo 'Connection failed: '. $e->getMessage();
}
if it's a login page, using this:
//check name and password
$sth=$dbh->prepare('SELECT 1 FROM users WHERE name = ? AND password = ?');
$sth->execute(array($_POST["name"], $_POST["pw"]);
$row=$sth->fetchAll(PDO::FETCH_ASSOC);
if (count($row) == 1){
echo "Correct name and password";
} else {
echo "Wrong name or password";
}
if it's a signup page, using this:
//insert name and pass
$sth=$dbh->prepare('INSERT INTO users (name, password) VALUES (?,?)');
$sth->execute(array($_POST["name"], $_POST["pw"]);

Can't get information about username and password from MySQL when doing log in page

I got a assignment to do log in and register page using ajax, php and jQuery. The problem is that when register page passes the information to my MySQL database witch name is users and it includes username, password, fname, lname and email fields, I can't get logged in with the same information.
My code looks like this:
<?php
include_once('db.php');
$username = mysql_real_escape_string ($_POST["username"]);
$password = mysql_real_escape_string (md5($_POST["password"]));
if(empty($username) || empty($password))
echo "Username and Password are mandatory to Login";
else
{
$sql = "SELECT count(*) FROM users WHERE(
username = '$username'
AND
password = '$password')";
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
if($row[0] > 0)
echo "Login Successful";
else
echo "Failed to Login. Please check your Username and Password and try again";
}
?>
and every time I try to log in with the same information that is passed in MySQL I get the "Failed to Login" message. Maybe it's some kind of problem with the server? Can it be? Because code should be fine.
I will include my code for log in page too, maybe it helps:
<html>
<head><title>Login Page</title></head>
<body>
<script type="text/javascript" src="script/jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="script/script.js"></script>
<form id="loginForm" action="login.php" method="POST">
Username: <input type="text" name="username" id="username"/><br/>
Password: <input type="password" name="password" id="password"/><br/>
<button id="submit">Login</button>
</form>
<div id="ackk"></div>
</body>
</html>
script.js
$("button#submit").click( function() {
if( $("#username").val() == "" || $("#password").val() == "" )
$("#ackk").html("Please enter both username and password");
else
$.post( $("#loginForm").attr("action"),
$("#loginForm :input").serializeArray(),
function(data) {
$("#ackk").html(data);
});
$("#loginForm").submit( function() {
return false;
});
});
SOLUTION: Funny thing that posting this problem I thought about one thing, md5 encryption uses 32 characters and when I created a SQL database I selected just 30 chars for password space, I guess that happens when you are new in programming things you never thought you gonna try to program. Although thank you for your fast answers especially #popnoodles I will try to implement that.

How do I show the PHP variable value in the JavaScript pop-up?

I have the following scripts. The user will pass a numerical value e.g. 123 as a parameter in the URL, and the app will load/fetch that value from MySQL and show it in the textarea.
E.g., entering, "example.com/index.php?id=123" in the URL will pull the 123rd record from the database and show it in the textarea. Everything seems to be working, but I want to show the last row/id of the "source" table when the form is submitted. So, instead of showing "Saved!" in the pop-up, it should show something like "124" (or, the last updated row/number).
index.php:
<?php
include('connect-db.php');
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
$id = $_GET['id'];
$result = mysql_query("SELECT content FROM source WHERE id=$id") or die(mysqli_error());
$row = mysql_fetch_array($result);
if($row)
{
$submit_date = date("Ymd");
$content = $row['content'];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit( function () {
$.post(
'submit.php',
$(this).serialize(),
//
// show the last id here!
//
function(data){ alert("Saved!"); }
);
return false;
});
});
</script>
</head>
<body>
<div id="header" >
<form action="submit.php" method="post" id="myform">
<textarea id="editor" name="editor" id="editor"><?php echo $content; ?></textarea>
<br/>
<input type="submit" name="submit" value="Submit" id="submit"/>
</form>
</div>
</body>
</html>
submit.php:
<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = $_SERVER['REMOTE_ADDR'];
if ($content != '') {
//
// Show the variable (last_id) value in the JavaScript above!
//
$last_id = mysql_insert_id();
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
mysql_close($connection);
}
?>
connect-db:
<?php
$server = 'localhost';
$user = 'domdom';
$pass = 'password#123';
$db = 'domdom';
$connection = mysql_connect($server, $user, $pass) or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($db) or die ("Could not connect to database ... \n" . mysql_error ());
?>
Please note that I do not need any advice on PDO or MySQLi, that is not important at this time. However, any suggestions on improving the security/SQL query etc. are welcome. Thanks.
I will try to answer in 2 parts:
[1] PHP side: in the "isset($_GET['id'])" section, just return the content of the text area you want to fill out. Say, in your DB, 123 -> 'Friday'. Just return the String 'Friday'.
[2] Client side: Do not "submit" the form. Call a JS function, and in there, create an XmlHttpRequest, and send the request to the server as an AJAX request. When you get the return value, examine it and populate your HTML textarea.
If you think this method is suitable for you and you need more details, let me know. I do this in many of my sites.

Why is PHP mysql_insert_id() returning zero?

I have the following code. The $last_id is always showing zero. I do have a column in the "source" table that has auto-increment id. What is the problem with this code?
index.php:
<?php
// connect to the database
include('connect-db.php');
$last_id = mysql_insert_id($connection);
$content = "Please type your content here!";
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit( function () {
$.post(
'submit.php',
$(this).serialize(),
function(data){
alert("Your ID: <?php echo $last_id;?>");
}
);
return false;
});
});
</script>
</head>
<body>
<div id="header" >
<form action="submit.php" method="post" id="myform">
<textarea id="editor" name="editor" id="editor"><?php echo $content; ?></textarea>
<br/>
<input type="submit" name="submit" value="Submit" id="submit"/>
</form>
</div>
</body>
</html>
connect-db:
<?php
$server = 'localhost';
$user = 'mumbo';
$pass = 'mumbo123';
$db = 'jumbo';
$connection = mysql_connect($server, $user, $pass)
or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($db)
or die ("Could not connect to database ... \n" . mysql_error ());
?>
submit.php:
<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = $_SERVER['REMOTE_ADDR'];
if ($content != '') {
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
mysql_close($connection);
}
?>
try this as submit.php:
<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = $_SERVER['REMOTE_ADDR'];
if ($content != '') {
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
echo mysql_insert_id();
}
?>
and in the javascript:
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit( function () {
$.post(
'submit.php',
$(this).serialize(),
function(data){
alert("Your ID: " + data);
}
);
return false;
});
});
</script>
This line is computed when the original page loads:
alert("Your ID: <?php echo $last_id;?>");
So it's effectively:
alert("Your ID: 0");
Since all you've done at that point is connect, there is no insert id. I'm not familiar with jquery, but presumably the data parameter to your callback should contain data about the response from submit.php. You need to make submit.php return the ID, then get that data through whatever means in jquery, and display it.
Edit: actually, it looks like what you're doing can't really do what I said, anyhow.
http://api.jquery.com/submit/
You're setting up a handler which is run whenever the form is submitted - however, this is before the submit actually happens, so you can't actually get the ID there. Your options are to use something like XmlHttpRequest to make an asynchronous call, or have this popup on the submit.php page.
First of all do not use mysql, use mysqli or pdo, mysql is a deprecated system and should not be used. It is not secure and can be hacked easily.
Second, mysql_insert_id only works if you call it directly after the insert...
AKA
if ($content != '') {
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
$last_id = mysql_insert_id();
echo $last_id
mysql_close($connection);
then your jquery must say
alert("Your ID: "+data);
The function data that is returned is whatever you echo from your script. Jquery retrieves it in whatever callback variable you set (data) and then you can use it.

Categories