Null values inserted in database table using php pdo - php

I made a PHP interface for teacher table. All columns in table is set to NOT NULL. If I submit the form with empty inputs. Empty values will be submitted to my database table teacher. I can't understand if columns of the table is set to not null why database table accepts null values from my user interface.
if(filter_has_var(INPUT_POST, "add_teacher")){
function test_input($data){
$data = stripslashes($data);
$data = trim($data);
$data = htmlspecialchars($data);
return $data;
}
if(empty($_POST["firstname"])){
$firstname_err = "* Firstname is required!";
} else {
if(!preg_match("/^[a-zA-Z ]*$/",$_POST["firstname"])){
$firstname_err = "Invalid Firstname";
} else if (!test_input($_POST["firstname"])){
$firstname_err = "Invalid firstName, please enter a valid first name!";
} else {
$firstname = $_POST["firstname"];
}
}
if(empty($_POST["lastname"])){
$lastname_err = "* Last name is required!";
} else {
if(!preg_match("/^[a-zA-Z ]*$/",$_POST["lastname"])){
$lastname_err = "Invalid last name";
} else if (!test_input($_POST["lastname"])){
$lastname_err = "Invalid last name, please enter a valid last name!";
} else {
$lastname = $_POST["lastname"];
}
}
if(empty($_POST["DOB"])){
$DOB_err = "* Date of birth is a required field!";
} else {
$DOB = $_POST["DOB"];
}
if(empty($_POST["gender"])){
$gender_err = "* Gender is a required field!";
} else {
$gender = $_POST["gender"];
}
if(empty($_POST["tazkira_number"])){
$tazkira_number_err = "* This is a required field";
} else {
if(!filter_var($_POST["tazkira_number"], FILTER_VALIDATE_INT)){
$tazkira_number_err = "* Only numbers are allowed";
} else if(!test_input($_POST["tazkira_number"])){
$tazkira_number_err = "* Invalid data entered";
}
else {
$tazkira_number = $_POST["tazkira_number"];
}
}
if(empty($_POST["phone_number"])){
$phone_number_err = "* This is a required field";
} else {
$phone_number = $_POST["phone_number"];
}
if(empty($_POST["academic_field"])){
$academic_field_err = "* Academic field is required!";
} else {
if(!preg_match("/^[a-zA-Z ]*$/",$_POST["academic_field"])){
$academic_field_err = "Invalid academic field.";
} else if (!test_input($_POST["academic_field"])){
$academic_field_err = "Invalid academic field, please enter a valid academic field!";
} else {
$academic_field = $_POST["academic_field_err"];
}
}
if(empty($_POST["email"])){
$email_err = "* Email field is required!";
} else {
if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)){
$email_err = "Invalid email entered";
} else if (!test_input($_POST["email"])){
$academic_femail_err = "Invalid data, please enter a valid email address!";
} else {
$email = $_POST["email"];
}
}
if(empty($_POST["position"])){
$position_err = "* Position field is required!";
} else {
if(!preg_match("/^[a-zA-Z ]*$/",$_POST["position"])){
$position_err = "* Invalid data";
} else if (!test_input($_POST["position"])){
$position_err = "* Invalid data, please enter a valid position!";
} else {
$position = $_POST["position"];
}
}
if(empty($_POST["hire_date"])){
$hire_date_err = "* Hire date is a required field!";
} else {
$hire_date = $_POST["hire_date"];
}
$resign_date = $_POST["resign_date"];
$sql = "INSERT INTO teacher (firstname, lastname, DOB, gender, tazkira_number, phone_number, academic_field, email, position, hire_date, resign_date) VALUES (:firstname, :lastname, :DOB, :gender, :tazkira_number, :phone_number, :academic_field, :email, :position, :hire_date, :resign_date)";
$stmt = $conn->prepare($sql);
$res = $stmt->execute(["firstname"=> $firstname, "lastname" => $lastname, "DOB" => $DOB, "gender" => $gender, "tazkira_number" => $tazkira_number, "phone_number" => $phone_number, "academic_field" => $academic_field, "email" => $email, "position" => $position, "hire_date" => $hire_date, "resign_date" => $resign_date]);
$add_teacher_success_msg = "New teacher added successfully!";
}
As you can see above this code inserts into teacher some values. If I don't write anything in input of the form and click submit. Null or empty values will be submitted to table. Please help me solve this problem. Thank you

Your "empty values" are actually not "null" values but "empty strings" (strings with zero characters).
To make PDO recognize them as NULL values, you have to convert empty strings into null before you inserting them into database.
For example, you could create function:
// e2n means "empty to null", and made shorter for more convinient usage:
function e2n($src)
{
if (is_string($src) && trim($src) == "")
{
return null;
}
else
{
return $src;
}
}
And use it like:
$sql = "INSERT INTO teacher (firstname, lastname, DOB, gender, tazkira_number, phone_number, academic_field, email, position, hire_date, resign_date) VALUES (:firstname, :lastname, :DOB, :gender, :tazkira_number, :phone_number, :academic_field, :email, :position, :hire_date, :resign_date)";
$stmt = $conn->prepare($sql);
$res = $stmt->execute(["firstname"=> e2n($firstname), "lastname" => e2n($lastname), "DOB" => e2n($DOB), "gender" => e2n($gender), "tazkira_number" => e2n($tazkira_number), "phone_number" => e2n($phone_number), "academic_field" => e2n($academic_field), "email" => e2n($email), "position" => e2n($position), "hire_date" => e2n($hire_date), "resign_date" => e2n($resign_date)]);
Also, I recommend you to refactor your algorythm, so you have some array of fields, and names of validators, that are used for them, and walk through fields, running corresponding validators, and also make e2n conversion in place.
About error "SQLSTATE[23000]: Integrity constraint violation: 1048":
To skip insertion of data, you should add testing for your *_err variables:
$isOk = true;
//All your Error fields
$err_fields = ['firstname_err', 'lastname_err', 'DOB_err', 'gender_err', 'tazkira_number_err', 'phone_number_err', 'position_err', 'academic_field_err', 'email_err', 'hire_date_err'];
foreach ($err_fields as $field)
{
if (isset($$field) && $$field)
{
echo "You have error!<br>";
$isOk = false;
}
}
if ($isOk)
{
// Running SQL if there were no errors:
$sql = "INSERT INTO teacher (firstname, lastname, DOB, gender, tazkira_number, phone_number, academic_field, email, position, hire_date, resign_date) VALUES (:firstname, :lastname, :DOB, :gender, :tazkira_number, :phone_number, :academic_field, :email, :position, :hire_date, :resign_date)";
$stmt = $conn->prepare($sql);
$res = $stmt->execute(["firstname"=> e2n($firstname), "lastname" => e2n($lastname), "DOB" => e2n($DOB), "gender" => e2n($gender), "tazkira_number" => e2n($tazkira_number), "phone_number" => e2n($phone_number), "academic_field" => e2n($academic_field), "email" => e2n($email), "position" => e2n($position), "hire_date" => e2n($hire_date), "resign_date" => e2n($resign_date)]);
}

You're checking for invalid values, but not doing anything if you find them. I.e., you're always running the INSERT, no matter what errors you find. I'd recommend not using a separate variable for each error, but instead append errors to an array:
$errors = [];
if (empty($_POST["email"])) {
$errors[] = 'Email is required.';
}
if (empty($_POST["academic_field"])) {
$errors[] = "Academic field is required.";
}
// and so on...
Then, you can just check to see if $errors is empty to know if you have any errors:
if (empty($errors)) {
// No errors, try the insert.
$sql = "INSERT INTO teacher ...";
$stmt = $conn->prepare($sql);
$res = $stmt->execute(...);
} else {
// Display the errors.
echo "You have errors:";
foreach ($errors as $error) {
echo $error;
}
}

Related

Receiving Error Message, despite data being sent

I have recently implemented a number of if statements that check to see if the require data has been entered, if not then I receive the error message something is wrong with.... But after implementing them I now recieve that error message regardless of whether the data is in fact being sent to the database (the data that is being sent is all correct) and I can't for the life of me figure out why.
$query = "insert into $sql_table (Eoi, Job_reference_number, First_Name, Last_Name, Street_Address, Suburb, State, Postcode, Email, Phone_Number, Skills) values ('$eoi','$jobNumber', '$firstName', '$lastName', '$streetAddress', '$suburb', '$state', '$postcode', '$emailAddress', '$phoneNumber', '$skills')";
$result = mysqli_query($conn, $query);
if($jobNumber = ''){
$result = false;
}
if($firstName = ''){
$result = false;
echo "<p> Something is wrong with your First Name </p>";
}
if($lastName = ''){
$result = false;
echo "<p> Something is wrong with your Last Name </p>";
}
if($streetAddress = ''){
$result = false;
echo "<p> Something is wrong with your Street Address </p>";
}
if($suburb = ''){
$result = false;
echo "<p> Something is wrong with your Suburb </p>";
}
if($postcode = ''){
$result = false;
echo "<p> Something is wrong with your Postcode </p>";
}
if($email = ''){
$result = false;
echo "<p> Something is wrong with your Email </p>";
}
if($phoneNumber = ''){
$result = false;
echo "<p> Something is wrong with your Phone Number </p>";
}
if($skills = ''){
$result = false;
echo "<p> Something is wrong with your Skills </p>";
}
if($result != mysqli_query($conn, $query)) {
echo "<p>Something is wrong with ", $query, "</p>";
}else {
echo "<p class=\"ok\">Successfully added a New EOI record</p>";
}
}
}
mysqli_close($conn);
I expect the result to be Successfully added a new EOI record when the user inputs valid data but instead I get the error message.
First you have a syntax error in if statement
if statement should be == not =
if($yourVariable == ''){
echo "<p> Something is wrong with your yourVariable </p>";//no meaning of this line
$result = false;
}
it means if your variable is empty then $result will false and you're can check it in your last if
Second you are checking all variable after DB insertion, you need to do it before insertion in db

My query keeps allowing me to register an existing account

I'm trying to make a master account that adds students , and i want to show that a certain account is existing through Email or Unique USN(university student number)
<?php
require 'config.php';
if (isset ($_POST['fname']) && (isset($_POST['mname']) && (isset($_POST['lname']) && (isset($_POST['email']) && (isset($_POST['usn']) && (isset($_POST['schedule'])))))))
{
$fname = $_POST['fname'];
$mname = $_POST['mname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$usn = $_POST['usn'];
$schedule = $_POST['schedule'];
$sql = 'INSERT INTO students(fname, mname, lname, email, usn, schedule) VALUES (:fname, :mname, :lname, :email, :usn, :schedule))';
$statement = $db->prepare($sql);
executing variable/array
if ($statement->execute([':fname' => $fname, ':mname' => $mname, ':lname' => $lname, ':email' => $email, ':usn' => $usn, ':schedule' => $schedule]))
{
echo "<script type= 'text/javascript'> alert('New Student Record Inserted Successfully'); </script>";
}
tried to show error that a student with the same usn exists
$check = $db->prepare("SELECT COUNT(*) FROM students WHERE 'usn' = :usn");
$check->bindValue(':usn', $_POST['usn']);
$check->execute();
if($check->fetch(PDO::FETCH_ASSOC) > 0)
{
echo "<script type= 'text/javascript'> alert('User already exist.'); </script>";
}
tried to show that a student with the same email exists
$check2 = $db->prepare("SELECT COUNT(*) FROM students WHERE 'email' = :email");
$check2->bindValue(':email', $_POST['email']);
$check2->execute();
if($check2->fetch(PDO::FETCH_ASSOC) > 0)
{
echo "<script type= 'text/javascript'> alert('Email already exist.'); </script>";
}
if (empty ($_POST['fname']) or (empty($_POST['lname']) or (empty($_POST['email']) or (empty($_POST['usn']) or (empty($_POST['schedule']))))))
{
echo "<script type= 'text/javascript'> alert('There are some field/s that must be filled.'); </script>";
}
}
?>
I tried doing this but it activates the error handlers instantly
One problem is that you've quoted the column identifiers in your queries ('usn' = :usn" and 'email' = :email".) That's going to compare the bound values to the literal strings 'usn' and 'email'. So don't do that.
if($check2->fetch(PDO::FETCH_ASSOC) > 0) is also a problem.
If your query runs successfully, $check2->fetch(PDO::FETCH_ASSOC) is going to be an array with one value, which does evaluate to > 0, regardless of the value in it. (PHP casts the array to int for comparison with 0, which is undefined behavior, but in this case apparently returns > 0.)
You need to get the first column from the result instead, and then refer to that in your if condition.
if ($check2->fetchColumn() > 0) ...
Also, regardless of any of this, if you have certain columns that should remain unique in your table, add unique indexes to them so they won't accept duplicate values even if your application doesn't catch them properly.

validate my form and header to another success page

I am trying to validate my form fields and redirect the user to success page
so this is the PHP code
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$experiences = $courses = $careerObjective = $availability = $typeOfJob = $rank = $jTitle = $otherJobTitle
= $salaryRange = $currency = $workIn = "";
$experiencesErr = $coursesErr = $careerObjectiveErr = $availabilityErr = $typeOfJobErr = $rankErr = $jTitleErr
= $otherJobTitleErr = $salaryRangeErr = $currencyErr = $workInErr = "";
$id = "";
$uid = "";
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$error = array(
"coursesErr"=>"",
"careerObjectiveErr"=>"",
"otherJobTitleErr"=>"",
"experiencesErr"=>"",
"availabilityErr"=>"",
"typeOfJobErr"=>"",
"rankErr"=>"",
"jTitleErr"=>"",
"salaryRangeErr"=>"",
"currencyErr"=>"",
);
if (empty($_POST['experiences'])) {
$error['experiencesErr'] = "Experiences Required";
} else {
$experiences = check_input($_POST['experiences']);
if (!preg_match("/^[0-9_a-zA-Z ]*$/", $experiences)) {
$error['experiencesErr'] = "Only letters, numbers and '_' allowed";
}
}
$courses = check_input($_POST['courses']);
if (!preg_match("/^[0-9_a-zA-Z ]*$/", $courses)) {
$error['coursesErr'] = "Only letters, numbers and '_' allowed";
}
$careerObjective = check_input($_POST['careerObjective']);
if (!preg_match("/^[0-9_a-zA-Z ]*$/", $careerObjective)) {
$error['careerObjectiveErr'] = "Only letters, numbers and '_' allowed";
}
if (empty($_POST['availability'])) {
$error['availabilityErr'] = "Availability Required";
} else {
$availability = check_input($_POST['availability']);
}
if (empty($_POST['typeOfJob'])) {
$error['typeOfJobErr'] = "Full/Part Time Required";
} else {
$typeOfJob = check_input($_POST['typeOfJob']);
}
if (empty($_POST['typeOfJob'])) {
$error['typeOfJobErr'] = "Full/Part Time Required";
} else {
$typeOfJob = check_input($_POST['typeOfJob']);
}
if (empty($_POST['rank'])) {
$error['rankErr'] = "Self-assessment Required";
} else {
$rank = check_input($_POST['rank']);
}
if (empty($_POST['jTitle'])) {
$error['jTitleErr'] = "Job Field Required";
} else {
$jTitle = check_input($_POST['jTitle']);
}
$otherJobTitle = check_input($_POST['otherJobTitle']);
if (!preg_match("/^[0-9_a-zA-Z ]*$/", $otherJobTitle)) {
$error['otherJobTitleErr'] = "Only letters, numbers and '_' allowed";
}
if (empty($_POST['salaryRange'])) {
$error['salaryRangeErr'] = "Salary Range Required";
} else {
$salaryRange = check_input($_POST['salaryRange']);
}
if (empty($_POST['currency'])) {
$error['currencyErr'] = "Currency Required";
} else {
$currency = check_input($_POST['currency']);
}
$workIn = check_input($_POST['workIn']);
if(!$error){
$putData = $db->prepare("INSERT INTO hired_ts_info (id, uid, experiences, courses, career_objective,
availability, type_of_job, rank, job_title, other_job_title, salary_range, currency, workIn)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$putData->bind_param('iisssssssssss', $id, $uid, $experiences, $courses, $careerObjective, $availability,
$typeOfJob, $rank, $jTitle, $otherJobTitle, $salaryRange, $currency, $workIn);
if($putData->execute()){
header("Location:?pid=4&pp=2&pps=technicalSummary&m=g");
}else{
echo "Error on executing";
}
}
}
?>
and this is the first lines of the HTML code
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post" id="personRegestrationPage4">
<div class="f_left width100percent">
<div class="TwoLine">
<label for="experiences" class="requiredFields">experiences and qualifications</label>
<textarea name="experiences" id="experiences"></textarea>
<span class="notAllowed"><?php if (isset($error)) {
echo $error['experiencesErr'];
}?></span>
</div>
<div class="TwoLine">
<label for="courses">Previous Courses</label>
<textarea name="courses" id="courses"></textarea>
<span class="notAllowed"><?php if (isset($error)) {
echo $error['coursesErr'];
} ?></span>
</div>
</div>
and this is the submit button code
<input type="submit" name="subTs" id="subTs" value="Save Changes" class="submitBtn4">
Problem
now when I submit the form it come back without inserting anything to the db and no error message received
Update
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$experiences = $courses = $careerObjective = $availability = $typeOfJob = $rank = $jTitle = $otherJobTitle
= $salaryRange = $currency = $workIn = "";
$experiencesErr = $coursesErr = $careerObjectiveErr = $availabilityErr = $typeOfJobErr = $rankErr = $jTitleErr
= $otherJobTitleErr = $salaryRangeErr = $currencyErr = $workInErr = "";
$id = "";
$uid = "";
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$error = array();
if (empty($_POST['experiences'])) {
$error['experiencesErr'] = "Experiences Required";
} else {
$experiences = check_input($_POST['experiences']);
if (!preg_match("/^[0-9_a-zA-Z ]*$/", $experiences)) {
$error['experiencesErr'] = "Only letters, numbers and '_' allowed";
}
}
$courses = check_input($_POST['courses']);
if (!preg_match("/^[0-9_a-zA-Z ]*$/", $courses)) {
$error['coursesErr'] = "Only letters, numbers and '_' allowed";
}
$careerObjective = check_input($_POST['careerObjective']);
if (!preg_match("/^[0-9_a-zA-Z ]*$/", $careerObjective)) {
$error['careerObjectiveErr'] = "Only letters, numbers and '_' allowed";
}
if (empty($_POST['availability'])) {
$error['availabilityErr'] = "Availability Required";
} else {
$availability = check_input($_POST['availability']);
}
if (empty($_POST['typeOfJob'])) {
$error['typeOfJobErr'] = "Full/Part Time Required";
} else {
$typeOfJob = check_input($_POST['typeOfJob']);
}
if (empty($_POST['typeOfJob'])) {
$error['typeOfJobErr'] = "Full/Part Time Required";
} else {
$typeOfJob = check_input($_POST['typeOfJob']);
}
if (empty($_POST['rank'])) {
$error['rankErr'] = "Self-assessment Required";
} else {
$rank = check_input($_POST['rank']);
}
if (empty($_POST['jTitle'])) {
$error['jTitleErr'] = "Job Field Required";
} else {
$jTitle = check_input($_POST['jTitle']);
}
$otherJobTitle = check_input($_POST['otherJobTitle']);
if (!preg_match("/^[0-9_a-zA-Z ]*$/", $otherJobTitle)) {
$error['otherJobTitleErr'] = "Only letters, numbers and '_' allowed";
}
if (empty($_POST['salaryRange'])) {
$error['salaryRangeErr'] = "Salary Range Required";
} else {
$salaryRange = check_input($_POST['salaryRange']);
}
if (empty($_POST['currency'])) {
$error['currencyErr'] = "Currency Required";
} else {
$currency = check_input($_POST['currency']);
}
$workIn = check_input($_POST['workIn']);
if (!$error) {
$putData = $db->prepare("INSERT INTO hired_ts_info (id, uid, experiences, courses, career_objective,
availability, type_of_job, rank, job_title, other_job_title, salary_range, currency, workIn)
VALUE(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$putData->bind_param('iisssssssssss', $id, $uid, $experiences, $courses, $careerObjective, $availability,
$typeOfJob, $rank, $jTitle, $otherJobTitle, $salaryRange, $currency, $workIn);
if ($putData->execute()) {
header("Location:?pid=4&pp=2&pps=technicalSummary&m=g");
} else {
echo "Error on executing";
}
} else {
$error = array(
"coursesErr" => "",
"careerObjectiveErr" => "",
"otherJobTitleErr" => "",
"experiencesErr" => "",
"availabilityErr" => "",
"typeOfJobErr" => "",
"rankErr" => "",
"jTitleErr" => "",
"salaryRangeErr" => "",
"currencyErr" => "",
);
}
}
?>
still that didn't solve the issue
1- now the code submit correctly and gos to my DB.
2- if the fields is empty or not allowed input the message don't appear any more under the fields
any Ideas pleasee
The reason behind your script is not showing any error is this
that you set the value again for your error in the else statement which is empty; in these line
else {
$error = array(
"coursesErr" => "",
"careerObjectiveErr" => "",
"otherJobTitleErr" => "",
"experiencesErr" => "",
"availabilityErr" => "",
"typeOfJobErr" => "",
"rankErr" => "",
"jTitleErr" => "",
"salaryRangeErr" => "",
"currencyErr" => "",
);
}
in these line you set the value for your $error Arrray, and set them to empty.
The things is this even you set the array value before, but when the php reaches these line, it changes those value to empty value which you define,
For example if you have a code like this
$x=4;
$x=5;
even though you got same variable, but if you echo $x; its gonna give you always 5 cause this is the last value for $x;
to understand it more clearly what you should do give some value in any $error array in else statement it will show that $error
like this
$error = array(
"coursesErr" => "my name is spider man",
"careerObjectiveErr" => "",
"otherJobTitleErr" => "",
"experiencesErr" => "",
"availabilityErr" => "",
"typeOfJobErr" => "",
"rankErr" => "",
"jTitleErr" => "",
"salaryRangeErr" => "",
"currencyErr" => "",
);
}
and than run the code, it will show you that particular error not any other, because you set it value,
so what should you do now, easy option is this remove the else statement completely,

PHP Form Validation and Submit to Database

I would like to ask how do I set PHP "form validation" and "submit to database" in one single php file? This is what I tried to do in PART 1 and PART 2.
$latErr = $lngErr = $messageErr = "";
$lat = $lng = $message = "";
$tbl_name="stickers";
$datetime=date("d-m-y H:i:s");
//PART 1 - form validation method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["inputfield1"])) {
$latErr = "* Latitude is required. Please enable your browser geolocation settings.";
} else {
$lat = test_input($_POST["inputfield1"]);
}
if (empty($_POST["inputfield2"])) {
$lngErr = "* Longitude is required. Please enable your browser geolocation settings.";
}else{
$lng = test_input($_POST["inputfield2"]);
}
if (empty($_POST["message"])) {
$messageErr = "* Please enter your message.";
} else {
$message = test_input($_POST["message"]);
}
}
//PART 2 - check if all 3 parameters are filled, if yes then insert into database
if (isset($lat, $lng, $message)){
$sql="INSERT INTO $tbl_name(username, message, datetime, lat, lng )VALUES('$user- >username','$message', '$datetime', '$lat', '$lng')";
$result=mysql_query($sql);
//check if query successful
if($result){
$post_info = "Your msg is successfully posted!";
}else{
$post_info = "Oops, there is an error posting the msg.";
}
mysql_close();
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
It doesn't work. It just insert blanks into the database. Something is wrong but I dunno what is it? Anyone can advice. Thanks.
Maybe you need to use empty() instead of isset()?
//PART 1 - form validation method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["inputfield1"])) {
$latErr = "* Latitude is required. Please enable your browser geolocation settings.";
} else {
$lat = test_input($_POST["inputfield1"]);
}
if (empty($_POST["inputfield2"])) {
$lngErr = "* Longitude is required. Please enable your browser geolocation settings.";
}else{
$lng = test_input($_POST["inputfield2"]);
}
if (empty($_POST["message"])) {
$messageErr = "* Please enter your message.";
} else {
$message = test_input($_POST["message"]);
}
}
//PART 2 - check if all 3 parameters are filled, if yes then insert into database
if ( !empty($lat) && !empty($lng) && !empty($message) ){
$sql="INSERT INTO $tbl_name(username, message, datetime, lat, lng )VALUES('$user- >username','$message', '$datetime', '$lat', '$lng')";
$result=mysql_query($sql);
//check if query successful
if($result){
$post_info = "Your msg is successfully posted!";
}else{
$post_info = "Oops, there is an error posting the msg.";
}
}
else {
$post_info = "Empty content.";
}
mysql_close();

table just inserts one row. there is an auto increment id

This is my registration code.
Once I enter the fields in the form it shows me registration successful but adds blank data in my database table. It adds number 0 in my mobileno column.
Please help me here asap
include ('database_connection.php');
if (isset($_POST['formsubmitted'])) {
$error = array();//Declare An Array to store any error message
if (empty($_POST['mobileno'])) {//if no name has been supplied
$error[] = 'Please Enter a Mobile Number ';//add to array "error"
} else {
$name = $_POST['mobileno'];//else assign it a variable
}
if (empty($_POST['fname'])) {//if no name has been supplied
$error[] = 'Please Enter a First name ';//add to array "error"
} else {
$name = $_POST['fname'];//else assign it a variable
}
if (empty($_POST['lname'])) {//if no name has been supplied
$error[] = 'Please Enter a Last name ';//add to array "error"
} else {
$name = $_POST['lname'];//else assign it a variable
}
if (empty($_POST['email'])) {
$error[] = 'Please Enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA- Z0-9\._-]+)+$/", $_POST['email'])) {
//regular expression for email validation
$Email = $_POST['email'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['passwd1'])) {
$error[] = 'Please Enter Your Password ';
} else {
$Password = $_POST['passwd1'];
}
if (empty($_POST['passwd2'])) {
$error[] = 'Please Verify Your Password ';
} else {
$Password = $_POST['passwd2'];
}
if (empty($error)) //send to Database if there's no error '
{ //If everything's OK...
// Make sure the mobile no is available:
$query_verify_mobileno = "SELECT * FROM userdtls WHERE mobileno = '$mobileno'";
$result_verify_mobileno = mysqli_query($dbc, $query_verify_mobileno);
if (!$result_verify_mobileno)
{//if the Query Failed ,similar to if($result_verify_mobileno==false)
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result_verify_mobileno) == 0) { // IF no previous user is using this number .
// Create a unique activation code:
$activation = md5(uniqid(rand(), true));
$query_insert_user = "INSERT INTO userdtls (`mobileno`, `pass`, `fname`, `lname`, `email`, `activation`) VALUES ( '$mobileno', '$passwd1', '$fname', '$lname', '$email', '$activation')";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
// Send the email:
$message = " To activate your account, please click on this link:\n\n";
$message .= WEBSITE_URL . '/activate.php?email=' . urlencode($Email) . "&key=$activation";
mail($Email, 'Registration Confirmation', $message, 'From: rahul19dj#gmail.com');
// Flush the buffered output.
// Finish the page:
echo '<div class="success">Thank you for registering! A confirmation email has been sent to '.$email.' Please click on the Activation Link to Activate your account </div>';
} else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system error. We apologize for any inconvenience.</div>';
}
} else { // The mobile number is not available.
echo '<div class="errormsgbox" >That mobile number has already been registered.</div>';
}
} else {//If the "error" array contains error msg , display them
echo '<div class="errormsgbox"> <ol>';
foreach ($error as $key => $values) {
echo ' <li>'.$values.'</li>';
}
echo '</ol></div>';
}
mysqli_close($dbc);//Close the DB Connection
} // End of the main Submit conditional.
You're assigning all of your variables, except $email to $name overwriting each one in succession. This is definitely going to cause strange results which are dependant on the data types of each column in your dataase. If mobileno is set to be an int has a default value of 0 a string or empty value will result in you seeing 0 in your dataase.

Categories