JordyvD
JordyvD

Reputation: 1615

php array to pdo variables

Here's what i'm trying to achieve: i'm learning OOP for school and i have tp make a registration thingy.... it's working but a lot is hardcoded and i'd like to make an universal insert function which works like $class->insert "1, 2, 3", "foo, bar, thing" where it'll insert foo into 1 bar into 2 and thing into 3 here comes the problem: i don't know how to convert my PHP array into SQL variables because i do not know how many items there are in my PHP array. (due to an explode)

here's my code so far:

<?php

 class database
{
static protected $_connection;

public function __construct($host, $dbname, $username, $password)
{
    self::$_connection = new PDO("mysql:host=" . $host . ";dbname=" . $dbname, $username, $password);
    self::$_connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return self::$_connection;

}

public function insert($tablename, $columns, $values)
{
    $exploded = explode(", ", $values);
    $valuenumber = NULL;
    $string = NULL;
    $teller = 0;


    $query = self::$_connection->prepare('INSERT INTO gebruikers (:naam) VALUES ');
    foreach ($exploded as $array) {
        $query->bindparam(":value" . $valuenumber, $array);
        $valuenumber++;
    }
    for ($i = $valuenumber; $i > 0; $i--) {
        $string .= ", :value" . $teller;
        $teller++;
        // alles wordt in een string gezet: ":value, :value1, :value2
    }
    $stringarray = explode($string, ", ");
    $query->execute(array(
        'naam' => $teller
    ));
}

}



$client = new database("localhost", "oop", "root", "");
$client->insert("gebruikers", "naam", "test");

I'm sorry if it's a bit messy and for the lack of comments i'm pretty new in this.

Could anyone please help me out a bit? thanks,

g3.

Upvotes: 0

Views: 513

Answers (1)

Prisoner
Prisoner

Reputation: 27628

public function insert($table, $columns, $values)
{
    // make sure we have the same amount of keys and values
    if(count($columns) !== count($values)){
        return false;
    }

    $query = self::$_connection->prepare('INSERT INTO ' . $table . ' (' . implode(',', $columns) . ') VALUES (:' . implode(',:', $columns) . ')');

    $index = 0;
    foreach($columns as $column){
        $query->bindparam(":" . $column . $values[$index++]);
    }

}

If I were you, I'd get rid of passing $columns and $values separately and just pass a key => pair array like:

array('id' => 1, 'name' => 'new name');

I understand this is a learning process for you're sort of re-inventing the wheel here. Check out libraries like doctrine.

Upvotes: 1

Related Questions