OOP PHP PDO Dynamic Insert

Hi,
I’m quite new to OOP PHP and i’m trying to make a dynamic insert function , i’ve followed an example on Stackoverflow to do so since its my first try at making something dynamic. http://stackoverflow.com/a/13333344/3559635
It works but im still quite confused about the two foreach loops , and if possible could someone explain that part to me please and or is there an easier way to do this for a new guy like me?

Im sending my POST values from the index.php
[php]<?php
include(“Database.php”);

$db = new Database();
var_dump($db);

$table = “users”;
$whitelist = array(‘username’, ‘password’);
$data = array_intersect_key($_POST, array_flip($whitelist));

if(isset($_POST[‘username’]) AND ($_POST[‘password’]))
{
$db->postTesting($data, $table);
}
else
{
echo “Please fill in everything!”;
}[/php]

Database.php
[php]

<?php class Database { private $connection; private $typedb = "mysql"; private $host = "127.0.0.1"; private $dbname = "oopphp"; private $username = "root"; private $password = ""; public function __construct() { try{ $this->connection = new PDO($this->typedb. ":host=".$this->host. ";dbname=".$this->dbname, $this->username, $this->password); $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $this->connection; } catch(PDOException $e) { throw new Exception("Connection failed: ".$e->getMessage()); } } public function postTesting($data, $table) { try{ //var_dump($table, $data); $columns = ""; $holders = ""; foreach ($data as $column => $value) { //var_dump($column); //var_dump($value); $columns .= ($columns == "") ? "" : ", "; $columns .= $column; $holders .= ($holders == "") ? "" : ", "; $holders .= ":$column"; //var_dump($columns); //var_dump($holders); } $sql = "INSERT INTO $table ($columns) VALUES ($holders)"; //return $sql; $stmt = $this->connection->prepare($sql); //var_dump($stmt); foreach ($data as $placeholder => $value) { $stmt->bindValue(":$placeholder", $value); //var_dump($stmt); //var_dump($placeholder); //var_dump($value); } //var_dump($sql); //var_dump($stmt); $stmt->execute(); } catch(PDOException $rError) { throw new Exception("Registering Failed: ".$rError->getMessage()); } } } [/php] Im seriously confused about this part. [php] foreach ($data as $column => $value) { //var_dump($column); //var_dump($value); $columns .= ($columns == "") ? "" : ", "; $columns .= $column; $holders .= ($holders == "") ? "" : ", "; $holders .= ":$column"; //var_dump($columns); //var_dump($holders); } [/php] Thanks in advance :)!

lets break it down line by line.
[php]// this line says, using the $data array, lets label the key $column and the info $value.
foreach ($data as $column => $value) [/php]

Now we’re in the loop…
[php]// this first bit of this line says append to the $columns variable
$columns .=
// using .= is the same as writing $columns = $columns . ADDING SOMETHING HERE

// the rest of the line says if $columns is empty ($columns == “”)
// don’t add anything “”
// if it is not empty, add a comma and a space ", "
$columns .= ($columns == “”) ? “” : ", ";
[/php]

the same is true for the next few lines…
[php]$columns .= $column;
$holders .= ($holders == “”) ? “” : ", ";
$holders .= “:$column”;
[/php]

Make sense?
Red :wink:

I am not trying to confuse you, but you can even use prepared statements :wink:

Here’s just an example what I’m talking about ->
[php]public function create(array $records=NULL, $created_by = NULL) {

if (is_array($records)) {
	$db = Database::getInstance();
	$pdo = $db->getConnection();
	
	$this->sql = 'INSERT INTO calendar (created_by, security_level, date, time, name, info) VALUES ';
	
	foreach ($records as $this->record) {
		$this->query[] = '(:created_by'.$this->n.', :security_level'.$this->n .', :date' . $this->n . ', :time' . $this->n . ', :name' . $this->n . ', :info' . $this->n . ')';
		
		$this->record = (object) $this->record;
		$this->iData['created_by' . $this->n] = $created_by;
		$this->iData['security_level' . $this->n] = 'sysop';
		$this->iData['date' . $this->n] = $this->record->date;
		$this->iData['time' . $this->n] = $this->record->time;
		$this->iData['name' . $this->n] = $this->record->name;
		$this->iData['info' . $this->n] = $this->record->info;
		
		$this->n += 1;
		
	}
	
	if (!empty($this->query)) {
		$this->sql .= implode(', ', $this->query);
		$this->stmt = $pdo->prepare($this->sql);
		$this->result = $this->stmt->execute($this->iData);
	}            
	
}

} // End of create method/function:[/php]

Sorry for the late reply.

[member=26967]Redscouse[/member] Thanks for the explanation , it does make sense yes is there maybe an easier way to do that loop so its easier to understand :)?

[member=57087]Strider64[/member] Hehe its kinda confusing but i somewhat get it , hehe ;D.

Im also thinking of trying to make that bindValue loop into bindParam.

The current code you have is probably the most efficient way as it uses plenty of shorthand code.

You could, if you wish, do something like this;
[php]foreach ($data as $column => $value) {
if($columns == “”) {
$columns = $columns . “”;
}
else {
$columns = $columns . ", ";
}
//…
}
[/php]
That way seems rather long winded as if $columns is empty we don’t really do anything so let’s just change that slightly;
[php]foreach ($data as $column => $value) {
if($columns != “”) {
$columns = $columns . ", ";
}
//…
}
[/php]
Now we are only checking for $columns to be not empty before adding our comma and space.

If we make the code any shorter we end up with the version you already have.
Make sense?
Red :wink:

Sponsor our Newsletter | Privacy Policy | Terms of Service