Inserting PHP Session Variables into MySQL Database - php

I am having issues with my PHP code. I am trying to insert data into a mysql database using two session variables that I will need at a later time in the form. However whenever I submit the form I am returned with a "Unknown column in 'field list'" error.
The code is lengthy but you will likely need all of it to understand the issue.
<?php
session_start();
// Check for hazards and put them in an array if there is one selected
if($_SERVER['REQUEST_METHOD'] == 'POST') {
require ('../mysqli_connect.php'); //connect to the db
//Check for offender first name
if (empty($_POST['pris_firstname'])) {
$errors[] = 'You forgot to enter offender first name.';
} else {
$prisf=$_POST['pris_firstname'];
}
//Check for offender last name
if (empty($_POST['pris_lastname'])) {
$errors[] = 'You forgot to enter offender last name.';
} else {
$prisl=$_POST['pris_lastname'];
}
//Check for offender date of birth
$dob = ($_POST['pris_dateofbirth']);
//Check for offender phone number
if (empty($_POST['pris_phonenum'])) {
$errors[] = 'You forgot to enter offender Phone Number.';
} else {
$prisphone=trim($_POST['pris_phonenum']);
}
//Check for offender address
if (empty($_POST['pris_address'])) {
$errors[] = 'You forgot to enter offender Address.';
} else {
//$prisaddress=trim($_POST['pris_address']);
foreach($_POST["pris_address"] as $value) {
$prisaddress .= $value . '\n';
}
}
//Check for offender next of kin first name
if (empty($_POST['pris_kinfirstname'])) {
$errors[] = 'You forgot to enter next of kin first name.';
} else {
$kinfirst=trim($_POST['pris_kinfirstname']);
}
//Check for offender next of kin last name
if (empty($_POST['pris_kinlastname'])) {
$errors[] = 'You forgot to enter next of kin last name.';
} else {
$kinlast=trim($_POST['pris_kinlastname']);
}
//Check for offender next of kin phone number
if (empty($_POST['pris_kinphone'])) {
$errors[] = 'You forgot to enter next of kin area code.';
} else {
$kinphone=trim($_POST['pris_kinphone']);
}
if (empty($_POST['pris_kinrelation'])) {
$errors[] = 'You forgot to enter next of kin relation.';
} else {
$kinrelation=trim($_POST['pris_kinrelation']);
}
//Check for offender next of kin address
if (empty($_POST['pris_kinaddress'])) {
$errors[] = 'You forgot to enter next of kin street address.';
} else {
foreach($_POST["pris_kinaddress"] as $value2) {
$kinaddress .= $value2 . '\n';
}
}
if (empty($errors)) { //if everyhing is ok
$q = "INSERT INTO prisoner_profile (pris_status,
pris_firstname,
pris_lastname,
pris_dateofbirth,
pris_phonenum,
pris_address,
pris_kinfirstname,
pris_kinlastname,
pris_kinphone,
pris_kinaddress,
pris_kinrelation
) VALUES (
'$status',
".$_SESSION['pris_firstname'].", ".$_SESSION['pris_lastname'].",
'$dob',
'$prisphone',
'$prisaddress',
'$kinfirst',
'$kinlast',
'$kinphone',
'$kinaddress',
'$kinrelation'
)";
$r = #mysqli_query ($dbc, $q); //Run the query.
Hope someone can help!

The error is pretty much self-explanatory, it means that you have got a column name wrong in your database. I recomend you echo out the error for your query just for this case as:
$r = mysqli_query ($dbc, $q) or die (mysqli_error());

One of the columns that are listed in your INSERT statement does not actually exist in the prisoner_profile. Check your table schema.

The one obvious issue I can see here is that you haven't handled the escape characters in your query, and you have used a few \n characters in your code.
Use mysqli_real_escape_string to handle that when inputting the data to the database.
Something like
$q = mysqli_real_escape_string($q);

Related

Recurring Error Display error function php

I have an output_errors function on my website which outputs all the "set" errors in a variable.
It pretty much works exactly how it should except for one thing; for one error in particular, it will output that error more than once (which it shouldn't).
How it is supposed to work is: if the user that is registering does not input any information into a certain part of the form, it needs to output (once) the error Fields marked with an asterisk(*) must be filled in., along with any other errors that the user has come across. All of this is displayed in an unordered list.
This is the function that I have created:
function output_errors($errors){
return '<ul><li>' . implode('</li><li>', $errors) . '</li></ul>';
}
This is the code in which I specify when an error should be output:
$required = array('fname', 'username', 'password', 'password_again', 'email');
$reqCCNo = array('ccno');
// validation
foreach($_POST as $key=>$value){
if(empty($value) && in_array($key, $required) === true){
$errors[] = 'Fields marked with an asterisk(*) must be filled in.';
}
if(empty($value) && in_array($key, $reqCCNo) === true){
$errors[] = 'Please select a country.';
}
}
if(empty($errors)){
// credentials
if(preg_match('/[^a-z_\-0-9]/i', $fnp) || preg_match('/[^a-z_\-0-9]/i', $lnp)){
$errors[] = 'Credentials must only contain letters and numbers.';
}
// username
$result = mysqli_query($conn, "SELECT username FROM users WHERE username = '$user'");
$count = mysqli_num_rows($result);
if($count !== 0) {
$errors[] = 'That username is already taken.';
}
if(strlen($user) < 4){
$errors[] = 'Your username must be more than 4 characters long.';
}
if(strlen($user) > 16){
$errors[] = 'Your username must not be more than 16 characters long.';
}
if(preg_match('/[^a-z_\-0-9]/i', $user)){
$errors[] = 'Your username can only contain Alphanumeric characters.';
}
// email
if(filter_var($emailNex, FILTER_VALIDATE_EMAIL) === false){
$errors[] = 'That is not a valid email type.';
}
$email_result = mysqli_query($conn, "SELECT email FROM users WHERE email = '$emailNex'");
$email_count = mysqli_num_rows($email_result);
if($email_count !== 0) {
$errors[] = 'That email is already in use.';
}
// password
if(strlen($pass) < 6){
$errors[] = 'Your password must be more than 6 characters long.';
}
if($pass !== $_POST['password_again']){
$errors[] = 'Those passwords do not match!';
}
}
and, this is the code that I use to output all of those errors:
if(!empty($errors)){
echo output_errors($errors);
}
Say that I leave all the fields blank and input a username less than 4 characters long, this is how it should be output:
Fields marked with an asterisk(*) must be filled in.
Your username must be more than 4 characters long.
this is how it is being output right now:
Fields marked with an asterisk(*) must be filled in.
Fields marked with an asterisk(*) must be filled in.
Fields marked with an asterisk(*) must be filled in.
Please select a country.
Your username must be more than 4 characters long.
All help is appreciated!
Thanks
Problem is with your foreach loop. it insert error message for every Required file.
You need to create a flag outside your foreach loop and set it to true when it comes inside your condition as
$flag=FALSE;// set it false
foreach($_POST as $key=>$value){
if(empty($value) && in_array($key, $required) === true){
$flag=TRUE;// set true if fulfill your condition
}
}
if($flag){// set your message
$errors[] = 'Fields marked with an asterisk(*) must be filled in.';
}
It will set your error message once instead of multiple

Creating a registration page in PHP

Hi guys so im creating this registration page for my website in php..This is the PHP script
# Script 9.5 - register.php #2
// This script performs an INSERT query to add a record to the users table.
$page_title = 'Register';
include ('includes/header.html');
// Check for form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array(); // Initialize an error array.
// Check for a name:
if (empty($_POST['name'])) {
$errors[] = 'You forgot to enter your name.';
} else {
$n = mysqli_real_escape_string($dbh, trim($_POST['name']));
}
// Check for an email:
if (empty($_POST['email'])) {
$errors[] = 'You forgot to enter your email.';
} else {
$e = mysqli_real_escape_string($dbh, trim($_POST['email']));
}
// Check for a password and match against the confirmed password:
if (!empty($_POST['pass1'])) {
if ($_POST['pass1'] != $_POST['pass2']) {
$errors[] = 'Your password did not match the confirmed password.';
} else {
$p = mysqli_real_escape_string($dbh, trim($_POST['pass1']));
}
} else {
$errors[] = 'You forgot to enter your password.';
}
// Check for contact number:
if (empty($_POST['contact_no'])) {
$errors[] = 'You forgot to enter your contact no.';
} else {
$cn = mysqli_real_escape_string($dbh, trim($_POST['contact_no']));
}
if (empty($errors)) { // If everything's OK.
require 'connect_db.php';
$conn= mysqli_connect('*****' , '*****', '*****' , '*****' ,****);
// Make the query:
$q = ("INSERT INTO register_user(name, email, pass, contact_no) VALUES ('$n', '$e','$p','$cn')");
$r = #mysqli_query ($dbh, $q);// Run the query.
if ($r) { // If it ran OK.
// Print a message:
echo '<h1>Thank you!</h1>
<p>You are now registered. </p>
<p>Login </p>';
} else { // If it did not run OK.
// Public message:
echo '<h1>System Error</h1>
<p class="error">You could not be registered due to a system error. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbh) . '<br/><br/> Query: ' . $q . '</p>';
} // End of if ($r) IF.
mysqli_close($dbh); // Close the database connection.
// Include the footer and quit the script:
include ('includes/footer.html');
exit();
} else { // Report the errors.
echo '<h1>Error!</h1>
<p class="error">The following error(s) occurred:<br>';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br>";
}
echo 'Please try again.</p>';
} // End of if (empty($errors)) IF.
mysqli_close($dbh); // Close the database connection.
But the thing is once i register this is the output:
System Error
You could not be registered due to a system error. We apologize for any inconvenience.
Query: INSERT INTO register_user(name, email, pass, contact_no) VALUES ('', '','','')
so im kindly would glad for any assistance
You're calling mysqli_real_escape_string() BEFORE you establish your DB connection. This is not permitted. You MUST have a connection before doing the escape operations.
That means every single one of your form fields is going to be a boolean FALSE value, which signifies failure.
Your code should be structured
1. connect to db
2. process form inputs
3. if form inputs ok, insert into db
You've got #1 and #2 reversed.

PHP not working, database not updating

im writing this php script to update user passwords, requiring old pasword, new and new confirmation. It all works it seems up to the actual UPDATE mysql statement. Not sure what I've done wrong, al help appreciated!
Also, I am aware its not secure and such, I am just trying ot make it work first im a php newbie!
I'm tearing my hair out, when I run this, everything seems to work except it breaks just before if (empty($error)){ , i have tested the echo for session email and it displays that, however it does not update the database with the new password. Please help! below is my code:
<?php
session_start();
include('database_connection.php');
$error = array();
if (empty($_POST['oldpassword'])){
$error[] ='You did not enter your current password!';
} else {
$oldpassword = $_POST['oldpassword'];
}
if (empty($_POST['newpassword'])){
$error[] = 'You did not enter a new password!';
} else {
if(preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $_POST["newpassword"])){
$newpassword = $_POST['newpassword'];
} else{
$error[] = 'Password must be at least 8 characters and must contain at least one lower case letter, one upper case letter and one digit!';
}
}
if (empty($_POST['newpasswordcon'])){
$error[] = 'You did not enter your new password confirmation!';
} else {
if(preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $_POST["newpasswordcon"])){
$newpasswordcon = $_POST['newpasswordcon'];
} else{
$error[] = 'Password must be at least 8 characters and must contain at least one lower case letter, one upper case letter and one digit!';
}
}
if($_POST['newpassword'] != $_POST['newpasswordcon']){
$error[] ='New password and confirmation do not match!' ;
}
$sql = "SELECT password FROM users WHERE email='" . $_SESSION['email'] . "'";
$result = mysql_query($sql);
if( $r = mysql_fetch_array($result) ) {
extract($r);
if($_POST['oldpassword'] != $password);{
$error[] ='Incorrect current password!';
}
//breaks here
echo $_SESSION['email'];
if (empty($error)){
echo $_SESSION['email'];
mysql_query("UPDATE users SET password='$newpassword' WHERE email='" . $_SESSION['email'] . "'");
echo '<p class ="alert alert-success fade in">Success! Your password has been updated!</p>';
}
} else{
foreach ($error as $key => $values) {
echo '<p class ="alert alert-error fade in">'.$values.'</p>';
}
}
?>
There is a semicolon which should not be there.
if ($_POST['oldpassword'] != $password);{ // <- remove this semicolon after )
$error[] ='Incorrect current password!';
}
I don't see any addslashes() in your code and am wondering if you get any matches? http://www.php.net/manual/en/function.addslashes.php

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.

Php Form - Error Checking

I have created a form online and when the user clicks submit I want the form to check for error (ie missing field). At the moment I have the form checking the fields one by one and as soon as it encounters a error it will exit without checking the rest of the fields. Is there any way I can combine all the if statements that check for errors into one.
Here is the code
//Code to check that the Student Name field is completed
if(empty($_POST['studentName']))
{
$studentNameError = "You did not enter the student name Wank";
//echo "<h3> $studentNameError </h3>";
exit();
}
//Code to check that the Tutor Name field is completed
if(empty($_POST['tutorName'] ))
{
echo "<h3>You did not select a tutor name. Please go back and select your name from the tutors list</h3>";
exit();
}
//Code to check that the Procedure field is completed
if(empty($_POST['procedure'] ))
{
echo "<h3>You did not select a procedure. Please go back and enter the name of the procedure which you undertook</h3>";
exit();
}
//Code to check that the Grade field is completed
if(empty($_POST['grade'] ))
{
echo "<h3>You did not select a grade. Please go back and select your grade from the drop down list</h3>";
exit();
}
//Code to check that the Student Reflection field is completed
if(empty($_POST['studentReflection'] ))
{
echo "<h3>The student did not enter any comments for this procedure. Student reflection is required for each procedure. Please go back and enter any comments</h3>";
exit();
}
//Code to check if the tick box is checked that the tutor comment is entered
if( !strlen($_POST['tutorComments']) && isset($_POST['alert'] ))
{
echo "<h3>You must enter a reason why you have clicked the alert box</h3>";
exit();
}
For example, you can make a boolean variable to mark, if there is an error, and exit if it's true + combine error messages into one
$error = false;
if(empty($_POST['studentName']))
{
$errorMessages[] = "You did not enter the student name Wank";
$error = true;
}
//Code to check that the Tutor Name field is completed
if(empty($_POST['tutorName'] ))
{
$errorMessages[] = "You did not select a tutor name. Please go back and select your name from the tutors list";
$error = true;
}
//Code to check that the Procedure field is completed
if(empty($_POST['procedure'] ))
{
$errorMessages[] = "You did not select a procedure. Please go back and enter the name of the procedure which you undertook";
$error = true;
}
//Code to check that the Grade field is completed
if(empty($_POST['grade'] ))
{
$errorMessages[] ="You did not select a grade. Please go back and select your grade from the drop down list";
$error = true;
}
//Code to check that the Student Reflection field is completed
if(empty($_POST['studentReflection'] ))
{
$errorMessages[] = "The student did not enter any comments for this procedure. Student reflection is required for each procedure. Please go back and enter any comments";
$error = true;
}
//Code to check if the tick box is checked that the tutor comment is entered
if( !strlen($_POST['tutorComments']) && isset($_POST['alert'] ))
{
$errorMessages[] = "You must enter a reason why you have clicked the alert box";
$error = true;
}
if($error)
{
echo("<h3>".implode('<br/>',$errorMessages)."</h3>");
exit();
}
There are many ways. How about something like this, from top of my head:
$textFieldsThatCannotBeEmpty = array(
'studentName' => 'You did not enter the student name Wank',
'tutorName' => 'You did not select a tutor name. Please go back and select your name from the tutors list',
'procedure' => 'You did not select a procedure. Please go back and enter the name of the procedure which you undertook',
'grade' => 'You did not select a grade. Please go back and select your grade from the drop down list',
'studentReflection' => 'The student did not enter any comments for this procedure. Student reflection is required for each procedure. Please go back and enter any comments'
);
$errors = array();
// check text input fields
foreach($textFieldsThatCannotBeEmpty as $name => $errorMessage){
if(empty($_POST[$name])){
$errors[] = $errorMessage;
}
}
// checkbox
if(!strlen($_POST['tutorComments']) && isset($_POST['alert'])){
$errors[] = 'You must enter a reason why you have clicked the alert box';
}
if(count($errors) > 0){
// form is invalid, print errors
echo '<div class="errors">';
foreach($errors as $e){
echo '<h3>',htmlentities($e),'</h3>';
}
echo '</div>';
}else{
// form is valid, let's go and do something with the submitted data
}
Put all your error messages into an array, and loop through the $_POST. If the input field is empty, then echo the error message:
<?php
$errorMsgs = array(
'studentName' => 'You did not enter a student name',
...
);
$errors = '';
foreach($_POST as $field)
{
if(empty($field))
{
$errors .= $errorMsgs[$field] . '<br/>';
}
}
if(strlen($errors))
{
echo $errors;
exit();
}
This can be done like that (one of the many ways -- really depends on your exact requirements for validation):
<?php
$messages = array();
$errors = 0;
if (empty($_POST['studentName']))
{
$messages['studentName'] = "You did not enter the student name Wank";
$errors++;
}
if (empty($_POST['tutorName']))
{
$messages['tutorName'] = "<h3>You did not select a tutor name. Please go back and select your name from the tutors list</h3>";
$errors++;
}
if ($errors) {
// we have some invalid data in one of the fields
// display error messages (some feedback to user)
foreach ($messages as $v) {
echo $v, "\n";
}
exit();
}
// nope, we are fine
// do whatever else is required
Make a variable named $status for example and and initialize it to 0, at each test assign to it 1 if there is an error, at the end check whether if it is equal to one, exit the script otherwise continue the execution. Or better make an array and for each test assign 0 or 1, depend in the test(the field is not empty assign one else zero) and later you can echo an error message to user indicating the missing fields.

Categories