简体   繁体   中英

Php pdo insert array from form

Through tutorial I created html form that inserts data into database. It works great, but in tutorial it is not explained why they use such code for array list.

$db = new PDO("mysql:host=localhost;dbname=test", "test_user", "test123");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if(isset($_POST['btn-add']))
{
    $fields= (is_array($_POST['fields'])) ? $_POST['fields'] : array();
    $insertStmt = $db->prepare("INSERT INTO test (test_field) VALUES (:field)");

    foreach ($fields as $field) {
        $insertStmt->execute(array('field' => $field));
    }
}

<form action="" method="POST">
    <label>field 1 <input type="text" name="fields[0]"></label>         
    <label>field 2 <input type="text" name="fields[1]"></label>
    <button type="submit" name="btn-add">add</button>
</form>

My question is about this line. Maybe someone could explain it.

$products = (is_array($_POST['fields'])) ? $_POST['fields'] : array();

What this line do - ? $_POST['fields'] : array();

Why it does not work just with $products = (is_array($_POST['fields']))

Also is this a good way to create array insert from form or I should search for different tutorial?

The line you mentioned sets the variable $products to an array, no matter if there are data is given via the form or not.

$products = (is_array($_POST['fields'])) ? $_POST['fields'] : array(); 

says "If $_POST['fields'] is an array, then set $products to this given array, otherwise set $products as an empty array".

For further information on the ternary operator you can have a look here: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary

This ensures, that the following code

foreach ($fields as $field) {
    $insertStmt->execute(array('field' => $field));
}

doesn't raise a Warning like

WARNING Invalid argument supplied for foreach() on line number ...

Hope this helps :)

$fields = (is_array($_POST['fields'])) ? $_POST['fields'] : array();

Explanation

If $_POST['fields'] is an array, the condition evaluates to true . If the condition is true, the expression $_POST['fields'] before : will be assigned to the variable $fields otherwise the expression array() after : will be assigned.

The syntax goes like:

$var = condition ? expr1 : expr2;

To make you more clear, here it is:

$a = 10;
$b = 20;    
$c = $b > $a ? $b : $a;

Here, we check the condition if $b is greater than $a , if it is true, $b 's value is assigned to $c , if it is false, $a 's value is assigned.

This is how ternary expression works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM