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
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.
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,
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();
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.