1

I am having an issue echoing or printing from my PHP to my HTML. I am sure I am missing something basic with how PHP works, however I have been unable to find anything about this issue on the internet or on here. I am very confused, because I am not receiving an errors or any context to the problem at all. The rest of my code works fine, except for echo.

I normally use echo() for testing to ensure stuff exists, however this issue has plagued me during the entire development of this application. It only now bothers me because I will need to echo out a script to load in data (Which I will hide after the load using Vue).

This issue oddly enough only has happened inside of areas where I am using if to do things, especially when it has array_key_exists.

If anyone could help I would appreciate it (Or if someone could provide a better idea for me to transfer json data from PHP to JavaScript other than having to echo it out, since that opens a weak spot in my code for users to cheat my clicker game).

I have tried to test this in other parts of my code with the same results. I cannot use echo() or print() within any if statement. I can use it elsewhere however.

All of my PHP files end up inside of my index.php by usage of require

<?php
    if (array_key_exists("saveData", $_POST)) {
        $saveData = $_POST['saveData'];
        $token = $_COOKIE['validToken'];
        $token = mysqli_real_escape_string($link, $token);
        $query = "UPDATE userData SET saveData = '$saveData' WHERE token = '$token' LIMIT 1";
        mysqli_query($link, $query);
    }
    if (array_key_exists("logSubmit", $_POST)) {
        $email = $_POST["logEmail"];
        $email = filter_var($email, FILTER_SANITIZE_EMAIL); // Clean Email
        $email = filter_var($email, FILTER_VALIDATE_EMAIL); // Confirm Valid Email
        $query = "SELECT saveData FROM userData WHERE email = '$email' LIMIT 1";
        $loadData = mysqli_query($link, $query);
        echo("SALO Ready!");
    }
?>

I would expect for this to echo out "SALO Ready" however I get nothing instead.

EDIT: PHP's white screen of death does not work or apply. Everything else in my application works as expected

UPDATE #1: I have done some testing as recommended, and found that when I echo out of my if statements, one of two things happen

1) The echo() fires, and in the preview under Network on Chrome you can see it their however it does not display in the DOM. This is the case for any if statement that does not meet the below situation.

2) If the echo() is fired from a block used for registering or logging in, it will not display in the preview either. I will be restructuring my code to have those be functions called by the forms when submitted, instead of them just being conditional blocks. While this code is not included in this question, the initial login runs the code below as well to load up user data.

UPDATE #2: I have consolidated my code and followed some recommendations. My code is now inside of functions, that are fired by some if isset conditions. This actually PARTLY fixed my issue. I can echo from all of my functions (Register, Login, Save, Load). Now my issue would appear to be a comment below in relations to output buffering. While my initial question is (Mostly) solved, would anyone be able to help explain how to solve this? I only have ob_start() right now, followed by my functions, if isset conditions, and then everything else in my application. How can I get the echo go to them DOM? I will include the chunk of my code below that will absolutely need to echo out down the road.

EDIT: I have changed how I have ob_start() setup within my code. I call it in the functions that need it and then flush it afterwards. I will be testing with my load script later tonight to try to force the echo() out of the function. Genuinely confused as to why it had not worked in functions but works outside of them, even before this edit

function load() {
    $link = // Link Excluded for Security ;
    if (mysqli_connect_error()) {
        die ("DB Connection Error");
    }
    $email = $_POST["logEmail"];
    $email = filter_var($email, FILTER_SANITIZE_EMAIL); // Clean Email
    $email = filter_var($email, FILTER_VALIDATE_EMAIL); // Confirm Valid Email
    $query = "SELECT saveData FROM userData WHERE email = '$email' LIMIT 1";
    $loadData = mysqli_query($link, $query);
    mysqli_close($link);
    echo("Loading Triggered!");
}
if(isset($_POST['logSubmit'])) {
    login();
    load();
}

As mentioned, this shows the echo() inside of the network tab when I click on primary.php and click preview, it just isn't going to the DOM

Elderis
  • 17
  • 9
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/191885/discussion-on-question-by-elderis-unable-to-echo-or-print-from-php-functions). – Samuel Liew Apr 16 '19 at 05:21

2 Answers2

0

Just use keep your code inside a function and call the function name while post your input

Ex:

function yourFunctionName(){
    if (array_key_exists("saveData", $_POST)) {
        $saveData = $_POST['saveData'];
        $token = $_COOKIE['validToken'];
        $token = mysqli_real_escape_string($link, $token);
        $query = "UPDATE userData SET saveData = '$saveData' WHERE token = '$token' LIMIT 1";
        mysqli_query($link, $query);
    }
    if (array_key_exists("logSubmit", $_POST)) {
        $email = $_POST["logEmail"];
        $email = filter_var($email, FILTER_SANITIZE_EMAIL); // Clean Email
        $email = filter_var($email, FILTER_VALIDATE_EMAIL); // Confirm Valid Email
        $query = "SELECT saveData FROM userData WHERE email = '$email' LIMIT 1";
        $loadData = mysqli_query($link, $query);
        echo("SALO Ready!");
    }
}
Naveen M
  • 89
  • 3
  • Is there a way to fire two functions when the form is submitted? I need to fire a function from this file (salo.php aka SaveLoad) and from another file (reglog.php aka RegisterLogin.php) – Elderis Apr 15 '19 at 04:59
  • you may include the RegisterLogin.php in SaveLoad.php like this ex: include "new.php"; at the starting of the SaveLoad.php file and call the function inside the code – Naveen M Apr 15 '19 at 05:17
  • **Warning:** You are wide open to [SQL Injections](http://php.net/manual/en/security.database.sql-injection.php) and should really use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](http://php.net/manual/en/pdo.prepared-statements.php) or by [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Never trust any kind of input, especially that which comes from the client side. Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). – Dharman Apr 15 '19 at 18:50
0

There is a way to output contents to the DOM when using ob_start by using ob_flush();

ob_start(), when called stores all outputs buffer until instructed to be sent to the browser.

See:

What is Output Buffering?

(The suggested solution provides a re usable function to empty the buffer, sending contents to browser)

How to flush output after echo call

Vahe
  • 1,699
  • 3
  • 25
  • 76
  • Thank you for the suggestions! I see that there is debate on the second question you linked to as to what is and isn't currently working, would you be able to specify here as to what currently works in 2019. I do need the functionality of flushing it and then starting the buffer again though, I do believe. – Elderis Apr 16 '19 at 15:28
  • Answers in the same thread, starting from https://stackoverflow.com/a/46529290/1691103 and following are fairly recent, covering PHP7 as well. – Vahe Apr 16 '19 at 15:33
  • 1
    Alright, I will study on it and test until I get things working. Hopefully it works, this echo is going to be essential to my code as it seems to be the most effective way to get my JSON from PHP to JS – Elderis Apr 16 '19 at 15:38
  • I am not sure how you are retrieving the data in JavaScript, but if the PHP/JS are in one file, then try the two liner at the end of this comment, The first PHP script I wrote needed to get a simple array into JS. So I outputted the array as joined string with commas as the joining character, and I outputted the string version of the array into JS like `var arr = [ echo join(',', ['1','2','3']);?>];` Using JSON as the desired format, a php array can be captured by `var resString = ;` `var resJSON = JSON.parse(resString);` – Vahe Apr 16 '19 at 15:53