Related
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>";
}
}
?>
I'm a newbie with PHP. I am trying to create a log in /register system for a project, so I am using a login system source code I found which has many functions and features like salted passwords. The system itself works fine, but I am trying to add more fields to my MySQL Table. The system had an array for extra columns, but I think it was resulting in bad mysql syntax so I decided to write out the query myself using the variables, but I am not sure how I can give access to the variables to the function. The variables are in the register.php document, here is the code (all of register.php):
if( isset($_POST['submit']) ){
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$user = $_POST['username'];
$sex = $_POST['sex'];
$country = $_POST['strCountryChoice'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$pass2 = $_POST['pass2'];
$birthdate = $_POST['birthdate'];
$created = date("Y-m-d H:i:s");
//need to add a lot more validation functions.. AKA Check if email exists and username. Password > 5 chars
if( $user=="" || $email=="" || $pass=='' || $pass2=='' || $firstname=='' || $lastname='' || $sex='' || $country='' || $birthdate='' ){
echo "Fields Left Blank","Some Fields were left blank. Please fill up all fields.";
exit;
}
if( !$LS->validEmail($email) ){
echo "E-Mail Is Not Valid", "The E-Mail you gave is not valid";
exit;
}
if( !ctype_alnum($user) ){
echo "Invalid Username", "The Username is not valid. Only ALPHANUMERIC characters are allowed and shouldn't exceed 10 characters.";
exit;
}
if($pass != $pass2){
echo "Passwords Don't Match","The Passwords you entered didn't match";
exit;
}
$createAccount = $LS->register($user, $pass,
array(
"email" => $email,
"name" => $firstname,
"lastname" => $lastname,
"gender" => $sex,
"country" => $country,
"DOB" => $birthdate,
"created" => date("Y-m-d H:i:s") // Just for testing
)
);
if($createAccount === "exists"){
echo "User Exists.";
}elseif($createAccount === true){
echo "Success. Created account.";
}
}
The whole system takes place in another file which has the class. Here is the register function:
public function register( $id, $password, $other = array() ){
if( $this->userExists($id) && (isset($other['email']) && $this->userExists($other['email'])) ){
return "exists";
}else{
$randomSalt = $this->rand_string(20);
$saltedPass = hash('sha256', "{$password}{$this->passwordSalt}{$randomSalt}");
if( count($other) == 0 ){
/* If there is no other fields mentioned, make the default query */
//old query: ("INSERT INTO `{$this->dbtable}` (`username`, `password`, `password_salt`) VALUES(:username, :password, :passwordSalt)");
//new query: ("INSERT INTO `{$this->dbtable}` (`username`, 'email' , `password`, `password_salt` , 'name' , 'lastname' , 'gender' , 'country' , 'DOB') VALUES(:username, :email, :pass, :passwordSalt, :firstname, :lastname, :gender, :country, :DOB)");
$sql = $this->dbh->prepare("INSERT INTO `{$this->dbtable}` (`username`, `password`, `password_salt`) VALUES(:username, :password, :passwordSalt)");
}else{
/* if there are other fields to add value to, make the query and bind values according to it */
//old query: ("INSERT INTO `{$this->dbtable}` (`username`, `password`, `password_salt`, $columns) VALUES(:username, :password, :passwordSalt, :$colVals)");
//new query: ("INSERT INTO `{$this->dbtable}` (`username`, 'email' , `password`, `password_salt` , 'name' , 'lastname' , 'gender' , 'country' , 'DOB') VALUES(:username, :email, :pass, :passwordSalt, :firstname, :lastname, :gender, :country, :DOB)");
$keys = array_keys($other);
$columns = implode(",", $keys);
$colVals = implode(",:", $keys);
//l= $this->dbh->prepare("INSERT INTO `{$this->dbtable}` (`username`, `password`, `password_salt`, $columns) VALUES(:username, :password, :passwordSalt, :$colVals)");
//INSERT INTO MyGuests (firstname, lastname, email)cLUES ('John', 'Doe', 'john#example.com')
$sql = $this->dbh->prepare("INSERT INTO `{$this->dbtable}` (username,email,password,password_salt,name,lastname,created,gender,country,DOB) VALUES ('$username','$email','$pass','$saltedPass','$firstname','$lastname','$created','$gender','$country','$birthdate')");
print($sql);
foreach($other as $key => $value){
$value = htmlspecialchars($value);
$sql->bindValue(":$key", $value);
}
}
/* Bind the default values */
$sql->bindValue(":username", $id);
$sql->bindValue(":password", $saltedPass);
$sql->bindValue(":passwordSalt", $randomSalt);
$sql->execute();
return true;
}
}
So I need to use the variables from register.php in the class file. Can I just include it at the top or do I need to do something specific to the function?
Thanks. I'm focusing on the $sql line after else.
Yes you can include/require register.php file in the class file to use all the variables.
On another note i would like to mention that you should always filter out the POST data before adding it to the query for security concerns.
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 9 years ago.
Got this working how I want, but what updates can i do to it to make it better?
code: ----------------------------------------
$odb = new PDO('mysql:host=localhost;dbname=db371885849', $user, $pass);
$odb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['firstname'])) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$q = "INSERT INTO jobform(firstname, lastname, email) VALUES (:firstname, :lastname, :email);";
$query = $odb->prepare($q);
$results = $query->execute(array(
":firstname" => $firstname,
":lastname" => $lastname,
":email" => $email
));
}
++++++++++++++++++++++++Updated Working ++++++++++++++++++++++++++
$odb = new PDO('mysql:host=localhost;dbname=db371885849', $user, $pass);
$odb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['firstname'])) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
if (!empty($firstname))
{
$q = "INSERT INTO jobform(firstname, lastname, email) VALUES (:firstname, :lastname, :email);";
$query = $odb->prepare($q);
$results = $query->execute(array(
":firstname" => $firstname,
":lastname" => $lastname,
":email" => $email
));
} else {
echo "not today";
}
}
if(!empty($_POST['firstname']) && !empty($_POST['lastname']) && filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$q = "INSERT INTO jobform(firstname, lastname, email) VALUES (:firstname, :lastname, :email);";
$query = $odb->prepare($q);
$results = $query->execute(array(
":firstname" => $firstname,
":lastname" => $lastname,
":email" => $email
));
}else echo 'make an error';
It seems you don't need no validation at all.
So, how I'd did it, based on the code from the tag wiki
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$allowed = array('firstname', 'lastname', 'email');
$sql = "INSERT INTO jobform SET ".pdoSet($fields,$values);
$stm = $dbh->prepare($sql);
$stm->execute($values);
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}
However, if you want to validate user input, you'd meed more complex code:
<?
$allowed = array('firstname', 'lastname', 'email');
if ($_SERVER['REQUEST_METHOD']=='POST') {
$err = array();
//performing all validations and raising corresponding errors
if (empty($_POST['firstname']) $err[] = "Firstname is required";
if (empty($_POST['lastname']) $err[] = "Lastname is required";
if (!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) {
$err[] = "Wrong email format";
}
if (!$err) {
$sql = "INSERT INTO jobform SET ".pdoSet($fields,$values);
$stm = $dbh->prepare($sql);
$stm->execute($values);
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
} else {
foreach ($allowed as => $val) {
$form[$val] = '';
}
}
include 'form.tpl.php';
PDO is used to communicate with the database, not to validate values (apart from quoting them for safe inserts). You will have to perform validation before you get to launching your SQL queries with PDO:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (
// your empty() checks
) {
// your query
}
}
I have this validation code:
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("nnx",$con);
$tbl=mysql_query("SELECT * FROM tablename");
while($row=mysql_fetch_array($tbl))
{
$name=$_POST['name'];
$lname=$_POST['lname'];
$add=$_POST['add'];
$age=$_POST['age'];
$contact=$_POST['contact'];
$email=$_POST['email'];
$user=$_POST['user'];
$pass=$_POST['pass'];
if(($name!="")&&($lname!="")&&($add!="")&&($age!="")&&($contact!="")&& ($email!="")&&($user!="")&&($pass!=""))
{
if ($_POST['user']==$row['username'])
{
header("location: /register.php?codeErr2=1");
}
else
{
$value=mysql_query("INSERT INTO tablename(name, lastname, address, age, contact,email, username, password) VALUES ('".$_POST['name']."','".$_POST['lname']."','".$_POST['add']."','".$_POST['age']."','".$_POST['contact']."','".$_POST['email']."','".$_POST['user']."','".$_POST['pass']."')");
}
}
else
{
header("location: /register.php?codeErr=1");
}
}
This validation is for my registration form, If all the fields are filled up it will check if the username that the user enters is already on the database or not, else, it will get an error message. If the username is already on the database, an error message will be outputted else it will proceed to the next page and all values will be inserted on the database. The problem is that whenever I enter the username which was already on the database, it still accepts the username. I can't find anything wrong with my validation code. Can someone help me out what could be the possible problem here? Thank you in advance. :)
You should check for username and die after the redirect:
$tbl=mysql_query("SELECT * FROM tablename WHERE `username` = '".mysql_real_escape_string($_POST['user'])."'");
$row = mysql_fetch_assoc($tbl);
if ($_POST['user'] == $row['username']){
header("location: /register.php?codeErr2=1");
die;
}
You code is SQL injection vulnerable:
$con=mysql_connect("localhost","root","");
mysql_select_db("nnx",$con);
$tbl=mysql_query("SELECT * FROM tablename WHERE `username` = '".mysql_real_escape_string($_POST['user'])."'");
$row = mysql_fetch_assoc($tbl);
if ($_POST['user'] == $row['username']){
header("location: /register.php?codeErr2=1");
die;
}
$name= $_POST['name'];
$lname= $_POST['lname'];
$add = $_POST['add'];
$age = $_POST['age'];
$contact = $_POST['contact'];
$email = $_POST['email'];
$user = $_POST['user'];
$pass = $_POST['pass'];
if(($name!="") && ($lname!="") && ($add!="") && ($age!="") && ($contact!="") && ($email!="") && ($user!="") && ($pass!="")){
$value=mysql_query("INSERT INTO tablename(name, lastname, address, age, contact, email, username, password)
VALUES
('".mysql_real_escape_string($name)."','".mysql_real_escape_string($lname)."','".mysql_real_escape_string($add)."','".mysql_real_escape_string($age)."',
'".mysql_real_escape_string($contact)."','".mysql_real_escape_string($email)."','".mysql_real_escape_string($user)."',
'".mysql_real_escape_string($pass)."')");
} else {
header("location: /register.php?codeErr=1");
die;
}
As a side note you should move to PDO or MySQLi as mysql_* functions are deprecated.
Here is a nice tutorial and here is an example:
$db = new PDO('mysql:host=localhost;dbname=nnx;charset=UTF-8', 'root', '', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION))
$stmt = $db->prepare("SELECT * FROM `tablename` WHERE `username` = :username");
$stmt->execute(array(':username' => $_POST['user']));
$row_count = $stmt->rowCount();
if($row_count){
header("location: /register.php?codeErr2=1");
die;
}
if(($name!="") && ($lname!="") && ($add!="") && ($age!="") && ($contact!="") && ($email!="") && ($user!="") && ($pass!="")){
$stmt = $db->prepare("INSERT INTO `tablename`(`name`, `lastname`, `address`, `age`, `contact`, `email`, `username`, `password`) VALUES (:name, :lname, :address, :age, :contact, :email, :username, :password)");
$stmt->execute(array(':name' => $_POST['name'], ':lname' => $_POST['lname'], ':address' => $_POST['add'], ':age' => $_POST['age'], ':contact' => $_POST['contact'], ':email' => $_POST['email'], ':username' => $_POST['user'], ':password' => $_POST['pass']));
} else {
header("location: /register.php?codeErr=1");
die;
}
This way your are sql injection free.
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("nnx",$con);
$name=$_POST['name'];
$lname=$_POST['lname'];
$add=$_POST['add'];
$age=$_POST['age'];
$contact=$_POST['contact'];
$email=$_POST['email'];
$user=$_POST['user'];
$pass=$_POST['pass'];
if(($name!="")&&($lname!="")&&($add!="")&&($age!="")&&($contact!="")&& ($email!="")&&($user!="")&&($pass!=""))
{
$tbl=mysql_query("SELECT * FROM tablename where username = '{$user}'");
$num_rows = mysql_num_rows($tbl);
if($num_rows > 0){
header("location: /register.php?codeErr2=1");
} else {
while($row=mysql_fetch_array($tbl))
{
$value=mysql_query("INSERT INTO tablename(name, lastname, address, age, contact,email, username, password) VALUES ('".$_POST['name']."','".$_POST['lname']."','".$_POST['add']."','".$_POST['age']."','".$_POST['contact']."','".$_POST['email']."','".$_POST['user']."','".$_POST['pass']."')");
}
}
} else {
header("location: /register.php?codeErr=1");
}
?>