I am trying to register customers for a continuing education web site I am creating and need to add multiple entries to the phpMyAdmin table "users" for registration purposes. I am trying to add multiple entries, 25 total.
As you will see, I have tried the mysqli_multi_query() function to add them all but I cannot create a new record of those entries.
It shows that I am connected to the database and I have checked all values in the code with those in the table and they are ordered. So my questions are:
Is there a limit of entries per table?
Is it best to add few entries at a time than a sign-in page with multiple lines?
Am I trying to do too much in one file and need to split my job?
Error I am getting:
You are connected to the database. Error: INSERT INTO users (myName, home1, home2) VALUES (?, ?, ?);INSERT INTO users (city, ste, zip) VALUES (?, ?, ?);INSERT INTO users (email, certification, experience) VALUES (?, ?, ?);INSERT INTO users (employer, marketing, gender) VALUES (?, ?, ?);INSERT INTO users (dob, recert, full_name) VALUES (?, ?, ?);INSERT INTO users (phone, bHome1, bHome2) VALUES (?, ?, ?);INSERT INTO users (bCity, bState, bZip) VALUES (?, ?, ?);INSERT INTO users (payment, cardNum, expDate) VALUES (?, ?, ?);INSERT INTO users (pwd) VALUES (?);
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?, ?, ?);INSERT INTO users (city, ste, zip) VALUES (?, ?, ?);INSERT INTO users (' at line 1
The code so far validates all entries, checks if there are blank entries, and uses the function test-input. Any help is appreciated, including sources from where to learn PHP that worked better for your education. Thanks in advance and thank you for listening.
<?php
// Defined variables for validation
$myNameErr = $home1Err = $home2Err =$cityErr = $steErr = $zipErr = $emailErr = "";
$certificationErr = $experienceErr = $employerErr = $marketingErr = "";
$genderErr = $dobErr = $recertErr = $full_nameErr = $phoneErr = $bHome1Err = "";
$bHome2Err = $bCityErr = $bStateErr = $bZipErr = $paymentErr = $cardNumErr = "";
$expDateErr = $pwdErr = $pwd2Err = "";
$myName = $home1 = $home2 = $city = $ste = $zip = $email = "";
$certification = $experience = $employer = $marketing = "";
$gender = $dob = $recert = $full_name = $phone = $bHome1 = "";
$bHome2 = $bCity = $bState = $bZip = $payment = $cardNum = "";
$expDate = $pwd = $pwd2 = "";
// Validating fields by checking if fields are empty
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Checks full name
if (empty($_POST['myName'])) {
$myNameErr = "Name required.";
} else {
$myName = test_input($_POST['myName']);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' -.]*$/", $myName)) {
$myNameErr = "Only letters and white space allowed";
}
}
// Checks address
if (empty($_POST['home1'])) {
$home1Err = "Address required.";
} else {
$home1 = test_input($_POST['home1']);
}
// Checks additional address input
if (empty($_POST['home2'])) {
$home2 = test_input($_POST['home2']);
}
// Checks for city
if (empty($_POST['city'])) {
$cityErr = "City is required.";
} else {
$city = test_input($_POST['city']);
}
// Checks for state
if (empty($_POST['ste'])) {
$steErr = "State is required.";
} else {
$ste = test_input($_POST['ste']);
}
// Checks for zipcode
if (empty($_POST['zip'])) {
$zipErr = "Zip code is required.";
} else {
$zip = test_input($_POST['zip']);
}
// Checks for email and if format is correct
if (empty($_POST['email'])) {
$emailErr = "Email is required.";
} else {
$email = test_input($_POST['email']);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
// Confirms the current email
if (empty($_POST['email2'])) {
$email2Err = "Confirm your email.";
} else {
$email2 = test_input($_POST['email2']);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email2Err = "Invalid email format";
}
// Check if emails match
if ($email != $email2) {
$email2Err = "Emails don't match!";
}
}
// Checks for modality certification
if (empty($_POST['certification'])) {
$certificationErr = "Current certification is required.";
} else {
$certification = test_input($_POST['certification']);
}
// Checks for years of experience
if (empty($_POST['experience'])) {
$experienceErr = "Years of experience are required.";
} else {
$experience = test_input($_POST['experience']);
}
// Checks for the current employer
if (empty($_POST['employer'])) {
$employerErr = "Current employer required.";
} else {
$employer = test_input($_POST['employer']);
}
// Input about how they heard about us
if (empty($_POST['marketing'])) {
$marketing = "";
} else {
$marketing = test_input($_POST['marketing']);
}
// Checks for gender
if (empty($_POST['gender'])) {
$genderErr = "Gender required.";
} else {
$gender = test_input($_POST['gender']);
}
// Check the date of birth
if (empty($_POST['dob'])) {
$dobErr = "Date of birth required.";
} else {
$dob = test_input($_POST['dob']);
}
// Checks their end of certification date
if (empty($_POST['recert'])) {
$recertErr = "Recertification date required.";
} else {
$recert = test_input($_POST['recert']);
}
// Checks name as in credit card
if (empty($_POST['full_name'])) {
$full_nameErr = "Name as written in credit card required.";
} else {
$full_name = test_input($_POST['full_name']);
}
// Checks for phone number
if (empty($_POST['phone'])) {
$phoneErr = "Phone number is required.";
} else {
$phone = test_input($_POST['phone']);
}
// Billing Information
// Checks for billing address
if (empty($_POST['bHome1'])) {
$bHome1 = "";
} else {
$bHome1 = test_input($_POST['bHome1']);
}
// Checks for billing address 2
if (empty($_POST['bHome2'])) {
$bHome2 = "";
} else {
$bHome2 = test_input($_POST['bHome2']);
}
// Checks for billing city
if (empty($_POST['bCity'])) {
$bCity = "";
} else {
$bCity = test_input($_POST['bCity']);
}
// Checks for billing state
if (empty($_POST['bState'])) {
$bState = "";
} else {
$bState = test_input($_POST['bState']);
}
// Checks for billing zip code
if (empty($_POST['bZip'])) {
$bZip = "";
} else {
$bZip = test_input($_POST['bZip']);
}
// Checks for payment mode
if (empty($_POST['payment'])) {
$paymentErr = "Mode of payment is required.";
} else {
$payment = test_input($_POST['payment']);
}
// Checks for credit card number
if (empty($_POST['cardNum'])) {
$cardNumErr = "Credit card number required.";
} else {
$cardNum = test_input($_POST['cardNum']);
}
// Checks for expiration date
if (empty($_POST['expDate'])) {
$expDateErr = "Card's expiration date required.";
} else {
$expDate = test_input($_POST['expDate']);
}
// Checks for password
if (empty($_POST['pwd'])) {
$pwdErr = "Password required.";
} else {
$pwd = test_input($_POST['pwd']);
}
// Asks to confirm password and if both match
if (empty($_POST['pwd2'])) {
$pwd2Err = "Confirm your email.";
} else {
$pwd2 = test_input($_POST['pwd2']);
// Check if passwords match
if ($pwd != $pwd2) {
$pwd2Err = "Passwords don't match!";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(isset($_POST['submit'])){
$myName = $_POST['myName'];
$home1 = $_POST['home1'];
$home2 = $_POST['home2'];
$city = $_POST['city'];
$ste = $_POST['ste'];
$zip = $_POST['zip'];
$email = $_POST['email'];
$certification = $_POST['certification'];
$experience = $_POST['experience'];
$employer = $_POST['employer'];
$marketing = $_POST['marketing'];
$gender = $_POST['gender'];
$dob = $_POST['dob'];
$recert = $_POST['recert'];
$full_name = $_POST['full_name'];
$phone = $_POST['phone'];
$bHome1 = $_POST['bHome1'];
$bHome2 = $_POST['bHome2'];
$bCity = $_POST['bCity'];
$bState = $_POST['bState'];
$bZip = $_POST['bZip'];
$payment = $_POST['payment'];
$cardNum = $_POST['cardNum'];
$expDate = $_POST['expDate'];
$pwd = $_POST['pwd'];
// Adding multiple values to database table users
$sql = "INSERT INTO TABLE users (myName, home1, home2) VALUES (?, ?, ?);";
$sql .= "INSERT INTO TABLE users (city, ste, zip) VALUES (?, ?, ?);";
$sql .= "INSERT INTO TABLE users (email, certification, experience) VALUES (?, ?, ?);";
$sql .= "INSERT INTO TABLE users (employer, marketing, gender) VALUES (?, ?, ?);";
$sql .= "INSERT INTO TABLE users (dob, recert, full_name) VALUES (?, ?, ?);";
$sql .= "INSERT INTO TABLE users (phone, bHome1, bHome2) VALUES (?, ?, ?);";
$sql .= "INSERT INTO TABLE users (bCity, bState, bZip) VALUES (?, ?, ?);";
$sql .= "INSERT INTO TABLE users (payment, cardNum, expDate) VALUES (?, ?, ?);";
$sql .= "INSERT INTO TABLE users (pwd) VALUES (?);";
// Trying to save to the database
if (mysqli_multi_query($con, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
$hashPwd = password_hash($pwd, PASSWORD_DEFAULT);
$stmt->bind_param("sssssssssssssssssssssssss", $myName, $home1, $home2, $city, $ste, $zip,
$email, $certification, $experience, $employer, $marketing, $gender, $dob, $recert,
$full_name, $phone, $bHome1, $bHome2, $bCity, $bState, $bZip, $payment, $cardNum,
$expDate, $hashPwd);
mysqli_close($con);
}
Your multi-query is completely wrong. It will create nine new rows, each with a portion of the data for a user, instead of one. You only have one set of data, so you don't need multi_query at all.
You need
// Adding multiple values to database table users
$sql = "INSERT INTO TABLE users (myName, home1, home2, city, ste, zip, email, employer, marketing, gender, certification, experience, dob, recert, full_name, phone, bHome1, bHome2, bCity, bState, bZip, payment, cardNum, expDate, pwd) VALUES (?, ?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
$stmt = $con->prepare($sql);
$hashPwd = password_hash($pwd, PASSWORD_DEFAULT);
$stmt->bind_param("sssssssssssssssssssssssss", $myName, $home1, $home2, $city, $ste, $zip,
$email, $certification, $experience, $employer, $marketing, $gender, $dob, $recert,
$full_name, $phone, $bHome1, $bHome2, $bCity, $bState, $bZip, $payment, $cardNum,
$expDate, $hashPwd);
$result = $stmt->execute();
Tangentially Perpendicular & Rager pointed me in the right direction in the sense that my entries were wrong. Using multi-query (mysqli_multi_query) is the wrong way to do what I needed to do and had nothing to do with adding multiple entries into a table. mysqli_multi_query executes one or multiple queries which are concatenated by a semicolon (https://www.php.net/manual/en/mysqli.multi-query.php).
Yes, you can add as many entries per record as you want (if you want to complicate your life) but simple is better. Finally, the reason I could not get data into the table (besides using multi-query and that my entries were wrong), is that my version of MAMP (in a mac) was running version 7.4 and not PHP 8.0 as in my computer. Once I checked marked version 8 on MAMPs I was able to get my query in the table without any other issues.
You need to prepare your sql, bind the params and then execute. Forget the mysqli functions.
$sql = "INSERT INTO TABLE users (myName, home1, home2, city, ste, zip, email, employer, marketing, gender, certification, experience, dob, recert, full_name, phone, bHome1, bHome2, bCity, bState, bZip, payment, cardNum, expDate, pwd) VALUES (?, ?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
$stmt = $con->prepare($sql);
$hashPwd = password_hash($pwd, PASSWORD_DEFAULT);
$stmt->bind_param("sssssssssssssssssssssssss", $myName, $home1, $home2, $city, $ste, $zip,
$email, $certification, $experience, $employer, $marketing, $gender, $dob, $recert,
$full_name, $phone, $bHome1, $bHome2, $bCity, $bState, $bZip, $payment, $cardNum,
$expDate, $hashPwd);
$stmt->execute();
mysqli_close($con);
You're getting that error because mysql doesn't know what ? is. You are litterally try to execute INSERT INTO users (city, ste, zip) VALUES (?, ?, ?); which is not valid sql. The variables have to be converted first.
Also, this might be a little advanced for you but you can definitely refactor a lot of redundant code out of this... Just practice and you'll get it!
Here's a rough in of what I'm talking about
if ($_SERVER["REQUEST_METHOD"] != "POST") {
//Better to exit on smaller if then wrap everything in if statement.
die();
}
$list = [
'myName' => [ 'type' => 's', 'value' => '', 'err' => 'Name required.'],
'home1' => [ 'type' => 's', 'value' => '', 'err' => 'Address required.'],
'home2' => [ 'type' => 's', 'value' => '', 'err' => '']
// Complete all your entries
];
$hasErr = false;
foreach($list as $key => &$item){
if (empty($_POST[$key])) {
$item['value'] = $item['err'];
} else {
$hasErr = true;
$item['value'] = test_input($_POST[$key]);
switch($key){
case'myName':
if (!preg_match("/^[a-zA-Z-' -.]*$/", $item['value'])) {
$item['value'] = "Only letters and white space allowed";
}
break;
// Add more casses for more special proccessing.
}
}
}
unset($item); //Always unset pointers after loop.
if(!$hasErr){
$sql = "INSERT INTO users(";
$sqlCols = [];
$sqlVals = [];
foreach($list as $key => $item){
$sqlCols[] = $key;
$sqlVals[] = "?";
}
$sql .= implode(",", $sqlCols) . ") values ( " . implode(",", $sqlVals ). " )";
$stmt->prepare($sql);
foreach($list as $key => $item){
// Actually not sure this is possible, worth a shot though.
$stmt->pind_param($item['type'], $item['value']);
}
$stm->execute();
} else{
//Handle error
}
I had created a database which named student with ID, name, mat_number, specialty, age, and gender, in a PHP application.
I do not want the name or mat_number be taken in more than once.
I have done the connection to my database in a different page and called it in the add student page.
This following codes is for a faculty database collection
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if(!empty($name) && !empty($matNo) && !empty($age) &&
!empty($specialty) && !empty($gender))
{
$sql = "INSERT INTO `student`(`name`, `UB_number`, `age`,
`sex`, `specialty`)
VALUES ('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
header("Location: index.php");
}
else{
echo "Error: Complete all records";
}
}
?>
I want to get an error message demanding for a change if the 2 fields already exist in the database.
first name to check in database if already exist the record.
if no record run sql insert command.
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
$sql = "SELECT * FROM `student` WHERE name = "'.$name.'" and UB_number = '".$matNo."'";
$conn->query($sql);
$cnt = $conn->rowCount();
if($cnt == 0){
$sql = "INSERT INTO `student`
(`name`, `UB_number`, `age`,`sex`, `specialty`)
VALUES
('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
header("Location: index.php");
}else{
echo "Error: Complete all records";
}
}
If you would like to insert a new record to DB only if one doesn't exist which has the same name or mat_number then you first need to execute SELECT statement to see if it exists.
Using MySQLi:
<?php
include 'mysqli.php';
$conn = $mysqli;
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if ($name && $matNo && $age && $specialty && !$gender) {
$stmt = $conn->prepare('SELECT 1 FROM student WHERE name=? OR UB_number=?');
$stmt->bind_param('ss', $name, $matNo);
$stmt->execute();
$stmt->bind_result($exists);
$stmt->fetch();
if (!$exists) {
$stmt = $conn->prepare('INSERT INTO `student`(`name`, `UB_number`, `age`, `sex`, `specialty`) VALUES(?,?,?,?,?)');
$stmt->bind_param('sssss', $name, $matNo, $age, $gender, $specialty);
$stmt->execute();
exit(header("Location: index.php"));
} else {
echo 'A record with this name or material number already exists!';
}
} else {
echo "Error: Complete all records";
}
}
Using PDO:
<?php
include 'lib.php';
$conn = $pdo;
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if ($name && $matNo && $age && $specialty && !$gender) {
$stmt = $conn->prepare('SELECT 1 FROM student WHERE name=? OR UB_number=?');
$stmt->execute([$name, $matNo]);
$exists = $stmt->fetchColumn();
if (!$exists) {
$stmt = $conn->prepare('INSERT INTO `student`(`name`, `UB_number`, `age`, `sex`, `specialty`) VALUES(?,?,?,?,?)')
->execute([$name, $matNo, $age, $gender, $specialty]);
exit(header("Location: index.php"));
} else {
echo 'A record with this name or material number already exists!';
}
} else {
echo "Error: Complete all records";
}
}
hope this may be helpfull to you. In here I asume that you are not using any framework. But if you use a framework there are plenty of easy methods to do this.In here I have checked only name field. You should update code as you wants. Also it it better if you could validate your inputs before check. Like trim(). Thanks
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
//after user click the submit button
$sql_Select_Stundets = "SELECT * FROM student WHERE name = '$name' ";
// query the sql with db connection
$result_sql_Select_Stundets = mysqli_query($conn,$sql_Select_Stundets);
//Now check the row count to verify the output if there is any match
$rowcount=mysqli_num_rows($result);
//Now write insert inside if condition
if( $rowcount >0 ) {
if(!empty($name) && !empty($matNo) && !empty($age) &&
!empty($specialty) && !empty($gender)) {
$sql = "INSERT INTO `student`(`name`, `UB_number`, `age`,
`sex`, `specialty`)
VALUES ('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
bheader("Location: index.php");
}else{
echo "Error: Complete all records";
}
}else{
echo "<script>
alert('sorry this name is already available');
</script>";
}
}
?>
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 have seen a few other questions about this problem but I believe mine to be unique. I am processing a form and am relatively new to PHP and PDO so do not have the best debugging skills. I believe that my query's are wrong, as when I press the submit button on my form it just throws up a blank page with no error messages (even though I have error reporting on).
I started writing this in MySqli but then had to scrap it as it was not working and I needed to easily have variables inside my Insert statements. Here is my code
error_reporting(-1);
require 'scripts/PasswordHash.php';
$username = $name = $email = $password = $gender = $age = '';
$query = FALSE;
$dbh = new PDO('mysql:host=localhost;dbname=some_database;charset=utf8', 'some_user', 'some_password');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//Logic
if (empty($_POST['age'])) {
$errors[] = 'Please enter your age';
}
if (empty($_POST['gender'])) {
$errors[] = 'Please select your gender';
}
if ($_POST['password'] != $_POST['passwordRep']) {
$errors[] = 'You did not repeat your password properly';
}
if (empty($_POST['password'])) {
$errors[] = 'Please enter a password';
}
if (empty($_POST['email'])) {
$errors[] = 'Please enter your email in this format : xxxxx#xxx.xxx or xxxxx#xxx.xx.xx';
}
if (empty($_POST['name'])) {
$errors[] = 'Please enter your name';
}
if (check("username", $_POST['username']) == TRUE) {
$errors[] = 'That username already exists';
}
if (check("email", $_POST['email']) == TRUE) {
$errors[] = 'That username already exists';
}
if (empty($_POST['username'])) {
$errors[] = 'Please enter a username';
}
if (empty($errors)) {
$username = trim($_POST['username']);
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$password = PassHash::hash($_POST['password']);
$gender = trim($_POST['gender']);
$age = trim($_POST['age']);
$date = date("Y-m-d H:i:s");
$hash = md5( rand(0,1000) );
insert();
}
}
function insert() {
try {
//connect as appropriate as above
$sql= "INSERT INTO users VALUES(:username, :password, :name, :email, :date, :age, :gender, :hash)";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':date', $date, PDO::PARAM_STR);
$stmt->bindParam(':age', $age, PDO::PARAM_STR);
$stmt->bindParam(':gender', $gender, PDO::PARAM_STR);
$stmt->bindParam(':hash', $hash, PDO::PARAM_STR);
$stmt->execute();
$query = TRUE;
require 'scripts/sendEmailVerify.php';
} catch(PDOException $ex) {
echo "An Error occured!"; //user friendly message
echo ($ex->getMessage());
}
}
function check($field, $input) {
try {
$sql= "SELECT :field FROM users WHERE :field = :input";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':field', $field, PDO::PARAM_STR);
$stmt->bindParam(':input', $input, PDO::PARAM_STR);
$stmt->execute();
$row_count = $stmt->rowCount();
if ($row_count > 0) {
return TRUE;
} else {
return FALSE;
}
} catch(PDOException $ex) {
echo "An Error occured!"; //user friendly message
echo ($ex->getMessage());
}
}
I think it may be that I have the query's happening in functions (although I do not know). I have run this code through PHP code checker (http://phpcodechecker.com/) and it is fine so I don't think it is my syntax! Thanks,
Nick
EDIT: I have located the error thanks to the links about debugging!
I think that you can't use a parameter as a field identifier as you're using in check function.
Trying to handle the input from a check box as a boolean so that I can input the value amongst others into a database. The value is "mailingList" and i thought i had cracked it but it now just returns a pre defined error in my "catch" which should be unrelated. Below is the $_Post from the form
<?php
if (isset($_POST['register'])) {
$email = trim($_POST['email']);
$password = trim($_POST['pwd']);
$retyped = trim($_POST['conf_pwd']);
$firstname = trim($_POST['fname']);
$lastname = trim($_POST['lname']);
$company = trim($_POST['company']);
$mailinglist = trim($_POST['mailingListCheckbox']);
require_once('./includes/register_user_pdo.inc.php');
}
?>
then there is the related register_user_pdo.inc.php
<?php
require_once('./classes/CheckPassword.php');
$errors = array();
if (preg_match('/\s/', $email)) {
$errors[] = 'Email should not contain spaces.';
}
if (!isset($mailingList)) {
$mailingListValue = FALSE;
}
else {
$mailingListValue = TRUE;
}
$checkPwd = new Ps2_CheckPassword($password, 10);
$checkPwd->requireMixedCase();
$checkPwd->requireNumbers(2);
$checkPwd->requireSymbols();
$passwordOK = $checkPwd->check();
if (!$passwordOK) {
$errors = array_merge($errors, $checkPwd->getErrors());
}
if ($password != $retyped) {
$errors[] = "Your passwords don't match.";
}
if (!$errors) {
// include the connection file
require_once('./includes/connection.inc.php');
$conn = dbConnect();
// create a salt using the current timestamp
$salt = time();
// encrypt the password and salt with SHA1
$pwd = sha1($password . $salt);
// prepare SQL statement
$sql = 'INSERT INTO users (email, salt, pwd, lastName, firstName, company, mailingList)
VALUES (:email, :salt, :pwd, :lastName, :firstName, :company, :mailingList)';
$stmt = $conn->prepare($sql);
// bind parameters and insert the details into the database
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':salt', $salt, PDO::PARAM_INT);
$stmt->bindParam(':pwd', $pwd, PDO::PARAM_STR);
$stmt->bindParam(':lastName', $lname, PDO::PARAM_STR);
$stmt->bindParam(':firstName', $fname, PDO::PARAM_STR);
$stmt->bindParam(':company', $company, PDO::PARAM_STR);
$stmt->bindParam(':mailingList', $mailingListValue, PDO::PARAM_BOOL);
try {
$stmt->execute();
// check number of rows affected by previous insert
if ($stmt->rowCount() == 1) {
$success = "$email has been registered. You may now log in.";
}
}catch(PDOException $e){
if ($e->getCode() == 23000)
$errors[] = "Email is already in use. Please use another email address.";
else
$errors[] = 'Sorry, there was a problem with the database.';
}
}
?>
Any help would be much appreciated! Thanks in advance!
In your top segment of code you are defining
$mailinglist = trim($_POST['mailingListCheckbox']);
however in your second segment of code you are referencing
$stmt->bindParam(':mailingList', $mailingListValue, PDO::PARAM_BOOL);
You need to change your first part to
$mailingListValue = ....
EDIT
The above answer is wrong, actually it could be this :-
if (!isset($mailingList)) {
"L" is capitalised
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I have a php script which is supposed to register a user. It was working fine two weeks ago but it stopped working today after making minor changes to an unrelated part of the site. Here is the code:
<?php
$salt="mysecretsalt";
$activationkey = md5(uniqid(rand(), true));
$Firstname = $_POST['firstname'];
$Lastname = $_POST['lastname'];
$Email = $_POST['email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
function asc2hex ($temp) {
$data = "";
$len = strlen($temp);
for ($i=0; $i<$len; $i++) $data.=sprintf("%02x",ord(substr($temp,$i,1)));
return $data;
}
$Email = stripslashes($Email);
$password = stripslashes($password);
$password2 = stripslashes($password2);
$Firstname = stripslashes($Firstname);
$Lastname = stripslashes($Lastname);
$Email = mysql_real_escape_string($Email);
$password = mysql_real_escape_string($password);
$Lastname = mysql_real_escape_string($Lastname);
$password2 = mysql_real_escape_string($password2);
$Firstname = mysql_real_escape_string($Firstname);
$password_length = strlen($password);
if($password_length > 5)
{
$password = sha1(md5($salt.$password));
$password2 = sha1(md5($salt.$password2));
$Firstname = strtolower($Firstname);
$Firstname = ucfirst($Firstname);
$Lastname = strtolower($Lastname);
$Lastname = ucfirst($Lastname);
$Email = strtolower($Email);
if ($password == $password2){
$con = mysql_connect("localhost","root","password");
if (!$con)
{
die('Could not connect. Please Contact Us: ' . mysql_error());
}
mysql_select_db("members", $con);
$email_check = mysql_query("SELECT Email FROM users WHERE Email='$Email'");
$email_count = mysql_num_rows($email_check);
if(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $Email)) {
if ($email_count == '0') {
$Email = mysql_real_escape_string($Email);
$password = mysql_real_escape_string($password);
$Lastname = mysql_real_escape_string($Lastname);
$password2 = mysql_real_escape_string($password2);
$Firstname = mysql_real_escape_string($Firstname);
setcookie("Friendsplash", $activationkey, time()+3600);
mysql_query("INSERT INTO users (Firstname, Lastname, Email, password, activationkey) VALUES ('$Firstname', '$Lastname', '$Email', '$password', '$activationkey' )");
//$to = $Email;
//$subject = "Confirmation of Friendsplash.com Membership.";
//$message = "Welcome to our website! $Firstname $Lastname\r\rThis is a confirmation email regarding your recent request for a membership at Friendsplash.com\r\r
//To activate your account follow this confirmation link:\rhttp://localhost/html/activate.php?$activationkey
//\r\rIf you do not wish to activate this account please disregard this email.";
//$from = "postmaster#localhost";
//$headers = "From:" . $from;
//mail($to,$subject,$message,$headers);
mkdir("./usr/$Email", 0755);
echo "<meta http-equiv='REFRESH' content='0;url=confirmation.html'>";
}
else {
echo "<meta http-equiv='REFRESH' content='0;url=existing_email.html'>";
}
}
else {
echo "Please enter a valid email.<meta http-equiv='REFRESH' content='2;url=register.html'>";
}
}
else {
echo "<meta http-equiv='REFRESH' content='0;url=non-matching_passwords.html'>";
}
}
else {
echo "<meta http-equiv='REFRESH' content='15;url=short_password.html'>"; \\ Always taken here
}
}
}
}
?>
I have tried commenting out this if but it then just takes me to the if above it.
Your problem lies in the fact that you mysql_real_escape_string your data before you connect to the database. mysql_real_escape_string needs an existing database connection to do its job, if there is none, it'll return false. So all your data is false, hence your checks are failing. Read the manual page for details.
You should enable error reporting to catch such problems earlier.
error_reporting(E_ALL);
ini_set('display_errors', true);
Also, you shouldn't check the password length against the escaped value, since this may be significantly different from the value the user has entered.
Also, fail early. Don't have thousands of nested levels of if-else statements, it's unmaintainable. Rather, do something like:
if (!/* some important condition */) {
header('Location: http://example.com/error-page');
exit; // fail here
}
// business as usual