Jump to content

OOP PHP PDO Dynamic Insert


iPwNix

Recommended Posts

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 more clean way to do this for a new guy like me?

Im sending my POST values from the index.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!";
}

Database.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());
      }
   }
}

Im seriously confused about this part.

         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);
        } 

Thanks in advance for the help ;D
 

Edited by iPwNix
Link to comment
Share on other sites

the code you are asking about is just forming the list of column names and VALUES place-holders for the insert query - 

INSERT INTO table_name (list of column names here...) VALUES (list of prepared query place-holders here...)

that loop, and the two lines before it initializing the two variables, can simply be replaced with these two lines of code, which might make it clearer what it is doing - 

$columns = implode(', ',array_keys($data));
$holders = ':'.implode(', :',array_keys($data));
Link to comment
Share on other sites

Don't just copy and paste code you found somewhere on the Internet, especially when you have no idea what it does. Chances are it's garbage, and it may even cause security vulnerabilities.

 

And indeed that class is both garbage and dangerous. It leaves your application wide open to SQL injection attacks should you every forget to validate the array keys before calling the method. Ironically, Drupal had the exact same vulnerability a couple of months ago – maybe they also copied and pasted that code snippet.

 

Either write your own code or use a reputable library. But don't just copy and paste random code.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.