0

I'm using PHP, HTML, and MySQL to create a web page that lets users create text posts. I would like to avoid js and ajax for now.

When calling the function "post" from (post.php) the system is unable to complete the post. Removing the function line in (includes/post.inc.php) lets the user post correctly. I want to have the function line so I can reference multiple methods on this file. What am I messing up for the call of this function?

Here is the relevant information from post.php

    <?php
        require 'includes/dbh.inc.php';
        require 'includes/post.inc.php';
        session_start();
        date_default_timezone_set('America/Chicago');
        .
        . 
        echo '
            <form action="'.post($conn).'" method="post">
                <label for="text">New Post</label>
                <input type="text" name="Text" placeholder="Write your post here">
                <input type="hidden" name="Date" value="'.date("Y-m-d H:i:s").'">
                <br>
                <button type="submit" name="postSubmit">Post</button>
            </form>
        ';
    ?>

Then here is the post function from includes/post.inc.php

<?php

function post($conn) {  // deleting this line allows my code to run correctly
    session_start();
    if (isset($_POST['postSubmit'])) {
        require 'dbh.inc.php';
        $UserID = $_SESSION['UserID'];
        $Date = $_POST['Date'];
        $Text = $_POST['Text'];
        $SectionID = 1;
        // make a random value for $postID and then see if it exists in the DB
        $PostIDLength = 11;
        $PostIDString = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $PostIDDuplicate = true;
        while ($PostIDDuplicate = true) {
            $PostID = substr(str_shuffle($PostIDString), 0, $PostIDLength); //shuffle String, start with 0, 11 characters long
            $PostIDSQL = "SELECT PostID FROM PostTable WHERE PostID = ?";
            $PostIDStmt = mysqli_stmt_init($conn);
            if (!mysqli_stmt_prepare($PostIDStmt, $PostIDSQL)) {
                exit();
            }
            else {
                mysqli_stmt_bind_param($PostIDStmt, "s", $PostID);
                mysqli_stmt_execute($PostIDStmt);
                $PostIDResult = mysqli_stmt_get_result($PostIDStmt);
                $PostIDResultCheck = mysqli_num_rows($PostIDResult);
                if ($PostIDResultCheck <= 0) {
                    $PostIDDuplicate = false;
                    break;
                }
                else {
                    // repeat until you have a unique ID
                }
            }               
        }
        $PostSQL = "INSERT INTO PostTable (PostID, UserID, SectionID, Date, Text) VALUES (?, ?, ?, ?, ?)";
        $PostSTMT = mysqli_stmt_init($conn);
        if (!mysqli_stmt_prepare($PostSTMT, $PostSQL)) {
            echo 'Error2';
        }
        else {
            mysqli_stmt_bind_param($PostSTMT, "ssiss", $PostID, $UserID, $SectionID, $Date, $Text);
            mysqli_stmt_execute($PostSTMT);
        }
        header('Location: ../home');
        exit();
    }
    else {
        header("Location: ../home.php?error");
        exit();
    }
}   
adamcapjones
  • 185
  • 1
  • 17
  • 1
    Where did you call the function? – Don't Panic Apr 12 '22 at 19:21
  • in post.php user submits a form that should call the post function. – adamcapjones Apr 12 '22 at 19:31
  • 1
    A script loading doesn't execute a function. You need `post($conn);` to invoke the function, you also will need `$conn` defined somewhere. See https://3v4l.org/6PhRf for simple demo – user3783243 Apr 12 '22 at 19:37
  • I see the function is defined there, but it won't be executed automatically. It needs to be called somewhere with `post($some_argument)`. (It looks like it's supposed to take a mysqli connection as an argument, but since it works when you delete the function line I assume that `$conn` variable that's used later is defined in the required dbh file.) – Don't Panic Apr 12 '22 at 19:37
  • I have added the call using post($conn) *See revised code above Now when I load the page, I the input field is not rendering – adamcapjones Apr 12 '22 at 19:41
  • 1
    You cannot have the function has the form action. PHP processes the page and sends it to the browser, at which point it is done with it. In order to use PHP again, you either need the action to submit the form to a PHP page that will do the processing (either the same page or a different page, that is up to you) or use ajax to submit the form. – aynber Apr 12 '22 at 19:56
  • It looks like post.php could just be HTML. You can capture the date on the PHP side, or you require it from client when page is loaded, rather than submitted? (Note user also could change date with current approach). I don't see a need for `post()`, why not just have the PHP execute as is; are other processes going to use `post` as well? – user3783243 Apr 13 '22 at 14:16
  • At this point I will just have a completely separate file for running functions. I could not figure out how to run this code as a function. – adamcapjones Apr 14 '22 at 17:23

1 Answers1

0

You're not calling the post function on includes/post.inc.php with the submit, just declaring it.

I recommend to use an jquery/ajax call on form submit:

$('#postSubmit').on('click', function() {
    
    var text = $("#Text").val();
    var date= $("#Date").val();
    var action = 'createpost';
    $.ajax({
      type: "POST",
      url: 'includes/post.inc.php',
      data: ({
        action : action,
        text : text,
        date: date
      }),
      success: function(data) {
               console.log("do something")
      } 
    });
});

Just add Ids to the inputs and the submit button