Hello, I'm trying to understand a general CRUD class that I've seen here:
http://www.phpro.org/classes/PDO-CRUD.html

I'm learning PHP and I have some doubts on this method to generally insert
data into DB. The class name is crud and here is the method: 

public function dbInsert($table, $values) {

        $this->conn();

        $fieldnames = array_keys($values[0]);

        $size = sizeof($fieldnames);
        
        $i=1;
        
        //construction of the prepared statment
        $sql = "INSERT INTO $table";

        $fields = '( ' . implode(' ,', $fieldnames) . ' )';

        $bound = '(:' . implode(', :', $fieldnames) . ' )';

        $sql .= $fields.' VALUES '.$bound;
        
        //prepares statement e saves it on variable $stmt
        $stmt = $this->db->prepare($sql);

        foreach($values as vals)
        {
                $stmt->execute($vals);
        }
}


To place values on the DB we do:

$crud = new crud();

$values = array
            (
                array('animal_name'=>'bruce', 'animal_type'=>'dingo'),
                array('animal_name'=>'bruce', 'animal_type'=>'kangaroo'),
            );

$crud->dbInsert('animals', $values);





The doubts:
1) Names convention question: 
Isn't more correct to call $columname, instead of $fieldname ? 

2) Why do we have this?
 $i=1  


3) Here: 
$fieldnames = array_keys($values[0]);

We are keeping on variable $fieldnames, the key value of the $values array,
when this array is on the position 0 ? And what is *actually* the value
returned, considering our array?
 
$values = array
            (
                array('animal_name'=>'bruce', 'animal_type'=>'dingo'),
                array('animal_name'=>'bruce', 'animal_type'=>'kangaroo'),
            );


4) Here:
foreach($values as $vals)
        {
                $stmt->execute($vals);
        }

We are telling that, for each (line/element/index ???) of $values array, the
actual value will be "given"(?) to vals, and the pointer goes to the next
(line/element/index)... ?

We then execute the prepared statement, but I don't get what are we passing
as a param? I mean, what kind of think does the execute PDO method expects
as a param? 
Why $stmt->execute($vals); and not only $stmt->execute(); ?


Can I please have your help on clarifying those doubts?


Thanks a lot,
Márcio


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to