Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
<?php
require("config.inc.php");
//if posted data is not empty
if (!empty($_POST)) {
if (empty($_POST['username']) || empty($_POST['password'])) {
// Create some data that will be the JSON response
$response["success"] = 0;
$response["message"] = "Please Enter Both a Username and Password.";
die(json_encode($response));
}
else if (empty($_POST['name']) || empty($_POST['mobilenumber']) || empty($_POST['address']) || empty($_POST['city']) || empty($_POST['state'])) {
// Create some data that will be the JSON response
$response["success"] = 0;
$response["message"] = "Please Enter the required marked ** field.";
die(json_encode($response));
}
else if (strlen($_POST['password']) < 6) {
$response["success"] = 0;
$response["message"] = "Your password should be at least 6 characters.";
die(json_encode($response));
}
else if ($_POST['password'] != $_POST['confirmpassword']){
$response["success"] = 0;
$response["message"] = "Confirm Password is not the same with Password you have entered.";
die(json_encode($response));
}
$query = " SELECT 1 FROM user WHERE email = :email";
$query_params = array(
':email' => $_POST['username']
);
//Now let's make run the query:
try {
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
//fetch is an array of returned data. If any data is returned,
//we know that the username is already in use, so we murder our
//page
$row = $stmt->fetch();
if ($row) {
// For testing, you could use a die and message.
//die("This username is already in use");
//You could comment out the above die and use this one:
$response["success"] = 0;
$response["message"] = "I'm sorry, this username is already in use";
die(json_encode($response));
}
$query = "INSERT INTO user ( name, email, password, mobilenumber, address, city, postcode, state) VALUES ( ;name, :email, :password, :mobilenumber, :address, :city, :postcode, :state) ";
//Again, we need to update our tokens with the actual data:
$query_params = array(
':name' => $_POST['name'],
':email' => $_POST['username'],
':password' => $_POST['password'],
':mobilenumber' => $_POST['mobilenumber'],
':address' => $_POST['address'],
':city' => $_POST['city'],
':postcode' => $_POST['postcode'],
':state' => $_POST['state']
);
//time to run our query, and create the user
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one:
$response["success"] = 0;
$response["message"] = "Database Error2. Please Try Again!";
die(json_encode($response));
}
//If we have made it this far without dying, we have successfully added
//a new user to our database. We could do a few things here, such as
//redirect to the login page. Instead we are going to echo out some
//json data that will be read by the Android application, which will login
//the user (or redirect to a different activity, I'm not sure yet..)
$response["success"] = 1;
$response["message"] = "Username Successfully Added!";
echo json_encode($response);
//for a php webservice you could do a simple redirect and die.
//header("Location: login.php");
//die("Redirecting to login.php");
} else {
?>
<h1>Register</h1>
<form action="register.php" method="post">
Name:<br />
<input type="text" name="name" value="" />
<br /><br />
Email:<br />
<input type="text" name="username" value="" />
<br /><br />
Password:<br />
<input type="password" name="password" value="" />
<br /><br />
Confirm Password:<br />
<input type="password" name="confirmpassword" value="" />
<br /><br />
Mobile Number:<br />
<input type="text" name="mobilenumber" value="" />
<br /><br />
Address:<br />
<input type="text" name="address" value="" />
<br /><br />
City:<br />
<input type="text" name="city" value="" />
<br /><br />
Postcode:<br />
<input type="text" name="postcode" value="" />
<br /><br />
State:<br />
<input type="text" name="state" value="" />
<br /><br />
<input type="submit" value="Register New User" />
</form>
<?php
}
?>
This is the message I got back
{"success":0,"message":"Database Error2. Please Try Again!"}
I dont know what kind of exceptional the program catch... , Anyone help me out please?
It is very much appreciate of you all help.
If needed any else coding i can give it here.
$query = "INSERT INTO user ( name, email, password, mobilenumber, address, city, postcode, state) VALUES ( ;name, :email, :password, :mobilenumber, :address, :city, :postcode, :state) ";
change to
$query = "INSERT INTO user ( name, email, password, mobilenumber, address, city, postcode, state) VALUES ( :name, :email, :password, :mobilenumber, :address, :city, :postcode, :state) ";
Related
I'm creating a user management system. I can edit users. I can create users. I can verify that the email is in the correct format. However, my issue is with verifying if the same email exists in the database. I keep getting this error: Ouch, failed to run query: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicata du champ 'Markr#fun.com' pour la clef 'email'. This code is below. The first being the form that's used store info to the database. The second being the script that's run once the submit button is pressed.
<?php
require("../scripts/connect.php");
if(empty($_SESSION['user']))
{
header("Location: ../hound/login.php");
die("Redirecting to ../hound/login.php");
}
$query_parm = array(
':id' => $_GET['id']
);
$query = "
SELECT
*
FROM users
WHERE
id = :id
";
try
{
$stmt = $db->prepare($query);
$stmt->execute($query_parm);
}
catch (PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
?>
<form action="../scripts/edit_users.php" method="post">
<?php foreach($rows as $row): ?>
Username:<br />
<b><?php echo htmlentities($row['username'], ENT_QUOTES, 'UTF-8'); ?></b>
<br /><br />
<input type="hidden" name="id" value="<?php htmlentities($row['id'], ENT_QUOTES, 'UTF-8'); ?>">
First Name:<br />
<input type="text" name="first_name" value="<?php echo `enter code he htmlentities($row['first_name'], ENT_QUOTES, 'UTF-8'); ?>" />
<br /><br />
Last Name:<br />
<input type="text" name="last_name" value="<?php echo htmlentities ($row['last_name'], ENT_QUOTES, 'UTF-8'); ?>" />
<br /><br />
E-Mail Address:<br />
<input type="text" name="email" value="<?php echo htmlentities($row ['email'],ENT_QUOTES,'UTF-8'); ?>" />
<br /><br />
Password:<br />
<input type="password" name="password" value="" /><br />
<br /><br />
<input type="submit" value="Update User" />
Back<br />
<?php endforeach; ?>
</form>
This is the script that's run when submit is pressed.
<?php
require("common.php");
if(empty($_SESSION['user']))
{
header("Location: ../hound/login.php");
die("Redirecting to ../hound/login.php");
}
if(!empty($_POST))
{
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
die("Please enter a valid email address...");
}
if($_POST['email'] !=$_POST['email'])
{
$query_email = "
SELECT email
from users
where
email = :email
";
$query_goes = array(
':email' => $_POST['email']
);
try
{
$stmt = $db->prepare($query_email);
$result = $stmt->execute($query_goes);
}
catch (PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
if($row)
{
die("That email is already in use...");
}
}
}
$array_value = array(
':email' => $_POST['email'],
':first_name' => $_POST['first_name'],
':last_name' => $_POST['last_name'],
':id' => $_POST['id']
);
$query = "UPDATE users
SET
email = :email,
first_name = :first_name,
last_name = :last_name
WHERE
id = :id
";
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($array_value);
}
catch(PDOException $ex)
{
die("Ouch, failed to run query: " . $ex->getMessage());
}
header("Location: users.php");
die("Redirecting to users.php");
?>
Exactly what are you trying to do here?
if($_POST['email'] !=$_POST['email'])
That's an impossible condition. "If this thing is not itself".
So your check to see if an email address exists NEVER gets executed, then you blindly try to insert it anyways.
As well, this is NOT how you do this sort of check. Even if the code was properly structured, there's NO guarantee that some parallel script won't be able to insert that very same email address in the (short) interval between this script doing its select and then the insert.
You should do an unconditional insert, and check if it succeeded, e.g.
if ($_POST) {
$sql = "INSERT ..."
try {
...execute...
catch (PDOException $e) {
if ($e->getCode() == 1062) // duplicate key violation
... email is a dupe
}
}
}
It is probably due to if($_POST['email'] !=$_POST['email']) line since this will always evaluate to False thus it will not even check if the email already exists in your DB.
I'm currently developing an android application and using PHP/MySQL/JSON for the user registration and the login procedere. Now i want to use bcyrpt for hashing the user data. I am totally new to PHP and read a lot of tutorials for hashing, but i do not found any proper tutorial for my PHP skript which i can use.
I tried the password_hash() function, but it won't work.
Can you please give me advice how i can use bcrypt with my files.
Those are my PHP files:
LOGIN
<?php
require("config.inc.php");
if (!empty($_POST)) {
$query = "
SELECT
id,
username,
password
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
$validated_info = false;
$row = $stmt->fetch();
if ($row) {
if ($_POST['password'] === $row['password']) {
$login_ok = true;
}
}
if ($login_ok) {
$response["success"] = 1;
$response["message"] = "Login successful!";
die(json_encode($response));
} else {
$response["success"] = 0;
$response["message"] = "Invalid Credentials!";
die(json_encode($response));
}
} else {
?>
<h1>Login</h1>
<form action="login.php" method="post">
Username:<br />
<input type="text" name="username" placeholder="username" />
<br /><br />
Password:<br />
<input type="password" name="password" placeholder="password" value="" />
<br /><br />
<input type="submit" value="Login" />
</form>
Register
<?php
}
?>
REGISTER
<?php
require("config.inc.php");
if (!empty($_POST)) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$response["success"] = 0;
$response["message"] = "Please Enter Both a Username and Password.";
die(json_encode($response));
}
$query = " SELECT 1 FROM users WHERE username = :user";
$query_params = array(
':user' => $_POST['username']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
$row = $stmt->fetch();
if ($row) {
$response["success"] = 0;
$response["message"] = "I'm sorry, this username is already in use";
die(json_encode($response));
}
$query = "INSERT INTO users ( username, password ) VALUES ( :user, :pass ) ";
$query_params = array(
':user' => $_POST['username'],
':pass' => $_POST['password']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error2. Please Try Again!";
die(json_encode($response));
}
$response["success"] = 1;
$response["message"] = "Username Successfully Added!";
echo json_encode($response);
} else {
?>
<h1>Register</h1>
<form action="register.php" method="post">
Username:<br />
<input type="text" name="username" value="" />
<br /><br />
Password:<br />
<input type="password" name="password" value="" />
<br /><br />
<input type="submit" value="Register New User" />
</form>
<?php
}
?>
In your register script you should not store the password directly, instead call the password_hash() function and store its result:
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($_POST['password'], PASSWORD_DEFAULT);
In the login script you can get the password-hash from the database as you did, but instead of comparing it with the entered password, you have to call the password_verify() function:
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($_POST['password'], $existingHashFromDb);
I have been trying to figure this out for over two days, I am following a youtube tutorial, with a basic sign in for my Android Application, but before I do that I want to test the .php script.
I am thinking that I should get a success when I press the login button but I am getting Invalid credentials, and I know that the username and password is correct
Below is my login.php script.
require("config.inc.php");
if (!empty($_POST)) {
//gets user's info based off of a username.
$query = "SELECT id, username, passwrd
FROM application_users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
//This will be the variable to determine whether or not the user's information is correct.
//we initialize it as false.
$validated_info = false;
//fetching all the rows from the query
$row = $stmt->fetch();
echo $row;
if ($row) {
//if we encrypted the password, we would unencrypt it here, but in our case we just
//compare the two passwords
if ($_POST['password'] === $row['password']) {
$login_ok = true;
}
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if ($login_ok) {
$response["success"] = 1;
$response["message"] = "Login successful!";
die(json_encode($response));
} else {
$response["success"] = 0;
$response["message"] = "Invalid Credentials!";
die(json_encode($response));
}
} else {
?>
<h1>Login</h1>
<form action="login.php" method="post">
Username:<br />
<input type="text" name="username" placeholder="username" />
<br /><br />
Password:<br />
<input type="password" name="password" placeholder="password" value="" />
<br /><br />
<input type="submit" value="Login" />
</form>
Register
</form>
<?php
}
?>
So when the script loads and I input the values from the remote MYSQL server, the message comes back as invalid credentials.I just want to make sure my login is successful before I head over to the android part, which would be a big todo in itself.
I haven't had the opportunity to test it with a real database, but this should work. You still have to add the require("config.inc.php"); on the top of the file and I've added a custom database connection. I also work with PDO so the queries may look like different than what you've used so far.
<?php
// Database connection
try
{
$db = new PDO('mysql:host=localhost;dbname=mydatabase', 'myusername', 'mypassword');
$db->exec('SET CHARACTER SET UTF8');
}
catch (Exception $e)
{
//Message in case of error when connecting to the database
die('Erreur : ' . $e->getMessage());
}
// *** End database connection
$username = ""; // Initialize value in order to keep its value so the user can still see it in his form
if (isset($_POST['login'])) { // if the "login" button is pressed
$username = $_POST['username']; // retrieve username value from the form
$password = $_POST['password']; // retrieve password value from the form
/*
* If a username is unique then a way to do it is to count how many times
* the couple with this username and this password appears in our database.
*/
$query = $db->prepare("SELECT COUNT(*) userAmount ".
"FROM application_users ".
"WHERE username = $username ".
"AND password = $password;");
$query->execute();
$query->closeCursor();
$resultAmount = $query->fetch();
if ($resultAmount['userAmount'] == 0){ // If the couple username-password is unfound
$message = "Username or password unknown";
} else {
$message("Login successful");
}
}
?>
<h1>Login</h1>
<form action="login.php" method="post">
Username:<br />
<input type="text" name="username" placeholder="username" value="<?php echo($username); ?>" />
<br/><br/>
Password:<br/>
<input type="password" name="password" placeholder="password" value="" />
<br/><br/>
<input type="submit" name="login" value="Login" />
Register
</form>
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I've written this code for a registration page, but I am unable to get insert data into my database using PDO(or doing something incorrectly rather). Here is the registration page code:
<?php
if (empty($_POST)){
?>
<form name="registration" action="register.php" method="POST">
<label for "username">Username: </label>
<input type="text" name="username"/><br />
<label for "password">Password: </label>
<input type="password" name="password"/><br />
<label for "fname">First Name: </label>
<input type="text" name="fname"/><br />
<label for "lname">Last name: </label>
<input type="text" name="lname"/><br />
<label for "email">Email: </label>
<input type="text" name="email"/><br />
<button type="submit">Submit</button>
</form>
<?php
}
else{
$form = $_POST;
$username = $form['username'];
$password = $form['passowrd'];
$fname = $form['fname'];
$lname = $form['lname'];
$email = $form['email'];
$user = 'root';
$pass = 'pdt1848!';
$db = new PDO('mysql:host=localhost;dbname=phpproject', $user, $pass);
$sql = "INSERT INTO users (username, password, fname, lname, email)VALUES(:username, :password, :fname, :lname, :email)";
$query = $db->prepare($sql);
$result = $query->execute(array(':username'=>$username, ':password'=>$password,
':fname'=>$fname, ':lname'=>$lname, ':email'=>$email));
if ($result){
echo "Thanks for registering with us!";
} else {
echo "Sorry, an error occurred while editing the database. Contact the guy who built this garbage.";
};
};
?>
The error is right here, passowrd
$password = $form['passowrd'];
A mere typo.
change it to:
$password = $form['password'];
when one fails, the whole query fails.
Had you error reporting in your code, it would've picked it up right away.
Ways that you can use in the future are a try & catch method, such as:
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
as well as
error_reporting(E_ALL);
ini_set('display_errors', 1);
Links that you can consult for further reading:
PDO
http://www.php.net/manual/en/pdo.error-handling.php
http://www.php.net/manual/en/pdo.errorinfo.php
MySQL
http://www.php.net/manual/en/mysqli.error.php
http://www.php.net/mysqli_error
(more)
http://php.net/manual/en/errorfunc.configuration.php#ini.display-errors
http://php.net/manual/en/errorfunc.configuration.php#ini.display-startup-errors
http://php.net/manual/en/function.error-reporting.php
Passwords
I also noticed that you are storing passwords in plain text. This is not recommended.
Use one of the following:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Other links:
PBKDF2 For PHP
Well I do something like this,
$user = 'your username';
$pass = 'your pass';
$db = new PDO( 'mysql:host=localhost;dbname=your_data_base_name', $user, $pass );
/*Grab Post*/
$form = $_POST;
$username = $form[ 'username' ];
$password = $form[ 'password' ];
$first_name = $form[ 'first_name' ];
$surname = $form[ 'surname' ];
$address = $form[ 'address' ];
$email = $form[ 'email' ];
// Sql
$sql = "INSERT INTO users ( username, password, first_name, surname, address, email ) VALUES ( :username, :password, :first_name, :surname, :address, :email )";
$result = $query->execute( array( ':username'=>$username, ':password'=>$password, ':first_name'=>$first_name, ':surname'=>$surname, ':address'=>$address, ':email'=>$email ) );
if ( $result ){
echo "Thank you. You have been registered";
} else {
echo "Sorry, there has been a problem inserting your details.";
}
In addition I always, enable my error reporting as Tuga suggested. It never fails me.
apart from the typo in the passowrd you should enable exceptions for PDO and use a try and catch statement to catch the exception. Also some other little changes, like structuring the PHP first and removing the odd re-assign of the POST superglobal.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$result = "Thanks for registering with us!";
try{
$db = new PDO('mysql:host=localhost;dbname=phpproject', 'root', 'pdt1848!');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
$sql = "INSERT INTO users (username, password, fname, lname, email)
VALUES(:username, :password, :fname, :lname, :email)";
$query = $db->prepare($sql);
$query->execute(array(':username'=>$_POST['username'],
':password'=>$_POST['password'],
':fname'=>$_POST['fname'],
':lname'=>$_POST['lname'],
':email'=>$_POST['email']));
}catch(PDOException $e){
$result = 'Sorry, an error occurred while editing the database. Contact the guy who built this garbage.';
//or use $e->getMessage(); for the real error
}
echo $result;
}
else{ ?>
<form name="registration" action="register.php" method="POST">
<label for "username">Username: </label>
<input type="text" name="username"/><br />
<label for "password">Password: </label>
<input type="password" name="password"/><br />
<label for "fname">First Name: </label>
<input type="text" name="fname"/><br />
<label for "lname">Last name: </label>
<input type="text" name="lname"/><br />
<label for "email">Email: </label>
<input type="text" name="email"/><br />
<button type="submit">Submit</button>
</form>
<?php } ?>
Also its a very bad idea to store plain-text passwords in your db. ~ Read: Best way to store password in database.
Edit,
Added some validation of your inputs to help you get started, hope it helps. not tested.
<?php
try{
$db = new PDO('mysql:host=localhost;dbname=phpproject', 'root', 'pdt1848!');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}catch(PDOException $e){
die('Sorry, an error occurred while editing the database. Contact the guy who built this garbage.');
//or use $e->getMessage(); for the real error
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
//create empty error array - to fill with errors if any
$error = array();
//validate username
if(empty($_POST['username'])){
$error['username'] = 'Enter a username';
}elseif(strlen($_POST['username']) <= 2){
$error['username'] = 'Username too short > 2 chars';
}else{
//check for existing user
$sql = "SELECT 1
FROM `users`
WHERE username = :username";
$query = $db->prepare($sql);
$query->execute(array(':username' => $_POST['username']));
$result = $query->fetchAll(PDO::FETCH_ASSOC);
if(!empty($result)){
$error['username'] = 'User already exists';
}
}
//validate pass
if(empty($_POST['password'])){
$error['password'] = 'Please enter password';
}elseif(strlen($_POST['password']) < 6){
$error['password'] = 'Password too short, password should be 6 chars or longer';
}
//validate fname
if(empty($_POST['fname'])){
$error['fname'] = 'Please enter your first name';
}
//validate fname
if(empty($_POST['lname'])){
$error['lname'] = 'Please enter your last name';
}
//validate email
if(empty($_POST['email'])){
$error['email'] = 'Please enter your email';
}else{
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$error['email'] = 'Please enter valid email';
}
}
//no errors detected so insert
if(empty($error)){
$sql = "INSERT INTO users (username, password, fname, lname, email)
VALUES(:username, :password, :fname, :lname, :email)";
$query = $db->prepare($sql);
$query->execute(array(':username'=>$_POST['username'],
':password'=>$_POST['password'],
':fname'=>$_POST['fname'],
':lname'=>$_POST['lname'],
':email'=>$_POST['email']));
$result = 'Thanks for registering with us! Click here to login';
}else{
$result = 'Please correct the errors';
}
}?>
<?php echo isset($result) ? $result : null;?>
<form name="registration" action="register.php" method="POST">
<label for "username">Username: <?php echo isset($error['username']) ? $error['username'] : null;?></label>
<input type="text" name="username"/><br />
<label for "password">Password: <?php echo isset($error['password']) ? $error['password'] : null;?></label>
<input type="password" name="password"/><br />
<label for "fname">First Name: <?php echo isset($error['fname']) ? $error['fname'] : null;?></label>
<input type="text" name="fname"/><br />
<label for "lname">Last name: <?php echo isset($error['lname']) ? $error['lname'] : null;?></label>
<input type="text" name="lname"/><br />
<label for "email">Email: <?php echo isset($error['email']) ? $error['email'] : null;?></label>
<input type="text" name="email"/><br />
<button type="submit">Submit</button>
</form>
This is my shipmentrequest.php
<?php
require("config.inc.php");
if (!empty($_POST)) {
if (empty($_POST['name']) || empty($_POST['mobilenumber']) || empty($_POST['address']) || empty($_POST['city']) || empty($_POST['postcode']) || empty($_POST['state'])) {
// Create some data that will be the JSON response
$response["success"] = 0;
$response["message"] = "Please Enter the required marked ** field.";
die(json_encode($response));
}
else if (strlen($_POST['postcode']) < 5 || strlen($_POST['postcode']) >= 6) {
$response["success"] = 0;
$response["message"] = "Your postcode should be only 5 numbers.";
die(json_encode($response));
}
$query = "INSERT INTO shipmentrequest ( name, mobilenumber, address, city, postcode, state) VALUES ( :receivername, :receivermobilenumber, :receiveraddress, :receivercity, :receiverpostcode, :receiverstate) ";
//Again, we need to update our tokens with the actual data:
$query_params = array(
':name' => $_POST['name'],
':mobilenumber' => $_POST['mobilenumber'],
':address' => $_POST['address'],
':city' => $_POST['city'],
':postcode' => $_POST['postcode'],
':state' => $_POST['state']
);
//time to run our query, and create the user
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one:
$response["success"] = 0;
$response["message"] = "Database Error2. Please Try Again!";
die(json_encode($response));
}
//If we have made it this far without dying, we have successfully added
//a new user to our database. We could do a few things here, such as
//redirect to the login page. Instead we are going to echo out some
//json data that will be read by the Android application, which will login
//the user (or redirect to a different activity, I'm not sure yet..)
$response["success"] = 1;
$response["message"] = "Shipping Service Succesfully Requested!";
echo json_encode($response);
//for a php webservice you could do a simple redirect and die.
//header("Location: login.php");
//die("Redirecting to login.php");
} else {
?>
<h1>Shipment Request</h1>
<form action="shipmentrequest.php" method="post">
Name:<br />
<input type="text" name="name" value="" />
<br /><br />
Mobile Number:<br />
<input type="text" name="mobilenumber" value="" />
<br /><br />
Address:<br />
<input type="text" name="address" value="" />
<br /><br />
City:<br />
<input type="text" name="city" value="" />
<br /><br />
Postcode:<br />
<input type="text" name="postcode" value="" />
<br /><br />
State:<br />
<input type="text" name="state" value="" />
<br /><br />
<input type="submit" value="Request Service" />
</form>
<?php
}
?>
I dont know why even I filled up my postcode textfield with 5 numbers only, It will just jump to the exceptional handling which is... Database Error2. Please Try Again! Can anyone tell me why it will go to the catch statement?
Looks like those tokens in $query doesn't match with what you put in $query_params array:
VALUES (:receivername, :receivermobilenumber, :receiveraddress, :receivercity, :receiverpostcode, :receiverstate)
binding parameter name values are not matched.
it should be :name, :mobilenumber, etc instead of :receivername, :receivermobilenumber, etc
$query = "INSERT INTO shipmentrequest ( name, mobilenumber, address, city, postcode, state) VALUES ( :name, :mobilenumber, :address, :city, :postcode, :state) ";