PHP, AJAX for Signup Form - php

I am trying to set up my first PHP site and I really want to do it the right way. I am working on the form located: http://www.bwgblog.com/signup.
I have set up the following form:
<p><form action="/signup/register.php" method="post">
<label for="first_name">First Name</label>
<input type="text" name="first_name" />
<label for="last_name">Last Name</label>
<input type="text" name="last_name" />
<label for="company">Company</label>
<input type="text" name="company" />
<label for="job_title">Job Title</label>
<input type="text" name="job_title" />
<label for="phone">Phone</label>
<input type="text" name="phone" />
<label for="email">Email</label>
<input type="text" name="email" />
<label for="username">Choose a Username</label>
<input type="text" name="username" />
<label for="password">Choose a Password</label>
<input type="text" name="password" />
<label for="confirm_password">Confirm Your Password</label>
<input type="text" name="confirm_password" />
<input type="submit" value="Get Started" />
</form>
And here is my PHP page, register.php:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$con = mysql_connect("localhost","*******","******"); //Replace with your actual MySQL DB Username and Password
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("bwgblog", $con); //Replace with your MySQL DB Name
$first_name=mysql_real_escape_string($_POST['first_name']);
$last_name=mysql_real_escape_string($_POST['last_name']);
$company=mysql_real_escape_string($_POST['company']);
$job_title=mysql_real_escape_string($_POST['job_title']);
$phone=mysql_real_escape_string($_POST['phone']);
$email=mysql_real_escape_string($_POST['email']);
$username=mysql_real_escape_string($_POST['username']);
$password=mysql_real_escape_string($_POST['password']);
$confirm_password=mysql_real_escape_string($_POST['confirm_password']);
$sql="INSERT INTO members (first_name,last_name,company,job_title,phone,email,username,password,confirm_password) VALUES ('$first_name','$last_name','$company','$job_title','$phone','$email','$username','$password','$confirm_password')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
echo "The form data was successfully added to your database.";
mysql_close($con);
?>
I am trying to figure out how to add in AJAX such that it gives me two things. 1) The ability for it to check in realtime the username field as that field should be unique, and 2) the ability to have the confirm password field render a green checkmark if it == password field.
I have been looking all day for how to do this and can't get a clear look at it. Here is how the files are laid out:
signup (folder)
-> index.php
-> register.html.php
-> register.php

1) AJAX doesn't require the backend to be anything special - so the simplest solution there may be to have a 'usercheck.php' file that queries the DB for the username passed, then returns some form of true/false. You'll probably want to reply using JSON (this is easy if you have PHP 5 - see json_encode).
Regarding the AJAX frontend you'll find it easiest if you use an existing framework (I've used Mochikit and prototype, both seem fine) of which there are several. This should allow you to load the server's response easily.
If you have the AJAX use GET rather than POST (this is simpler) then you can test the response by just viewing the page with the appropriate query string. In any case using Firebug will allow you to view the calls in realtime.
2) There is no need to have the password check AJAX - that can be done simply using plain JavaScript: simply compare the .value properties of the two inputs.

Agreed with PeterJCLaw on all accounts except the choice of javascript framework. Here is how you could do it with jQuery:
// give the form an ID to use a better selector: ie: $('#myform')
// intercept form submit
$('form').submit(function(){
// check if passwords match; you might want to do more thorough validation
if($('input[name=password]').val()==$('input[name=confirm_password]').val()){
// make ajax post request and store the response in "response" variable
$.post('/signup/register.php', $(this).serialize(), function(response){
// process response here (assume JSON object has boolean property "ok"
if(response.ok==true){
// sweet, it worked!
alert('OK!');
}else{
// handle error
alert('Ooops');
}
}, 'json');
// stop the form from being submitted
return false;
}else{
// for the sake of simplicity
alert('Passwords don't match!);
}
});

Look at Jquery's validate extension.
It will simplify all of this. Checking remote values is simple too.
A relatively recent post on this with example code.
You can upload Jquery to your server, or google code hosts them. Using the google version greatly increases the chance that your customers will have already downloaded it also and can use their cached copy.

$fields = array('first_name','last_name','company','job_title','phone','email','username','password','confirm_password');
$dbfields = array(); $dbdata = array(); $dbfieldq = array(); $types = ''; //Setting Variable
foreach ($fields as $field){ //For Each Field
if (!isset($_POST[$field]){ header('Location: signup.php'); die('Please Fill in all fields, they are required'); } //Missing Field Error -- Doublecheck on serverside
array_push($dbdata, strip_tags($_POST[$field])); //Add Data - MySQLi Prepared Statements don't need to be escaped
array_push($dbfields,$field); //Add a field
array_push($dbfieldq,'?'); //Add a ?
$types += 's'; //Add a field type (string for all of these)
}
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db'); //Connect
if ($mysqli->connect_error) { //If there is a connect Error
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$names = explode($dbfields); //Explode the Field Names
$questions = explode($dbfieldq); //Explode the ?
$stmt = $mysqli->prepare("INSERT INTO DBName ($names) VALUES ($questions)");
$params = $this->paramValues;
array_unshift($dbdata, implode($this->paramTypes);
call_user_func_array( array( $stmt, 'bind_param' ), $params);
$stmt->bind_param($types, $code, $language, $official, $percent);
$stmt->execute();
$mysqli->close();
A better way to do the php... Use prepared statements and loops to prepare the variables.

Related

Repurposed PHP/MySQL CRUD code that used to work no longer works

I'm an occasional PHP/MySQL hobbyist, meaning every couple of years I get an idea for a simple CRUD project and try to execute it. This last happened in Oct 2018. Yesterday I started another CRUD project, hoping to repurpose some old code. But my INSERT commands are not working. The code is literally taken from an old live site I had that worked perfectly.
I've spent an entire day googling and there's a lot of old stuff out there. I did the usual, turning on PHP errors and echoing out my variables (which turn up empty). I know I'm connecting to my database because I echoed out a success message. Not really looking for anyone to solve my problem for me, but rather to tell me, yeah things have change and you need to check out X source.
Here's a stripped down version of my code. Has PHP/MySQL CRUD syntax changed since 2018?
// Connect to database
require_once "mysqli-connect.php";
$mysqli = dbConnect('dbname');
// Define variables and initialize with empty values
$fname = $lname = "";
// Process the form
if(isset($_POST['submit'])) {
// Set first name
$fname = trim($_POST['fname']);
// Set last name
$lname = trim($_POST['lname']);
// Prepare an insert statement
$query = "INSERT INTO test_table (fname, lname) VALUES (?, ?)";
if ($stmt = $mysqli->prepare($query)) {
// Bind variables to the prepared statement as parameters
$stmt->bind_param("ss", $param_fname, $param_lname);
// Set parameters
$param_fname = $fname;
$param_lname = $lname;
// Attempt to execute the prepared statement
if($stmt->execute()){
// Get last inserted id
$last_id = mysqli_insert_id($mysqli);
// Redirect to photo upload page
?>
<script type="text/javascript">
window.location = 'upload_image.php'; // This does NOT redirect like it should
</script>
<?php
exit;
} // End execute
} // End prepare
// Close statement
$stmt->close();
} // End process form
// Close connection
$mysqli->close();
?>
<form class="needs-validation" novalidate action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<label for="fname">*First name</label>
<input type="text" class="form-control" name="fname" value="<?php echo $fname; ?>" maxlength="20" autofocus required>
<div class="invalid-feedback">
Valid first name is required.
</div>
<label for="lname">*Last name</label>
<input type="text" class="form-control" name="lname" value="<?php echo $lname; ?>" maxlength="20" required>
<div class="invalid-feedback">
Valid last name is required.
</div>
<input type="submit" class="btn btn-submit btn-block" value="Continue">
</form>
I literally pasted "$_POST['submit']" in a google search and the first result said
isset( $_POST['submit'] ) : This line checks if the form is submitted using the isset() function, but works only if the form input type submit has a name attribute (name="submit")
All it took to fix this was adding name="submit" to my input type. I didn't have that in the original file from 2018. Weird.
EDIT: This worked in my test table, but not my real table. Turns out MySQL doesn't like table names with underscores. While they are perfectly valid characters, apparently there's no guarantee they'll always work. Once I removed the underscores, everything worked fine. Took a long time just adding, removing and changing things one at a time.

My HTML form is not posting to my database, is there something wrong with my php?

I am trying to get my HTML form to post to my data base but I get nothing. I am not bothered about the security side of things at the moment I would just like it functional. I have looked all over the web for a solution and at most of the similar problems on here. I am probably just missing something stupid.
HTML
<form action="booking.php" id="booking" name="booking" method="post">
Let us know what you would like and when and we will get back to you
to confirm<br>
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br>
<label for="email">Email:</label>
<input type="email" name="email" id="email" required>`
PHP
<?php
define('db_database', 'database');
define('db_user_name', 'username');
define('db_password', 'password');
define('db_server_name', 'server');
$dbconnect = mysqli_connect(db_server_name, db_user_name, db_password,
db_database);
if (!$dbconnect) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected!';
$db_selected = mysqli_select_db($dbconnect, db_database);
$name = $_POST['name'];
$mysqli = "INSERT INTO booking (name) VALUES ($name)";
?>
MySQL returned an empty result set (i.e. zero rows). (Query took 0.0004 seconds.)
Make sure that the name attribute in the input tag from your name is defined as name like: <input type="text" name="name"> Without this you can't access. Check if you get the value of the submitted form like: echo $_POST["name"]
I would recommend to get the $name variable in the SQL-Query like this: INSERT INTO booking (name) VALUES ('$name')
If it's not working after all, try to execute the query like this:
$result = mysqli_query($dbconnect, $mysqli);
(instead of your $db_selected part)
I hope I can help.

Trying to save result from PHP function in MySQL

I've created a simple customer signup form (signup.html) to capture 3 fields (email, subdomain and plan).
I also want to assign them a random password, I've lifted the code to generate this from this SO article (Generating a random password in php).
My PHP code (insert.php) is saving the form data fine into MySQL, but not the result from the randomPassword function, where it places "()" in the field instead of the randomly generated password I am hoping for.
I gather I'm not calling the result from the randomPassword() function properly. What am I doing wrong here?
SIGNUP.HTML
<form action="insert.php" method="post" class="inline-form">
<div class="form-group">
<label for="email">Your email address</label>
<input type="email" name="email" class="form-control input-lg" id="email" placeholder="Enter email">
</div><br><br>
<label>Select your plan</label><br>
<div class="radio">
<label>
<input type="radio" name="plan" id="plan" value="optionA" checked>
Option A
</label>
</div><br>
<div class="radio">
<label>
<input type="radio" name="plan" id="plan" value="optionB">
Option B
</label><br><br>
</div>
<div class="form-group">
<label for="subdomain">Pick your subdomain
</label>
<input type="text" name ="subdomain" class="form-control input-lg" id="subdomain">
</div>
<br><br>
<button type="submit" class="btn btn-teal" name="Sign Up">Sign me up!</button>
</form>
INSERT.PHP
<?php
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function randomPassword() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
return implode($pass); //turn the array into a string
}
$sql="INSERT INTO accounts (email, plan, subdomain, password)
VALUES
('$_POST[email]','$_POST[plan]','$_POST[subdomain]','$randomPassword()')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
It doesn't look like you assign a variable to contain the password at all. Functions don't just execute on their own. Use the following:
$myPass=randomPassword();
$sql="INSERT INTO accounts (email, plan, subdomain, password)
VALUES
('$_POST[email]','$_POST[plan]','$_POST[subdomain]','$myPass')";
A function on it's own is just sitting there WAITING to be executed, but doesn't fire off on it's own. In this case, the function returns a value (the password it makes). To actually get it, you write code like $myPass=randomPassword(); which then executes the function and the value is passed into the variable.
As you don't appear to be a veteran, I will expand some more. If you aren't sure why to have a function rather than just execute the code in the first place, a function can be used over and over. Lets say I did the following:
$myPass1=randomPassword();
$myPass2=randomPassword();
With that one function I now have two totally different passwords stored in the variables. You can do all sorts of other fancy things, but think of a function as a snippet of code that is to be re-used within your code, hopefully on a number of occasions - without the need to have it written many times.
Perhaps this would work
$sql="INSERT INTO accounts (email, plan, subdomain, password)
VALUES ('$_POST[email]','$_POST[plan]','$_POST[subdomain]','randomPassword()')";

PHP form post to MySQL error

I'm creating a php-post form, containing: Who, What, Where, Contact and date_created.
I've made a database with these rows.
Here's my HTML Form code:
<form id="contactform" action="post.php">
<p class="contact"><label for="who">Who</label></p>
<input id="who" name="who" placeholder="Who are you? (First & Second name)" required="" tabindex="1" type="text">
<p class="contact"><label for="email">What</label></p>
<input id="what" name="what" placeholder="What do you want?" required="" type="text">
<p class="contact"><label for="username">Where</label></p>
<input id="where" name="where" placeholder="Country, City, Street..." required="" tabindex="2" type="text">
<p class="contact"><label for="password">Contact</label></p>
<input type="text" id="contact" name="contact" placeholder="Phone number or email"required="">
<br><br>
<input class="buttom" name="submit" id="submit" tabindex="5" value="Submit" type="submit">
And here's the php post.php code:
<?php
// Grab our POSTed form values
// Note that whatever is enclosed by $_POST[""] matches the form input elements
$who = $_POST["who"];
$what = $_POST["what"];
$where = $_POST["where"];
$contact = $_POST["contact"];
// Connect to our DB with mysql_connect(<server>, <username>, <password>)
$sql_connection = mysql_connect("server_name", "admin", "password");
mysql_select_db("database_name", $sql_connection);
$sql = "INSERT INTO content (
who,
what,
where,
contact,
date_created
)
VALUES (
'$who',
'$what',
'$where',
'$contact',
NOW()
)";
mysql_query($sql, $sql_connection);
mysql_close($sql_connection);
?>
When I try to post something, nothing is happening. The screen is just white, the database is empty and the url is like this:
http://my-website.com/post.php?who=Firstname+Secondname&what=Some+sentences+here-and&where=America&contact=some#website.com&submit=Submit%21
Just as HamZa DzCyberDeV said, you didn't specify which method you're using in <form> tag.
For situations when you're POSTing something in your database, just as you are now - use method="post" and for forms when you're searching for something, use method="get".
In case of using post method, your URL will change to only my-website.com/post.php and in case of using get method, your URL will change to something like my-website.com/post.php?... (where your things which you're getting are going) - just how you got URL after submitting.
The screen is just white because post.php (where you're going after clicking on submit button) doesn't contain anything to send to output, which you can easily do with echo.
For instance, you can make a new html page which will be written down with echo:
echo '
<html
<body>
This is my website!
</body>
</html>
';
Also, what you could do is to use include() php script which has already formed HTML, or you can check out here for some other redirect methods:
http://php.about.com/od/learnphp/ht/phpredirection.htm
Just remember that PHP is language which server is processing and only HTML tags (with CSS and JS) are sent to other browser to be read.
For more about POST and GET method you can read here:
http://php.net/manual/en/reserved.variables.post.php
http://php.net/manual/en/reserved.variables.get.php
why don't you try this to get an error or a clue to what is going wrong, enclose your code in try and catch blocks:
try {
// your code
} catch ( Exception $e ) {
echo $e->getMessage();
}

Saving to MySQL database via html forms

I am making a php page that retrieves data from a database table and putting it in a table for the user to see via MySQLi commands.
I was wondering how I should approach the reverse situation. I want the user to be able to enter in information into textboxes and the click a button at the bottom of the page called 'save' which will prompt the user "are you sure" before saving to the database. If the user clicks 'yes', then the new entry is inserted into the database.
I have the following code to create the labels and textboxes:
<FORM>
ID: <input type="text" name="id"><br />
NM: <input type="text" name="nm"><br />
Company: <input type="text" name="company"><br />
Address: <input type="text" name="address"><br />
City: <input type="text" name="city"><br />
Zip: <input type="text" name="zip"><br />
State: <input type="text" name="state"><br />
Phone: <input type="text" name="phone"><br />
Website: <input type="text" name="web_site"><br />
</FORM>
However, when it comes to the 'save' button, I can implement the button just fine, but how would I go about saving the information entered into the database?
My initial thought process was to find the values that the user entered. I'm new to PHP and WEB dev in general, but I need to know how to get the value of the text in the textbox. Would I have to sift all the values through via the PHP Post method?
Once I have the information the user wants to enter, I was thinking maybe MySQLi has an insert function, which I found here, http://php.net/manual/en/mysqli.insert-id.php. Then it's just a quick insert and it's in the database after the user gives the 'yes' at the prompt.
Do I have the right idea in mind? Is there a more efficient way to do this?
Any help is greatly appreciated. I've looked around for problems and solutions similar to the ones related to my scenario but there were none. =(
Thanks!
EDIT:
Here is the code I have on the agentprocess.php that the action form sends the information to:
<?php
$agent_nm = $_POST['nm']; // gather all the variables
$company = $_POST['company'];
$address = $_POST['address'];
$city = $_POST['city'];
$zip = $_POST['zip'];
$state = $_POST['state'];
$phone = $_POST['phone'];
$web_site = $_POST['web_site'];
$batch_id = $_POST['batch_id']; // added batch id
//connect
$conn = new mysqli('local', 'admin', 'pass', 'DB');
if(mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
//generate the query (doesn't add id because id is autoincremented)
$query = "INSERT INTO t_agent VALUES (NULL, " . $agent_nm . ", " . $company . ", " . $address . ", " . $city . ", " . $zip . ", " . $state . ", " . $phone . ", " . $web_site . ", " . $batch_id . ")";
//insert and close.
mysqli_query($conn, $query);
mysqli_close($conn);
Despite the code here, I've queried the table and the new entry is not there. Am I missing something here?
Thanks in advance!
Very simple example, added the label tag to the labels for your input and put it inside of a form.
<form method="post" action="process.php" id="myForm" name="myForm" >
<label for="ID">ID</label>: <input type="text" name="ID" /><br />
<label for="nm">NM:</label> <input type="text" name="nm"><br />
<label for="company">Company:</label> <input type="text" name="company"><br />
<label for="address">Address:</label> <input type="text" name="address"><br />
<label for="city">City</label>: <input type="text" name="city"><br />
<label for="zip">Zip</label>: <input type="text" name="zip"><br />
<label for="state">State</label>: <input type="text" name="state"><br />
<label for="phone">Phone</label>: <input type="text" name="phone"><br />
<label for="web_site">Website</label>: <input type="text" name="web_site"><br />
<input type="submit" name="submit" />// this is your submit button
</form>
On the process.php page
//get your inputs from the form
$ID = $_POST['ID'];
//do the same for each of the text inputs
Then you can use mysqli as you described to insert the values into your database, feel free to comment if you need any help with the mysqli part of the question, I didn't include it here since you had the link posted in the original question.
you need to use forms. yes, using the name attributes in your elements, you sift through $_POST(eg. $_POST['company']) for the values you want to store into the DB. here's an example. Use MYSQLi statements instead of mysql as in the eg.
this is simple yet a little complex task for web development beginers.
So I am going to give you an full example of what you need to do...
To do the SAVE button check the fastest way is to use javascript confirm dialog and if confirmed to submit form with javascript also.
The Mysql insert part is easy, you need to check if there is data that you submited via form in $_REQUSET (this works better than $_POST or $_GET because it catchs it both.) and then to connect to db and do an insert query...
Everything is explained in this example:
http://pastebin.com/thNmsXvn
But please use some template engine like Smarty because doing php, javascript and html in one file without template is awful and long term will give you only problems.
I think that I was very clear in the example I put on pastebin but if you have some questions feel free to ask...
Just to add, I have removed ID from HTML form because the best solution for managing ID's in MySQL is auto increment option, you configure that when you create table and set it to a specific field. Most usually it is ID, and it must be an integer.
You should use PDO functions for PHP/MySQL
id field should be autoincrement
<?php
$host= "xxx";
$username="xxx";
$password="xxx";
$database="xxx ";
// Gets data from URL parameters
$name = $_POST['nm'];
//Repeate for all other parameters
// Opens a connection to a MySQL server
try {
// DBH means "DB Handle"
// MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$host;dbname=$database", $username, $password);
}
catch(PDOException $e) {
echo $e->getMessage();
}
// STH means "Statement Handle"
$STH = $DBH->prepare("INSERT INTO mytable ( id, nm,company,address,city,zip,state,phone,web_site ) values ( NULL,:nm,:company,:address,:city,:zip,:state,:phone,:web_site)");
$STH->bindParam(':name', $name);
//Repeate for all other parameters
$STH->execute();
//# close the connection
$DBH = null;
?>

Categories