The default value for $ _POST [];

I have a problem with the default value for $ _POST []; So, I have an html form with text fields, and the information is sent to a php script. The PHP script has a sql query that is sent to my database. But if my html text file is empty, the request doesn't matter. So I want my message to be assigned a default value of 0, so it returns a value at least.

So here is an example html form (this is not my script application). Just an example.

<form action="testscript.php" method="POST">
    <input type="id" name="ID"/>
    <input type="text" name="test"/>
    <input type="submit" value="Send"/>
</form>

Ok, so this script will send both identifiers and the test text fields will always have a numeric value. And it sends the information to testcript.php

Here is an example testcript.php

    $conn = mysqli_connect('host', 'dbuser', 'dbpass', 'dbname');
    $id = $_POST['id'];
    $test = $_POST['test'];
    $sql = "INSERT INTO test_table (id, test) VALUES ($id, $test)";

    if (mysqli_query($conn, $query)) {
        echo "Success";
    } else {
        echo "Failed" . mysqli_error($conn);
    }

, , html php script , :

INSERT INTO test_table (id, test) VALUES ( , )

:

INSERT INTO test_table (id, test) VALUES (0, 0)

. , value html, , .

, , statment ,

if (isset($_POST['test'])) {
    $test = $_POST['test'];
} else {
    $test = 0;
}

, , statment html- 100 . , statment , script , .

, , statment php value html?

+4
2

, , , . , .

$id = isset($_POST['id']) ? $_POST['id'] : 0;
$test = isset($_POST['test']) ? $_POST['test'] : 0;

....

, .

, PHP

$fields = array('id', 'test', 'extra', 'more', ..., 'one_hundred');

, - - 0 (). / "" ( )

foreach($fields as $field_name)
{
   ${$field_name} = isset($_POST[$field_name]) ? mysqli_real_escape_string($conn, $_POST[$field_name]) : 0;
}

$id, $test, $extra, $more,...., $one_hundred, .

+5

, , , ,

isset($_POST["test"]) ? $_POST["test"] : 0

, :

<input type="checkbox" name="courses[]" value="1">
<input type="checkbox" name="courses[]" value="2 >

:

foreach($_POST['courses'] as $course) {
    echo $course; // etc etc etc 
}

.

: SQL-. , , , , . PDO .

0

Source: https://habr.com/ru/post/1618175/


All Articles