dotty
dotty

Reputation: 7

How to substitute $_POST inputs with fgets(STDIN) in PHP

I want to create PHP CLI CRUD Application. I started by simply creating MySQL connection and writing basic CRUD functions. Now I want to be able to accept data using PHP CLI, so I need to substitute $_POST with fgets(atleast, I think so). Never dealed with that before, so would appreciate any help.

<?php

echo "Welcome to Company Register App" . "\n\n";

//establish database connection
define("DB_SERVER", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "root");
define ("DB_NAME", "mydatabase");

$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
if($mysqli === false) {
    echo "Sorry, there seems to be a connection issue.";
} else {
    echo "We are connected". "\n\n";
}

//register function
function addCompany() {

    $name = "";
    $code = "";
    $phone = "";
    $comment = "";
    $id = 0;
    $update = false;

    if (isset($_POST['save'])) {
        $name = $_POST['name'];
        $code = $_POST['code'];
        $phone = $_POST['phone'];
        $comment = $_POST['comment'];

        mysqli_query($mysqli, "INSERT INTO mydatabase (name, code, email, phone, comment) VALUES ('$name', '$code', '$phone', '$comment')"); 

    }
}

?>

I expect to be able to run this file and be prompted to enter info.

Thank you!

Upvotes: 0

Views: 153

Answers (1)

MilanG
MilanG

Reputation: 7114

Check for $argc and $argv variables. $argc should contain number of passed parameters and $argv is the array that contains passed parameters:

https://www.igorkromin.net/index.php/2017/12/07/how-to-pass-parameters-to-your-php-script-via-the-command-line/

Check it on php.net:

https://www.php.net/manual/en/reserved.variables.argv.php

https://www.php.net/manual/en/reserved.variables.argc.php

But also check ont getopt() function:

https://www.php.net/manual/en/function.getopt.php

Upvotes: 1

Related Questions