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) ";
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.
First here is my code:
<?php
//establish connection to the database
require("database.php");
try{
// prepare and bind
$stmt = $conn->prepare("INSERT INTO clients (phonenumber, firstname) VALUES (:phonenumber, :firstname)");
$stmt->bindParam(':phonenumber', $phonenumber, PDO::PARAM_STR);
$stmt->bindParam(':firstname', $firstname, PDO::PARAM_STR);
// set parameters and execute
if(isset($_POST['phonenumber'])){ $phonenumber = $_POST['phonenumber']; }
if(isset($_POST['firstname'])){ $firstname = $_POST['firstname']; }
$stmt->execute();
}catch (Exception $e) {
echo "Could not insert data into the database $e";
exit;
}
//my attempt on checking if the data has been successfully entered in the database
$inserted = true;
?>
<h2>The Form</h2>
<hr />
<br />
<form action="" method="post">
Number: <input type="text" name="phonenumber" value="" />
<br /><br />
First Name: <input type="text" name="firstname" value="" />
<br /><br />
<input type="submit" name="submit" value="Submit">
</form>
<br />
<hr />
</body>
</html>
Then I'm attempting to check if the form data has been successfully entered like this:
<?php
if($inserted = true){
echo "THE DATA HAS BEEN SUCCESSFULLY ENTERED IN THE DATABASE";
}
?>
Now as you can see I'm trying to set a variable named $inserted as true when the data is entered so that I can determine if the data has been entered successfully. But for some reason it is NOT working. It keeps giving me an error that $inserted is undefined so I wrapped it with isset() and even though that got rid of the error it however did not check to see if $inserted was set. In other words I always keep getting the echo message that it has been entered successfully even though it has not for some reason.
Help is greatly appreciated, thank you very much.
Instead of using a flag, you could use the ->lastInsertId method to check whether the last insertion was succesful.
<?php
if(isset($_POST['firstname'], $_POST['phonenumber'])) {
require('database.php');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$phonenumber = $_POST['phonenumber'];
$firstname = $_POST['firstname'];
try{
$stmt = $conn->prepare("INSERT INTO clients (phonenumber, firstname) VALUES (:phonenumber, :firstname)");
$stmt->bindParam(':phonenumber', $phonenumber, PDO::PARAM_STR);
$stmt->bindParam(':firstname', $firstname, PDO::PARAM_STR);
$stmt->execute();
}
catch (Exception $e) {
echo "Could not insert data into the database $e";
echo $e->getMessage();
exit;
}
if($conn->lastInsertId() > 0) {
echo 'insertion was made';
}
}
?>
<h2>The Form</h2>
<hr />
<br />
<form action="" method="post">
Number: <input type="text" name="phonenumber" value="" />
<br /><br />
First Name: <input type="text" name="firstname" value="" />
<br /><br />
<input type="submit" name="submit" value="Submit">
</form>
<br />
<hr />
</body>
</html>
Sidenote: You could also use ->rowCount() as well:
if($conn->rowCount() > 0) {
// do your thing
}
I'm new to using PDO's and I'm having trouble with my code. I found out how to insert the user's information into the database but I cannot figure out how to login with the same registered information. Any advice would be great
The registration form
<?php
session_start();
$dbh=new PDO("mysql:host=localhost;dbname=csci409_starter","root","root");
$fields = array(
'first_name'=>'First Name',
'last_name'=>'Last Name',
'email'=>'Email',
'password'=>'Password',
);
//If the form has been submitted, validate it.
if(isset($_POST['submit'])){
//Create an array to hold the values we want to insert.
$values = array();
//For each of the fields we want, check if the field was posted, and if so trim it and use it. Otherwise use NULL.
foreach($fields AS $field=>$label){
//This line is using the ternary operator, it's basically a shorthand if/else assignment.
$values[$field] = isset($_POST[$field]) ? trim($_POST[$field]) : NULL;
}
$errors = array();
/*First and Last Names are required. strlen will return the string's length */
if(!isset($values['first_name']) || !strlen($values['first_name'])){
$errors['first_name'] = 'Please Enter a First Name';
}
if(!isset($values['last_name']) || !strlen($values['last_name'])){
$errors['last_name'] = 'Please Enter a Last Name';
}
//If there are any errors, display the form again. Otherwise, insert the data
if(!count($errors)){
$sql = "INSERT INTO googlereaderreplacement.users (first_name, last_name, email, password)
VALUES (?, ?, ?, ?)";
$stmt = $dbh->prepare($sql);
/* array_values() will pull just the array's values, without the string keys.
The positional placeholder requires a numeric key. */
$result = $stmt->execute(array_values($values));
}
}
?>
<style>
label{
display: block;
margin: 5px 0;
}
.error{
font-weight: bold;
color: #BB0000;
}
</style>
<?php
//If the form was submitted and an insert was attempted, display a message.
if(isset($result)){
if($result){
echo '<b>Successfully Inserted!</b>';
}else{
echo '<b>Unable to Insert</b>';
print '<pre>'.print_r($stmt->errorInfo(), true);
}
}
?>
<h1>Insert Contact</h1>
<form action="register.php" method="post">
First Name: <input type="input" name="first_name" id="first_name" value="" />
<br/>
Last Name: <input type="input" name="last_name" id="last_name" value="" />
<br/>
Email (Username): <input type="text" name="email" id="email" value="" />
<br />
Password: <input type="password" name="password" id="password" value="" />
<br />
Confirm Password: <input type="password" name="password2" id="password2" value="" />
<br />
<input type="submit" value="Register" name="submit" id="submit" />
</form>
<form action="index.php">
<input type="submit" value="Return to Main page">
</form>
The Index Page
<?php
session_start();
if(isset($_SESSION['name'])){
echo 'Welcome back '.$_SESSION['name'], 'Logout';
} else {
echo 'Login<br />
Register';
}
?>
and the login page
<?php
session_start();
$error = NULL;
// form login logic here
if(isset($_POST['submit']))
{
$valid = TRUE;
// form validation goes here
// assumed valid
if($valid)
{
$safe_email = mysql_real_escape_string($_POST['email']);
$safe_password = sha1($_POST['password']);
$sql = "SELECT id, created, first_name, last_name, email, level FROM users WHERE email = '$safe_email' AND password = '$safe_password'";
// echo $sql;
require_once "_db_connect.php";
$results = mysql_query($sql, $db);
$row = mysql_fetch_assoc($results);
// echo '<pre>';
// print_r($row);
// echo '</pre>';
$_SESSION['first_name'] = $_SESSION['name'] = $row['first_name'];
$_SESSION['email'] = $row['email'];
$_SESSION['level'] = $row['level'];
$_SESSION['id'] = $row['id'];
header("Location: index.php");
}
}
// look for messages
if(isset($_GET['msg']))
{
switch($_GET['msg'])
{
case 1:
echo '<h2>Please login below!</h2>';
break;
}
}
$title = "Login";
$h1 = "Login Below";
?>
<!-- content -->
<form action="login.php" method="post">
<?php
echo $error;
?>
Email (Username): <input type="text" name="email" id="email" value="" />
<br />
Password: <input type="password" name="password" id="password" value="" />
<br />
<input type="submit" value="Login" name="submit" id="submit" />
</form>
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) ";
OK so my register system is correctly inserting into my database the username, password, and e-mail but not any other fields. I first tried putting the values directly into the SQL query and then put them in the form as hidden text fields. The direct values gave an SQL syntax error and the hidden text doesn't insert anything but successfully adds the user, pass, and email. All MYSQL field types are LONGTEXT. Here's the code.
Register.php
<form name="register" method="post" action="register2.php"><br />
Username<br><input name="username" type="text" size="20" /><br /><br />
Password<br><input name="password" type="password" size="20" /><br /><br />
E-mail<br><input name="email" type="text" size="20" /><br /><br />
<input="hidden" id="status" type="text" value=Waiting for a request size="100" />
<input="hidden" id="request" type="text" value="None sent" size="100" />
<input="hidden" id="paid" type="text" value="Please pay for an instant spot" size="100" />
<input="hidden" id="priority" type="text" value="To be determined by your web designer" size="100" />
<input="hidden" id="files" type="text" value="None" size="100" />
<input="hidden" id="filespass" type="text" value=None" size="100" /><div id="captcha2">
<img id="captcha" src="securimage/securimage_show.php" alt="CAPTCHA Image" /><br><br>Please re-write the security code below<br><input type="text" name="captcha_code" size="10" maxlength="6" size="20"/></div>
<br>
<input type="submit" name="submit" value="Register" /><br><br>
<a href='forgot.php'>Forgot</a> your password?<br>
</form>
Register2.php
<?php
include_once 'securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($_POST['captcha_code']) == false) {
// the code was incorrect
// you should handle the error so that the form processor doesn't continue
// or you can use the following code if there is no validation or you do not know how
echo "The security code entered was incorrect.<br /><br />";
echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
exit;
}else{
$con = mysql_connect(secret);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dylanmediagroup", $con);
$username = htmlspecialchars($_POST['username']);
$password = htmlspecialchars($_POST['password']);
$email = htmlspecialchars($_POST['email']);
$status = htmlspecialchars($_POST['status']);
$priority = htmlspecialchars($_POST['priority']);
$paid = htmlspecialchars($_POST['paid']);
$files = htmlspecialchars($_POST['files']);
$filespass = htmlspecialchars($_POST['filespass']);
$checkuser = mysql_query("SELECT * FROM users WHERE username ='$username'");
$checkemail = mysql_query("SELECT * FROM users WHERE email='$password'");
if(mysql_num_rows($checkuser) > 0 ) { //check if there is already an entry for that username
echo "<img src='http://www.myhealthguardian.com/wp-content/uploads/2010/01/sad-face.gif' width='25%' height='21%'><br><br>Account already registered.<br> <a href='forgot.php'>Forgot</a> your password?<br><br>";
} else {
$sql="INSERT INTO `users` (username, password, email, status, priority, paid, files, filespass) VALUES ('$username', '$password', '$email', '$status', '$priority', '$paid', '$files', '$filespass')";
}
if (!mysql_query($sql,$con))
{
}else{
echo "<img src='http://3.bp.blogspot.com/-vpsc13PCfc0/TaLCGaq2SjI/AAAAAAAACTA/hw2MDzTk6mg/s1600/smiley-face.jpg' height='21%' width='25%'><br><br>Your registration was successful, please <a href='login.php'>login</a> to continue.";
}
}
mysql_close($con)
?>
You're using id instead of name for your hidden inputs.
And please use this syntax:
<input type="hidden" name="name" value="value" />
Also one of your values seem to break the string since it has quotation marks in it.