I just finished my first working registration form connected to a database. Actually, it's basically a copy of a tutorial demo # http://jqueryvalidation.org/files/demo/milk/ except I had to add the database stuff.
I still have one minor bug. The form doesn't work unless I delete this code:
// specifying a submitHandler prevents the default submit, good for the demo
submitHandler: function() {
alert("submitted!");
},
It's kind of trivial, but it would be nice if the user could see some sort of "Success" message when they click the Submit button. I didn't want to post all the code, but I have a live page # http://www.govwa.org/test/registration.php
This is the PHP code that I inserted just before the form closing tag:
include('config.php');
$pdo = connect();
// adding new member using PDO with try/catch to escape the exceptions
try {
$sql = "INSERT INTO g1_members (firstname, lastname, username, password, password_confirm, email) VALUES (:firstname, :lastname, :username, :password, :password_confirm, :email)";
$query = $pdo->prepare($sql);
$query->bindParam(':firstname', $_POST['firstname'], PDO::PARAM_STR);
$query->bindParam(':lastname', $_POST['lastname'], PDO::PARAM_STR);
$query->bindParam(':username', $_POST['username'], PDO::PARAM_STR);
$query->bindParam(':password', $_POST['password'], PDO::PARAM_STR);
$query->bindParam(':password_confirm', $_POST['password_confirm'], PDO::PARAM_STR);
$query->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
$query->execute();
} catch (PDOException $e) {
echo 'PDOException : '. $e->getMessage();
}
Does anyone have a hunch what the problem might be? Alternatively, is there another way of displaying a message when someone clicks the Submit button?
The submitHandler replaces the default submit, so the form is never submitted when you add that handler, you have to do it manually.
From the documentation
Callback for handling the actual submit when the form is valid. Gets
the form as the only argument. Replaces the default submit. The right
place to submit a form via Ajax after it is validated.
either remove it, or submit the form once valid in the handler
submitHandler: function(form) {
alert("submitted!");
form.submit()
},
Related
I have a file named reg.php that extends my registration.php for a login system.
The registration is connected with a mysqli database and I have a manual
increase in user id in php instead of autoincrement in mysqli because I could
not make this work.
When I hit the register button, my code is creating two entries in the db and
I dont know why.
<?php
if(isset($_POST["register_user"])){
header('location: login.php');
}
if(isset($_POST["username"])){
$username = mysqli_real_escape_string($db, $_POST['username']);
}
if(isset($_POST["email"])){
$email = mysqli_real_escape_string($db, $_POST['email']);
}
if(isset($_POST["password"])){
$password = mysqli_real_escape_string($db, $_POST['password']);
}
if(isset($_POST["passwordconfirm"])){
$passwordconfirm = mysqli_real_escape_string($db, $_POST['passwordconfirm']);
}
$idcount = mysqli_num_rows(mysqli_query($db, "SELECT id FROM user"));
$regquery = "INSERT INTO user (id, name, email, password) VALUES ('$idcount', '$username', '$email', '$password')";
mysqli_query($db, $regquery);
?>
all I want is one single entry.
There's nothing in the code, in your question, that could insert two rows in your database. My guess it that you call this script twice, probably because your form has two ways of submitting the same data:
The normal way, with the form action attribute.
Through an event, like onSubmit
You've got to stop the former, if the latter is used. Look at the example in the link for 2. It tells you how to stop the form from submitting as well:
// For this example, don't actually submit the form
event.preventDefault();
So if the onSubmit works, it stops the normal form submission, but if it doesn't work, the form is submitted the normal way.
$stmt = $conn->prepare("INSERT INTO chatbox (username, message)
VALUES (:username, :message)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':message', $message);
$username = $_POST['username'];
$message = $_POST['message'];
$stmt->execute();
?>
Where would I put htmlspecialchars() in this situation, please help me?
Nowhere here. Always try to put the "raw" (see below what I mean by "raw") data into your database. Only use htmlspecialchars when you want to show the data from your database.
"raw" as in sanitized and safe for the database, but not touched in a way that it is a certain format (e.g. HTML)
//edit:
So in order to use htmlspecialchars correctly, let's say you echo that message after receiving it from the database like that:
echo htmlspecialchars($message);
I'm trying to recall data from database to post later on
When someone logs in using this code:
function login($email, $password, $mysqli)
{
// Using prepared statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare("SELECT id, username, password, salt, phnumber, realname, age, sex FROM members WHERE email = ? LIMIT 1")) {
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($user_id, $username, $db_password, $salt, $phnumber, $realname, $age, $sex);
$stmt->fetch();
}
}
Then I set variables for email and name using this code:
$realname = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $realname);
$_SESSION['realname'] = $realname;
$email = preg_replace("/\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b/", "", $email);
$_SESSION['email'] = $email;
Then when I recall all the variables using print_r($_SESSION); The email is posted without # or . for example: johnsmithyahoocom and also the name is posted without space like JohnSmith Which is undesirable. How can I make it post the right email form and space between names?
Why are you using preg_replace?
And I would recommend, if you are already using a database, to store only the users ID in the SESSION and fetch the other data from the database, when you need the users Information.
Sorry for wasting your time on this
Everything was going fine I just had to relogin to apply changes I made
/\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b/ is working fine and recalls the right email form from database I just had to restart the SESSION to see changed I made.
I'm trying to learn how to make a registration form. I was getting an error message: "PDOException : SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'firstname' cannot be null"
Someone told me I could fix it with AJAX, which is something I want to learn anyway. But I'm not sure what I'm doing.
First, I took the PHP code out of my main page (register.php) and put it in a new file (reg-code.php). Then I included reg-code.php in register.php.
Next, I put the following in the head section of register.php:
<script>
submitHandler: function(form) {
$.post(
'/test/register/reg-code.php',
$(form).serialize(),
success: function() {
// display success message or something
It works!
}
);
};
</script>
I fixed one syntax error, but I get another one on the line success: function() {
But I'm not even sure if I'm moving in the right direction. The tutorials are confusing.
This is the PHP code I put in a separate file:
try {
$sql = "INSERT INTO members (firstname, lastname, username, password, password_confirm, email, age) VALUES (:firstname, :lastname, :username, :password, :password_confirm, :email, :age)";
$query = $pdo->prepare($sql);
$query->bindParam(':firstname', $_GET['firstname'], PDO::PARAM_STR);
$query->bindParam(':lastname', $_GET['lastname'], PDO::PARAM_STR);
$query->bindParam(':username', $_GET['username'], PDO::PARAM_STR);
$query->bindParam(':password', $_GET['password'], PDO::PARAM_STR);
$query->bindParam(':password_confirm', $_GET['password_confirm'], PDO::PARAM_STR);
$query->bindParam(':email', $_GET['email'], PDO::PARAM_STR);
$query->bindParam(':age', $_GET['age'], PDO::PARAM_STR);
$query->execute();
} catch (PDOException $e) {
echo 'PDOException : '. $e->getMessage();
}
Do I just have to figure out a syntax error, or do I need to go back to square one?
That error message means that the firstname variable is not being passed in properly. Make sure the name/id of your form field is indeed "firstname".
actually there is no problem with your procedure but
In your members table firstname column is not null and you are passing null value to it
If you use jQuery $.post - then in your php-script you should use $_POST variables:
$query->bindParam(':firstname', $_POST['firstname'], PDO::PARAM_STR);
// etc
Also:
success: function() {
// display success message or something
It works! // this string will cause syntax error
}
Use standard alert() function:
success: function() {
// display success message or something
alert('It works!');
}
First of all, Ajax has nothing to do with that error you get! So you might wan't to consider changing your title.
But anyway.
This means that your $_GET['firstname'] doesn't have a value, which means that no input from your registration form is send trough to your code.
And my suggestion would be that you change all you $_GET varibles to $_POST['inputfieldname'].
Because if you are using a form to send the data, you can't access them trough GET, as GET is used to acces data sent via the URL, so let's say you sent something with the url, and the url was www.yoururl.com/sent.php?something=bla
You would get the value from "something" like so $_GET['something'] and that would now have the data "bla", just to clarify.
The reason it says that the column cannot be null, is because that you have set that rule in your database, and if you removed that, i would just be a blank field.
Hope it helps a bit.
When I bind data in my php file to my database. I check by database and the values are all NULL? What is wrong?
Also: How can I pass a hashed password to be stored in my database? I know how to password_hash and password_verify. I can't figure out how to store a hashed password.
/*the variables are declared in a html form in another file. The action attribute
calls this php file with this code here. I use POST to get the user input for
each of the variables first, last, password, and initials*/
//create database connection
$dbc = mysqli_connect ('domain', 'root', 'password', 'database')
or die ('Error connecting');
//my condition to check for value when user enters data from html form. I use POST and isset.
if (isset($_POST['first']) && isset($_POST['last']) && isset($_POST['password']) &&
isset ($_POST['initials'])) {
//This is where I bind the data to prevent sql injection attacks.
$thisdb= mysqli_prepare($dbc, "INSERT INTO database VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssd', $first, $last, $password, $initials);
mysqli_stmt_execute($thisdb);
mysqli_stmt_close($thisdb);
}
else
{ echo('user missing data'); exit();}
// close database
mysqli_close ($dbc);
Use:
mysqli_stmt_bind_param($stmt, 'sssd', $_POST['first'], $_POST['last'], $_POST['password'], $_POST['initials']);
You were binding to variables that you never assigned.
Apart from the undefined variables that are already mentioned, you might run into problems as you are declaring your initials as a double:
mysqli_stmt_bind_param($stmt, 'sssd', $first, $last, $password, $initials);
^ are you sure initials is supposed to be a double?
You probably want:
mysqli_stmt_bind_param($stmt, 'ssss', $_POST['first'], $_POST['last'], $_POST['password'], $_POST['initials']);
You should add error handling to your database to see where what problem occurs exactly.
Note: Storing passwords in plain text is a very bad idea, you need to salt and hash them.