Form Validation

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
joselawrence
New php-forum User
New php-forum User
Posts: 14
Joined: Thu Jun 17, 2021 6:39 am

Thu Jun 17, 2021 6:50 am

Some help please, this is my first time working on a project or getting my hands dirty with code.
I am working on a simple php form and the goal is to pass the user input from the submission page to another page which I have successfully achieved, but the problem is that the form is not being validated, though I believe that I implemented the necessary php validation code, the data are still being submitted, whether the user leave the form empty, input less than the minimum character or input the wrong data, the form is be submitted successfully.

I uploaded this practice on github https://github.com/JoseLWal/simplephpform
I have validateform.php, index.php and mssgreceived.php

i) In index.php is the form and I also require validateform.php
ii) In mssgreceived.php is the output and I also require validateform.php
iii) validataform.php contains the form validate code and it is pasted below.

<?php

$username = $email = $issue = $message = "";
$usernamerr = $emailerr = $issuerr = $messagerr = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {

// Validate the username field
if (empty($_POST["username"])) {
$usernamerr = "Please enter your name.";
} elseif(strlen($_POST["username"]) < 3) {
$usernamerr = "Your name must be atleast 3 characters.";
} else {
$username = test_input($_POST["username"]);
// Ensure that username contains only letter and white spaces
if (!preg_match("/^[a-zA-Z-' ]*$/", $username)) {
$usernamerr = "Your name can contain only letters and white spaces.";
}
}

// Validate the email field
if (empty($_POST["email"])) {
$emailerr = "Please enter your email.";
} else {
$email = test_input($_POST["email"]);
// Ensure that email address is proper
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailerr = "Invalid email formart";
}
}

// Validate the issue field
if (empty($_POST["issue"])) {
$issuerr = "Please select an issue.";
} else {
$issue = test_input($_POST["issue"]);
}

// Validate the message field
if (empty($_POST["message"])) {
$messagerr = "Please explain the issue you have.";
} elseif(strlen($_POST["message"]) < 30) {
$usernamerr = "Your message must be atleast 3 characters.";
} else {
$message = test_input($_POST["message"]);
}
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

Thanks in advance
AdoptiveSolution
php-forum GURU
php-forum GURU
Posts: 212
Joined: Wed Jun 15, 2016 8:35 am

Thu Jun 17, 2021 8:16 am

You check for errors, but you do nothing with them.

Add an if statement on line 2 of mssgreceived.php and check if there are no errors.
If not, display the page.
If there are, display the errors and return to the entry form (index.php).
joselawrence
New php-forum User
New php-forum User
Posts: 14
Joined: Thu Jun 17, 2021 6:39 am

Thu Jun 17, 2021 12:23 pm

HI, thanks for the reply.
I discover that the problem is how do I prevent the action page from loading when a data do not match?
and how do I load the same page with the error messages.

If the inputs do not match the data will not be submitted, but once the submit button is clicked, the form is being directed to the mssgreceived.php page.

If is were using PHP_SELF then the would be no redirection.
is the any code that says for example

if(condition) {
action="page.php"
} else {
action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?>";
}
AdoptiveSolution
php-forum GURU
php-forum GURU
Posts: 212
Joined: Wed Jun 15, 2016 8:35 am

Fri Jun 18, 2021 2:02 am

The code at github doesn't work (properly).
So I rearranged it a bit and added some code.
This is the result ;

index.php

Code: Select all

<?php
session_start();
//https://stackoverflow.com/questions/13889198/php-avoid-browser-reposting-post-on-page-refresh/13889283#13889283
if( strcasecmp( $_SERVER['REQUEST_METHOD'],"POST" ) === 0 )
{
	$_SESSION['postdata'] = $_POST;
	header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']);
	exit();
}

if ( !$_SESSION['postdata'] )
{
	//header("Location: register.php");
	//exit();
}

if( isset( $_SESSION['postdata'] ) )
{
	$_POST = $_SESSION['postdata'];
	unset($_SESSION['postdata']);
}
?>
<!DOCTYPE html>
<html>
	<head>
		<title>Form Input</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<link rel="stylesheet" type="text/css" href="style.css">
	</head>
	
	<body>

	<?php
	$usernamerr = '.';
	include('validateform.php');
	//echo '<pre>' . print_r( $_SESSION, TRUE ) . '</pre>';
	if( $usernamerr . $emailerr . $issuerr . $messagerr == '' )
	{
		include('mssgreceived.php');
	} else {
	?>

		<div class="tophead">
		<h1>Simple Form Input</h1>
		<p>Please fill in this form</p>
		</div>
		<div class="input">
			<form method="POST" action="">
				<label for="username">Name: </label><br>
				<input type="text" name="username" value="<?php echo $_POST['username']; ?>" />
				<span class="error">*<br /><?php echo $usernamerr; ?></span><br><br>

				<label for="email">Email: </label><br>
				<input type="email" name="email" value="<?php echo $_POST['email']; ?>" />
				<span class="error">*<br /><?php echo $emailerr; ?></span><br><br>

				<label for="issue">Issue: </label><br>
				<select name="issue">
					<option value="query" <?php     echo $_POST['issue'] == 'query' ? 'selected ' : ''; ?>>Query</option>
					<option value="feedback" <?php  echo $_POST['issue'] == 'feedback' ? 'selected ' : ''; ?>>Feedback</option>
					<option value="complaint" <?php echo $_POST['issue'] == 'complaint' ? 'selected ' : ''; ?>>Complaint</option>
					<option value="other" <?php     echo $_POST['issue'] == 'other' ? 'selected ' : ''; ?>>Other</option>
				</select>
				<span class="error">*<br /><?php echo $issuerr; ?></span>
				<br><br>

				<label for="message">Message: </label><br>
				<textarea name="message" rows="6"><?php echo $_POST['message']; ?></textarea>
				<span class="error">*<br /><?php echo $messagerr; ?></span>
				<br><br>

				<input type="submit" name="Submit">
			</form>
		</div>
	<?php
	}
	?>
	</body>
</html>
mssgreceived.php

Code: Select all

<div class="tophead">
	<h1>Message Received</h1>
</div>

<div class="formoutput">

	<p>Hi <?php echo $username; ?>,</p>

	<p>Thanks for contacting us.</p>

	<p>We will get back to you through your email, <a href="mailto:<?php echo $email; ?>"><?php echo $email; ?></a>, concerning the issue you submitted.</p>

	<h3><?php echo strtoupper($issue); ?></h3>

	<p><?php echo $message; ?></p>

	<p><a href=".">New Message</a></p>

</div>

<?php $usernamerr = $emailerr = $issuerr = $messagerr = ""; ?>
validateform.php

Code: Select all

<?php 
$username = $email = $issue = $message = "";
$usernamerr = $emailerr = $issuerr = $messagerr = "";

//echo '<pre>' . print_r( $_POST, TRUE ) . '</pre>';

// Validate the username field
if ( empty( $_POST["username"] ) )
{
	$usernamerr = "Please enter your name.";
} elseif( strlen( $_POST["username"]) < 3 ) {
	$usernamerr = "Your name must be at least 3 characters.";
} else {
	$username = test_input($_POST["username"]);
	// Ensure that username contains only letter and white spaces
	if ( !preg_match("/^[a-zA-Z-' ]*$/", $username) )
	{
		$usernamerr = "Your name can contain only letters and white spaces.";
	}
}

// Validate the email field
if ( empty( $_POST["email"] ) )
{
	$emailerr = "Please enter your email.";
} else {
	$email = test_input($_POST["email"]);
	// Ensure that email address is proper
	if ( !filter_var($email, FILTER_VALIDATE_EMAIL) )
	{
		$emailerr = "Invalid email format";
	}
}

// Validate the issue field
if ( empty( $_POST["issue"] ) )
{
	$issuerr = "Please select an issue.";
} else {
	$issue = test_input($_POST["issue"]);
}

// Validate the message field
if ( empty( $_POST["message"] ) )
{
	$messagerr = "Please explain the issue you have.";
} elseif( strlen( $_POST["message"] ) < 3 ) {
	$messagerr = "Your message must be at least 3 characters.";
} else {
	$message = test_input($_POST["message"]);
}

function test_input($data)
{
	$data = trim($data);
	$data = stripslashes($data);
	$data = htmlspecialchars($data);
	return $data;
}

?>
User avatar
Strider64
php-forum GURU
php-forum GURU
Posts: 421
Joined: Sat Mar 23, 2013 8:24 am
Location: Livonia, MI
Contact:

Fri Jun 18, 2021 10:23 am

Personally, I like keep HTML and PHP separated as much as possible.

Here's my contact page's HTML

Code: Select all

form id="contact" name="contact" action="contact.php" method="post" autocomplete="on">

        <input id="token" type="hidden" name="token" value="<?= $_SESSION['token'] ?>">
        <label class="labelstyle" for="name" accesskey="U">Contact Name</label>
        <input name="name" type="text" id="name" tabindex="1" autofocus required="required"/>

        <label class="labelstyle" for="email" accesskey="E">Email</label>
        <input name="email" type="email" id="email" tabindex="2" required="required"/>

        <label class="labelstyle" for="phone" accesskey="P">Phone <small>(optional)</small></label>
        <input name="phone" type="tel" id="phone" tabindex="3">

        <label class="labelstyle" for="web" accesskey="W">Website <small>(optional)</small></label>
        <input name="website" type="text" id="web" tabindex="4">

        <label for="message-type">Reason for Writing?</label>
        <select id="message-type" name="reason">
            <option value="message">Message</option>
            <option value="inquiry">Inquiry</option>
            <option value="order">Order</option>
        </select>

        <label class="textareaLabel" for="comments">Comments Length:<span id="length"></span></label>
        <textarea name="comments" id="comments" spellcheck="true" placeholder="Enter Message Here..." tabindex="6"
                  required="required"></textarea>

        <!-- Use a data callback function that Google provides -->
        <div id="recaptcha" class="g-recaptcha" data-sitekey="6LdXNpAUAAAAAMwtslAEqbi9CU3sviuv2imYbQfe"
             data-callback="correctCaptcha"></div>


        <button id="submitForm" type="submit" name="submit" value="Submit" tabindex="7" data-response="">Submit</button>
    </form>
Notice the first line of validation is the require attribute that I deem necessary.

The rest I deal with JavaScript with a little bit of Ajax and PHP :

Code: Select all

'use strict';
/* Convert RGBa to HEX  */
const rgba2hex = (orig) => {
    let a,
        rgb = orig.replace(/\s/g, '').match(/^rgba?\((\d+),(\d+),(\d+),?([^,\s)]+)?/i),
        alpha = (rgb && rgb[4] || "").trim(),
        hex = rgb ?
            (rgb[1] | 1 << 8).toString(16).slice(1) +
            (rgb[2] | 1 << 8).toString(16).slice(1) +
            (rgb[3] | 1 << 8).toString(16).slice(1) : orig;

    if (alpha !== "") {
        a = alpha;
    } else {
        a = "01";
    }
    // multiply before convert to HEX
    a = ((a * 255) | 1 << 8).toString(16).slice(1);
    hex = hex + a;

    return hex;
};

const myColor = (colorcode) => {
    let hexColor = rgba2hex(colorcode);
    return '#' + hexColor;
};

/*
 * Constants & Variables Initialization Section.
 */
const myGreen = myColor("rgba(29, 100, 31, 0.70)"); /* Green with 70% transparency */
const myRed = myColor("rgba(84, 0, 30, 0.50)"); /* Red with 70% transparency */
const myBorder = myColor("rgba(85, 85, 85, 1.00");
const contact = () => {
    const d = document;
    const sendUrl = 'sendMsg.php';
    const submit = d.querySelector('#submitForm');
    const radioBtn = d.querySelector('#message-type');
    const buttons = d.getElementsByName("reason");
    const message = d.querySelector('#message');
    const messageSuccess = d.querySelector('#messageSuccess');

    let name = d.querySelector('#name');
    let email = d.querySelector('#email');
    let phone = d.querySelector('#phone');
    let website = d.querySelector('#web');
    let notice = d.querySelector('#notice');
    let sendEmail = {};
    let sendStatus = {
        name: false,
        email: false,
        comments: false
    };
    sendEmail.reason = 'message';
    sendEmail.token = d.querySelector('#token').value;

    message.style.display = "none";

    let comments = d.querySelector("textarea");
    let output = d.querySelector("#length");

    //d.getElementById('contact').scrollIntoView();


    name.addEventListener('input', () => {
        const value = name.value.trim();

        if (value) {
            name.style.borderColor = myBorder;
            sendEmail.name = name.value;
            sendStatus.name = true;
        } else {
            name.style.borderColor = "red";
            name.value = "";
            name.placeholder = "Name Required";
            name.focus();

        }

    });

    const emailIsValid = (email) => {
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
    };

    email.addEventListener('change', () => {
        let status = emailIsValid(email.value);
        console.log('Email Address', email.value, 'Status', status);
        if (!status) {
            email.value = "";``
            email.placeholder = "Email Address is Invalid!";
            email.style.borderColor = "red";
            email.focus();
        } else {
            email.style.borderColor = myBorder;
            sendEmail.email = email.value;
            sendStatus.email = true;
        }
    });


    /*
     * Selection Element
     */
    buttons.forEach((value, index) => {
        //console.log(value, index);
        buttons[index].addEventListener('change', (e) => {
            sendEmail.reason = e.target.value;
            //console.log('Reason:', sendEmail.reason);
        });
    });


    comments.addEventListener("input", () => {
        output.textContent = comments.value.length;
        const value = comments.value.trim();

        if (value) {
            comments.style.borderColor = myBorder;
            sendEmail.comments = comments.value;
            sendStatus.comments = true;
        } else {
            comments.style.borderColor = "red";
            comments.placeholder = "Message Required!";
            comments.focus();
        }
    });


    /* Success function utilizing FETCH */
    const sendUISuccess = function (result) {
        //console.log('Result', result);
        if (result) {
            d.querySelector('#recaptcha').style.display = "none";
            submit.style.display = "none";
            notice.style.display = "grid";

            notice.textContent = "Email Successfully Sent!";
            notice.style.color = "green";
            message.style.display = "grid";
            //messageSuccess.style.display = "block";
            d.querySelectorAll('form > *').forEach(function (a) {
                a.disabled = true;
            });
        }
    };

    /* If Database Table fails to update data in mysql table */
    const sendUIError = function (error) {
        console.log("Database Table did not load", error);
    };

    const handleSaveErrors = function (response) {
        if (!response.ok) {
            throw (response.status + ' : ' + response.statusText);
        }
        return response.json();
    };

    const saveRequest = (sendUrl, succeed, fail) => {

        fetch(sendUrl, {
            method: 'POST', // or 'PUT'
            body: JSON.stringify(sendEmail)

        })
            .then((response) => handleSaveErrors(response))
            .then((data) => succeed(data))
            .catch((error) => fail(error));
    };

    submit.addEventListener('click', (e) => {
        e.preventDefault();
        sendEmail.phone = phone.value;
        sendEmail.website = website.value;
        sendEmail.response = submit.getAttribute('data-response');
         if (sendStatus.name && sendStatus.email && sendStatus.comments) {
            saveRequest(sendUrl, sendUISuccess, sendUIError);
        } else {
            notice.style.display = "block";
            notice.textContent = "Name, Email, and Message Required!";
        }
    }, false);


};
contact();
If this was something more than a contact form I would have PHP validation as well in case someone disables JavaScript. However, most don't, so I don't worry about it.
Life is a fig newton of your imagination! https://www.phototechguru.com/
joselawrence
New php-forum User
New php-forum User
Posts: 14
Joined: Thu Jun 17, 2021 6:39 am

Fri Jun 18, 2021 10:58 pm

AdoptiveSolution wrote:
Fri Jun 18, 2021 2:02 am

validateform.php

Code: Select all

<?php 
$username = $email = $issue = $message = "";
$usernamerr = $emailerr = $issuerr = $messagerr = "";

//echo '<pre>' . print_r( $_POST, TRUE ) . '</pre>';

// Validate the username field
if ( empty( $_POST["username"] ) )
{
	$usernamerr = "Please enter your name.";
} elseif( strlen( $_POST["username"]) < 3 ) {
	$usernamerr = "Your name must be at least 3 characters.";
} else {
	$username = test_input($_POST["username"]);
	// Ensure that username contains only letter and white spaces
	if ( !preg_match("/^[a-zA-Z-' ]*$/", $username) )
	{
		$usernamerr = "Your name can contain only letters and white spaces.";
	}
}

// Validate the email field
if ( empty( $_POST["email"] ) )
{
	$emailerr = "Please enter your email.";
} else {
	$email = test_input($_POST["email"]);
	// Ensure that email address is proper
	if ( !filter_var($email, FILTER_VALIDATE_EMAIL) )
	{
		$emailerr = "Invalid email format";
	}
}

// Validate the issue field
if ( empty( $_POST["issue"] ) )
{
	$issuerr = "Please select an issue.";
} else {
	$issue = test_input($_POST["issue"]);
}

// Validate the message field
if ( empty( $_POST["message"] ) )
{
	$messagerr = "Please explain the issue you have.";
} elseif( strlen( $_POST["message"] ) < 3 ) {
	$messagerr = "Your message must be at least 3 characters.";
} else {
	$message = test_input($_POST["message"]);
}

function test_input($data)
{
	$data = trim($data);
	$data = stripslashes($data);
	$data = htmlspecialchars($data);
	return $data;
}

?>
AdoptiveSolution
Thanks for the update.
Though I am not familiar with creating session, but I will get on that very soon, but my concern is with the validateform.php

Is it wrong is I use if ($_SERVER["REQUEST_METHOD"] == "POST") { code here } ?
AdoptiveSolution
php-forum GURU
php-forum GURU
Posts: 212
Joined: Wed Jun 15, 2016 8:35 am

Sat Jun 19, 2021 12:54 am

$_SERVER["REQUEST_METHOD"] == "POST" is already executed at the beginning in index.php.

If you want to add $_SERVER["REQUEST_METHOD"] == "POST" to the validateform.php page, you have to remove ALL the PHP code at the beginning of index.php.

You may want to read this to understand the purpose of the code :

https://stackoverflow.com/questions/138 ... 3#13889283
joselawrence
New php-forum User
New php-forum User
Posts: 14
Joined: Thu Jun 17, 2021 6:39 am

Sat Jun 19, 2021 8:10 am

Ok, I now understand that the essence of the code in the top of the index.php is to avoid posting again if the user refresh the page.

The code helps a lot, though it had some warnings:

Code: Select all

<label for="username">Name: </label><br>
<input type="text" name="username" value="<?php echo $_POST['username']; ?>" />
<span class="error">*<br /><?php echo $usernamerr; ?></span><br><br>

<label for="email">Email: </label><br>
<input type="email" name="email" value="<?php echo $_POST['email']; ?>" />
<span class="error">*<br /><?php echo $emailerr; ?></span><br><br>

<label for="issue">Issue: </label><br>
<select name="issue">
    <option value="query" <?php     echo $_POST['issue'] == 'query' ? 'selected ' : ''; ?>>Query</option>
    <option value="feedback" <?php  echo $_POST['issue'] == 'feedback' ? 'selected ' : ''; ?>>Feedback</option>
    <option value="complaint" <?php echo $_POST['issue'] == 'complaint' ? 'selected ' : ''; ?>>Complaint</option>
    <option value="other" <?php     echo $_POST['issue'] == 'other' ? 'selected ' : ''; ?>>Other</option>
</select>
<span class="error">*<br /><?php echo $issuerr; ?></span>
<br><br>

<label for="message">Message: </label><br>
<textarea name="message" rows="6"><?php echo $_POST['message']; ?></textarea>
<span class="error">*<br /><?php echo $messagerr; ?></span>
<br><br>
but I am glad I were able to identify the causes and resolved them, which simply proves that my study in php is paying off.

Code: Select all

<label for="username">Name: </label><br>
<input type="text" name="username" value="<?php if($username) {echo $_POST['username'];} ?>" />
<span class="error">*<br /><?php echo $usernamerr; ?></span><br><br>

<label for="email">Email: </label><br>
<input type="email" name="email" value="<?php if($email) {echo $_POST['email'];} ?>" />
<span class="error">*<br /><?php echo $emailerr; ?></span><br><br>

<label for="issue">Issue: </label><br>
<select name="issue">
    <option value="query" <?php if($issue) {echo $_POST['issue'] == 'query' ? 'selected ' : '';} ?>>Query</option>
    <option value="feedback" <?php if($issue) {echo $_POST['issue'] == 'feedback' ? 'selected ' : '';} ?>>Feedback</option>
    <option value="complaint" <?php if($issue) {echo $_POST['issue'] == 'complaint' ? 'selected ' : '';} ?>>Complaint</option>
    <option value="other" <?php if($issue) {echo $_POST['issue'] == 'other' ? 'selected ' : '';} ?>>Other</option>
</select>
<span class="error">*<br /><?php echo $issuerr; ?></span>
<br><br>

<label for="message">Message: </label><br>
<textarea name="message" rows="6"><?php if($message) {echo $_POST['message'];} ?></textarea>
<span class="error">*<br /><?php echo $messagerr; ?></span>
<br><br>
Example value="<?php echo $_POST['username']; ?>" generated a warning of undefined array key and something like this worked: value="<?php if($username) {echo $_POST['username'];} ?>"

I believe you didn't thought of that, and since you did not test the code, you could not identify it.
Once again thanks a lot.
joselawrence
New php-forum User
New php-forum User
Posts: 14
Joined: Thu Jun 17, 2021 6:39 am

Sat Jun 19, 2021 10:47 pm

Strider64 I am also grateful for the assistance sir.

I do have another issue with the same code and hope to get more assistances.
I am now trying to post to the database using pdo, but this will be done from the mssgreceived.php file, that is when the user submit the form and the action page(mssgreceived.php) has been loaded.

I created a connect.php file which only connects to the database.

Code: Select all

<?php
require "validateform.php";
$val_ok = $username && $email && $issue && $message;
function connect() {
	global $val_ok;
	if ($val_ok) {
		try {
		    $conn = new PDO("mysql:host=localhost;dbname=forminput", "root", "JLWal1234,.");
		// Set Error mode to PDO Exception
			$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		} catch(PDOException $e) {
			echo $e->getMessage();
		}
		return $conn;
	}	
}
?>
then I require it in the mssgreceived.php file, but the problem here is that when I create the pdo query to send the data to the database, I get an error.

Code: Select all

<?php
include "connect.php";
$dbconnect = connect();
try {
	$sql = $conn->prepare("INSERT INTO
	    contactmssg (username, email, issue, message)
	    VALUES (:username, :email, :issue, :message)");
	$sql->bindParam(':username', $username);
	$sql->bindParam(':email', $email);
	$sql->bindParam(':issue', $issue);
	$sql->bindParam(':message', $message);
	$sql->execute();
	echo "Form submitted successfully.";
} catch(PDOException $e) {
	$e->getMessage();
}
?>
---- This is at the top of the other codes in the mssgreceived.php file

I did try other methods but still can't get it and I read a post that told me to put the connection in a function which I did in the connect.php file and then assign that function to a variable in the other file, which I did in the mssgreceived.php file but I am still getting errors.
AdoptiveSolution
php-forum GURU
php-forum GURU
Posts: 212
Joined: Wed Jun 15, 2016 8:35 am

Sun Jun 20, 2021 1:20 am

If you use this :

Code: Select all

$dbconnect = connect();
Then you should use it like this :

Code: Select all

$sql = $dbconnect->prepare(…
joselawrence
New php-forum User
New php-forum User
Posts: 14
Joined: Thu Jun 17, 2021 6:39 am

Sun Jun 20, 2021 11:31 pm

ok, I have resolved that also, thanks again.
joselawrence
New php-forum User
New php-forum User
Posts: 14
Joined: Thu Jun 17, 2021 6:39 am

Wed Jun 23, 2021 10:19 am

Hi, I still have another issue, I am not trying to output the users inputs in a tabular form.
Name, Email, Issue, Messages

I did though, but the problem is with the css. I set the form width to 100%, when I am not outputting anything the form width is 100% on the web page but when I insert the php code to output the form input from the database then it become complicated and the information are all over one another.
joselawrence
New php-forum User
New php-forum User
Posts: 14
Joined: Thu Jun 17, 2021 6:39 am

Sun Jun 27, 2021 11:41 pm

Hi, Some help again please.
I am trying to update the data in the database using pdo.
I were able to sent the data back to the form in the edit.php file and wrote the code to update the data in the database when the form is submitted, but when I make changes and submit, the data are not updated. I don't know what I am doing wrong, please assist me.

Once again the code is here: https://github.com/JoseLWal/simplephpform
I also have the form live here: http://simplesupport.rf.gd/
To view the messages go here: http://simplesupport.rf.gd/messages.php

Thanks a lot for all the assistance
joselawrence
New php-forum User
New php-forum User
Posts: 14
Joined: Thu Jun 17, 2021 6:39 am

Mon Jul 19, 2021 10:15 pm

AdoptiveSolution wrote:
Fri Jun 18, 2021 2:02 am
The code at github doesn't work (properly).
So I rearranged it a bit and added some code.
This is the result ;

index.php

Code: Select all

<?php
session_start();
//https://stackoverflow.com/questions/13889198/php-avoid-browser-reposting-post-on-page-refresh/13889283#13889283
if( strcasecmp( $_SERVER['REQUEST_METHOD'],"POST" ) === 0 )
{
	$_SESSION['postdata'] = $_POST;
	header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']);
	exit();
}

if ( !$_SESSION['postdata'] )
{
	//header("Location: register.php");
	//exit();
}
?>
AdaptiveSolution, Sir, I would really appreciate if you can reply to this comment, or any other assistance would be really appreciated also, as I am stuck up right now.

I believe the code mentioned here is to prevent duplicate entry and also to exit every process and display the error messages when there is an error/errors.

The code has been working very well for me ultil when I decided to upload file.
Because of the

Code: Select all

exit;
I get a warning of undefined array key for the photo and when I try to remove the

Code: Select all

exit;
the error messages are not displayed.

Here is my code

Code: Select all

<?php
session_start();
if (!isset($_SESSION['admin_id'])) {
	header("location:.././");
} else {
	include "../include/connect.php";
	if (strcasecmp($_SERVER['REQUEST_METHOD'], "POST") === 0) {
		$_SESSION['postdata'] = $_POST;
		header("Location: " .$_SERVER['PHP_SELF']. "?" .$_SERVER['QUERY_STRING']);
		exit;
	}

	// Define the add student variables and set to null
	$student_name = $roll_id = $email = $gender = $dob = $class = $photo = "";
	$student_namerr = $roll_iderr = $emailerr = $genderr = $doberr = $classerr = $photoerr = "";
	$status = "active"; // Set the status for newly added student to active.
	$success_notice = "";

	if (isset($_SESSION['postdata'])) {
		$_POST = $_SESSION['postdata'];
		// Validate the add student form
		include "../include/val_function.php";
		if (empty($_POST['student_name'])) {
			$student_namerr = "Student name is required.";
		} else {
			$student_name = val_input($_POST['student_name']);
			if (!preg_match("/^[a-zA-Z-' ].*$/", $student_name)) {
				$student_namerr = "Student name can only contain letters, white spaces and period mark.";
			}
		}
		if (empty($_POST['roll_id'])) {
			$roll_iderr = "Please enter a Roll Identification code for the student.";
		}  else {
			$roll_id = val_input($_POST['roll_id']);
			if (!preg_match("/^[a-zA-Z-0-9-' ]*$/", $roll_id)) {
				$roll_iderr = "Roll Identification code can only contain letters, numbers and hyphen.";
			}
		}
		if (!empty($email)) {
			$email = val_input($_POST['email']);
			if ( !filter_var($email, FILTER_VALIDATE_EMAIL) ) {
				$emailerr = "Invalid email format";
			}
		}
		if (empty($_POST['gender'])) {
			$genderr = "Please select a gender.";
		} else {
			$gender = val_input($_POST['gender']);
		}
		if (empty($_POST['dob'])) {
			$doberr = "Student date of birth is required";
		} else {
			$dob = val_input($_POST['dob']);
		}
		if (empty($_POST['class'])) {
			$classerr = "Please select a class for the student.";
		} else {
			$class = val_input($_POST['class']);
		}
		
			$photo = $_FILES['photo']['name'];
			$photo_temp = $_FILES['photo']['tmp_name'];
			$photo_type = $_FILES['photo']['type'];
			$photo_size = $_FILES['photo']['size'];
			$photo_dir = "../upload/" .$photo;
			if ($photo_type=="image/jpg" || $photo_type=="image/jpeg" || $photo_type=="image/png") {
				if ($photo_size < 5000000) {
					if (!file_exists($photo_dir)) {
						move_uploaded_file($photo_temp, $photo_dir);
					} else {
						$photoerr = "Photo already exist.";
					}
				} else {
					$photoerr = "Photo is too large";
				}
			} else {
				$photoerr = "Only jpg, jpeg and png images are allowed.";
			}
		
		try {
			include "../include/connect.php";
			$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$query = "SELECT * FROM students WHERE student_name=:student_name OR roll_id=:roll_id OR student_email=:email";
			$stmt = $conn->prepare($query);
			$stmt->bindParam(':student_name', $student_name);
			$stmt->bindParam(':roll_id', $roll_id);
			$stmt->bindParam(':email', $email);
			$stmt->execute();
			$count = $stmt->rowCount();
			$result = $stmt->fetchAll();
			foreach ($result as $result) {
				if ($count == 1 && $student_name == $result['student_name']) {
					$student_namerr = "Student already exist.";
				}
				if ($count == 1 && $roll_id == $result['roll_id']) {
					$roll_iderr = "Roll Identification code already exist";
				}
				if (!empty($email) && $count == 1 && $email == $result['student_email']) {
					$emailerr = "Email already exist";
				}
			}
			$data_ok = empty($student_namerr || $roll_iderr || $emailerr || $genderr || $doberr || $classerr || $photoerr);
			if ($data_ok) { // Submit the data
				$query = "INSERT INTO students (student_name, roll_id, student_email, gender, dob, class_id, student_photo, student_photo_location, student_photo_type, status)
				VALUES (:student_name, :roll_id, :email, :gender, :dob, :class, :student_photo, :student_photo_location, :student_photo_type, :status)";
				$stmt = $conn->prepare($query);
				$stmt->bindParam(':student_name', $student_name);
				$stmt->bindParam(':roll_id', $roll_id);
				$stmt->bindParam(':email', $email);
				$stmt->bindParam(':gender', $gender);
				$stmt->bindParam(':dob', $dob);
				$stmt->bindParam(':class', $class);
				$stmt->bindParam(':student_photo', $photo);
				$stmt->bindParam(':student_photo_location', $photo_location);
				$stmt->bindParam(':student_photo_type', $photo_type);
				$stmt->bindParam(':student_photo', $photo);
				$stmt->bindParam(':status', $status);
				$stmt->execute();
				$success_notice = "New student added successfully";
			}
		} catch(PDOException $e) {
			echo "Error: " .$e->getMessage();	
		} 
	}
	unset($_SESSION['postdata']);
}
?>
<!DOCTYPE html>
<html>
<head>
	<title>Add New Student</title>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" type="text/css" href="../css/style.css">
	<link rel="stylesheet" type="text/css" href="../css/menubar.css">
	<link rel="stylesheet" type="text/css" href="../css/input.css">
</head>
<body>
	<?php include "include/topbar.php"; ?>
	<div id="bottom">
		<?php include "include/sidebar.php"; ?>
		<div>
			<div id="head">
				<h1>Add Students</h1>
			</div>
			<div id="body">
				<div id="input">
					<form method="post" enctype="multipart/form-data">
						<?php echo $success_notice; ?>
						<table>
							<tbody>
								<tr>
									<td><label for="student_name">Student Name: </label></td>
									<td>
										<input type="text" name="student_name">
										<span class="error">* <br><?php echo $student_namerr; ?></span>
									</td>
								</tr>
								<tr>
									<td><label for="roll_id">Roll Id: </label></td>
									<td>
										<input type="text" name="roll_id">
										<span class="error">*<br><?php echo $roll_iderr; ?></span>
									</td>
								</tr>
								<tr>
									<td><label for="email">Email: </label></td>
									<td>
										<input type="email" name="email">
										<span class="error"><br><?php echo $emailerr; ?></span>
									</td>
								</tr>
								<tr>
									<td><label for="gender">Gender: </label></td>
									<td>
										<input type="radio" name="gender" value="male"> Male
										<input type="radio" name="gender" value="female"> Female
										<span class="error">*<br><?php echo $genderr; ?></span>
									</td>
								</tr>
								<tr>
									<td><label for="dob">Date of Birth: </label></td>
									<td>
										<input type="date" name="dob">
										<span class="error">*<br><?php echo $doberr; ?></span>
									</td>
								</tr>
								<tr>
									<td><label for="class">Class: </label></td>
									<td>
										<select name="class">
											<option value="">Select class</option>
											<?php
											try {
												$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
												$query = "SELECT * FROM classes";
												$stmt = $conn->prepare($query);
												$stmt->execute();
												$count = $stmt->rowCount();
												$result = $stmt->fetchAll();
												if ($count > 0) {
													foreach ($result as $result) {
											?>
											<option value="<?php echo $result['class_id']; ?>"><?php echo $result['class_name'] ?></option>
											<?php
													}
												}
											} catch(PDOException $e) {
												echo "Error: " .$e->getMessage();
											}
											?>
										</select>
										<span class="error">*<br><?php echo $classerr; ?></span>
									</td>
								</tr>
								<tr>
									<td><label for="photo">Photo: </label></td>
									<td>
										<input type="file" name="photo">
										<span class="error">*<br><?php echo $photoerr; ?></span>
									</td>
								</tr>
								<tr><td><button type="submit">Add Student</button></td></tr>
							</tbody>
						</table>
					</form>	
				</div>
			</div>
		</div>
	</div>
</body>
Thanks in advance
Post Reply