0

I'm trying to follow Lynda's PHP tutorial and I'm stuck with the validations for the pages CRUD. I've been trying to figure out what went wrong but I can't seem to find where the error is coming from even though it's already stated in error. I'm confused because I'm using the same validation for creating subject and it executes just fine but with for creating page, I'm getting the error - Notice: Undefined index: visible in D:\wd-stuff\ampps\www\cms.widgetcorp\includes\validation.php on line 14.

Below is the full code that I'm working on.

PS: I have a radio input named visible.

PS2: I've read the link that tackled the Undefined index but it didn't answer my question. The same validation works fine from another form (new_subject.php) which is basically the same as the new_page.php.

new_page.php

    require_once '../includes/session.php';
    require_once '../includes/functions.php';
    require_once '../includes/connection.php';
    require_once '../includes/validation.php';

    getSelectedContent();

    if (!$is_subject) {
        redirect_to("manage_content.php");
    }

    if (isset($_POST['submit'])) {

        // validations

        $req_fields = array("menu_name", "position", "visible", "content");
        validatePresence($req_fields);
        $field_with_length = array ("menu_name" => 30);
        validateLenght($field_with_length);


        if (empty($errors)) {

            $s_id = $is_subject['id'];
            $menu_name = mysqlPrep($_POST['menu_name']);
            $position = (int) $_POST['position'];
            $visible = (int) $_POST['visible'];
            $content = mysqlPrep($_POST['content']);

            $qry  = "INSERT INTO pages (";
            $qry .= " subject_id, menu_name, position, visible, content";
            $qry .= ") VALUES (";
            $qry .= " {$s_id}, '{$menu_name}', {$position}, {$visible}, '{$content}'";
            $qry .= ")";
            $result = mysqli_query($conn, $qry);

            if ($result) {
                $_SESSION['msg'] = "Page added.";
                redirect_to("manage_content.php?subject=" . urlencode($is_subject['id']));
            } else {
                $_SESSION['msg'] = "Page Creation Failed";
            }

        }
    } 

    include_once '../includes/layouts/header.php';

validation.php

$errors = array();

function isDataPresent($value)
{
    return (isset($value) && $value !== "");
}

function validatePresence($fields)
{
    global $errors;

    foreach ($fields as $field) {
        $value = trim($_POST[$field]);
        if (!isDataPresent($value)) {
            $errors[$field] = str_replace("_", " ", ucfirst($field)) . " can't be blank";
        }
    }   
}

function isLengthValid($value, $max)
{
    return (strlen($value) <= $max);
}

function validateLenght($fields)
{
    global $errors;
    foreach ($fields as $field => $max) {
        $value = trim($_POST[$field]);
        if (!isLengthValid($value, $max)) {
            $errors[$field] = str_replace("_", " ", ucfirst($field)) . " is too long";
        }
    }
}

I've also thought of just combining the two. But the main goal of my post is to understand why the validation works to one form but not with the other which is basically the same.

new_subject.php

require_once '../includes/session.php';
require_once '../includes/functions.php';
require_once '../includes/connection.php';
require_once '../includes/validation.php';

if (isset($_POST['submit'])) {
    $menu_name = mysqlPrep($_POST['menu_name']);
    $position = (int) $_POST['position'];
    $visible = (int) $_POST['visible'];

    // validations

    $req_fields = array("menu_name", "position", "visible");
    validatePresence($req_fields);
    $field_with_length = array ("menu_name" => 30);
    validateLenght($field_with_length);


    if (!empty($errors)) {
        $_SESSION['errors'] = $errors;
        redirect_to('new_subject.php');
    }

    $qry  = "INSERT INTO subjects (";
    $qry .= "menu_name, position, visible";
    $qry .= ") VALUES (";
    $qry .= " '{$menu_name}', $position, $visible";
    $qry .= ")";
    $result = mysqli_query($conn, $qry);

    if ($result === false) {
        $_SESSION['msg'] = "Subject Creation Failed";
        redirect_to("new_subject.php");
    }

    $_SESSION['msg'] = "Subject Created";
    redirect_to("manage_content.php");

} else {
    redirect_to("new_subject.php");
}

subject form

<form action="create_subject.php" method="post">
            <p>Menu name: 
                <input type="text" name="menu_name" value="">
            </p>
            <p>Position: 
                <select name="position">
                <?php
                    $subject_set = getAllSubjects();
                    $subject_cnt = mysqli_num_rows($subject_set);
                    for ($cnt = 1; $cnt <= $subject_cnt + 1; $cnt++) {
                        echo "<option value=\"{$cnt}\">{$cnt}</option>";
                    }
                ?>
                </select>
            </p>
            <p>Visible: 
                <input type="radio" name="visible" value="0"> No
                &nbsp;
                <input type="radio" name="visible" value="1"> Yes
            </p>
            <input type="submit" name="submit" value="Create Subject">
        </form>

page form

<form action="new_page.php?subject=<?= urlencode($is_subject['id']); ?>" method="post">
            <p>Menu name: 
                <input type="text" name="menu_name" value="">
            </p>
            <p>Position: 
                <select name="position">
                <?php
                    $page_set = getAllPages($is_subject['id']);
                    $page_cnt = mysqli_num_rows($page_set);
                    for ($cnt = 1; $cnt <= $page_cnt + 1; $cnt++) {
                        echo "<option value=\"{$cnt}\">{$cnt}</option>";
                    }
                ?>
                </select>
            </p>
            <p>Visible: 
                <input type="radio" name="visible" value="0"> No
                &nbsp;
                <input type="radio" name="visible" value="1"> Yes
            </p>
            <p>Content: <br>
                <textarea rows="20" cols="80" name="content"></textarea>
            </p>
            <input type="submit" name="submit" value="Create Page">
        </form>[Validation error that I'm trying to reproduce][1]
Oversoul
  • 51
  • 6
  • 2
    Possible duplicate of [PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef) – aynber Feb 13 '17 at 21:55

1 Answers1

0

That's because of a bug in the validatePresence() function, which tries to check a value against a condition, when the value could be not set, hence why the E_NOTICE is thrown. Change the code of that function to this:

function validatePresence($fields)
{
    global $errors;

    foreach ($fields as $field) {
        if (!isset($_POST[$field]) || trim($_POST[$field]) == '') {
            $errors[$field] = str_replace("_", " ", ucfirst($field)) . " can't be blank";
        }
    }   
}

Then, you can safely delete the isDataPresent() function code, as it's not really needed anymore after this change.

ablopez
  • 850
  • 4
  • 7
  • thank you for your reply. I've edited my post and added the other form processing that i was talking about. – Oversoul Feb 13 '17 at 22:24
  • I see. Can you update your question by posting the HTML of the 2 forms you mention? The one that works, and the one that throws the error. – ablopez Feb 13 '17 at 22:55
  • Subject form is the one that is working. page form is the one where I'm getting the error. – Oversoul Feb 13 '17 at 23:16
  • Did you change the validatePresence() code as per my suggestion and you're still getting the error? Also, before submitting, are you selecting one of the two radio inputs in the page form? – ablopez Feb 13 '17 at 23:22
  • I haven't changed the function as I'm trying to understand why it won't validate the fields the same it did with the other form. And no, I didn't select any of the radio input and as a result it should return an error message that 'Visible field can't be blank', just like the subject form. But for some reason the same validation is not working with the page form. – Oversoul Feb 13 '17 at 23:32
  • The only possible reason is that one of the includes in the subject form is changing the error reporting level of PHP to disable E_NOTICE. So, I'd recommend looking into those includes to ensure one or more of them aren't doing this, while also changing the code for the validatePresence() function and removing the isDataPresent() function as per my answer, to fix the real issue and simplify the code. – ablopez Feb 13 '17 at 23:36