vendredi 9 octobre 2015

How to create PDO Insert statemet, from looped key and value array

from POST method like "$uri = explode("&", $_SERVER["QUERY_STRING"]);" i can retrieve the value that i need for insertion operation. Thats is ok. Also i have a constructor function that call another function that return PDO for my sqlite connection:

 private function dbConnect()
{
    try {
        $this->db = new PDO('sqlite:model.sqlite3');
        $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch (PDOException $e) {
        echo $e->getMessage();
    }
    return $this->db;

}

This method has been tested with GET and is ok. Now i want to insert into table new record by URI Calls

private function disciplines(){
        // Cross validation if the request method is POST else it will return "Not Acceptable" status
        if($this->get_request_method() != "PUT"){
            $this->response('',406);
        }
        $uri= array();
        //echo "The query string is: ".$_SERVER['QUERY_STRING']; 
        $uri = explode("&", $_SERVER["QUERY_STRING"]);
        if(uri){  

        $aAttributi= array();
        $aAttributi2= array();
        foreach ($uri as $var_val) {
        $var_val = explode('=', $var_val);
        $var[]= $var_val[0];
        $val[]= $var_val[1];

        }

        array_shift($var);
        array_shift($val);
        //shift arry is for esclude first element on arrays
        $sTable= implode(',', $var);
        $sValue= implode(',', $val);

        print_r(array_values($var));
        print_r(array_values($val));

// OUTPUT:

 Array //array1
(
    [0] => discipline
    [1] => Material
)
Array // array 2
(
    [0] => sword
    [1] => Iron
)

Final desire step:

$qry = $this->db->exec(
        'INSERT INTO disciplines ($sTable) VALUES ($sValue)');
        echo $qry;

Does not work!!! Two problem: Please con you put me in right directon? any help is largely valued. Are

 echo $qry;
 'INSERT INTO discipline (Array) VALUES (Array)');

 basically I want:
 INSERT INTO disciplines (discipline, material ) VALUES (sword, iron )');

Thank you for your time and please if you don't want to help me it's ok, but don't down vote.

Aucun commentaire:

Enregistrer un commentaire