Skip to main content
update grammar, formatting, punctuation
Source Link

I wan'twant to insert rows in a database table with the precaution of sqlSQL-injection. I'amI'm using below flexible mysqlMySQL insert function, which enters a record in a given table. Is this the best approach I'm using or Isis there any other approach to do the same? Thanks in advanced.

I wan't to insert rows in table with the precaution of sql-injection. I'am using below flexible mysql insert function which enters a record in given table. Is this the best approach I'm using or Is there any other approach to do the same? Thanks in advanced.

I want to insert rows in a database table with the precaution of SQL-injection. I'm using below flexible MySQL insert function, which enters a record in a given table. Is this the best approach or is there any other approach to do the same?

edited title
Link

Mysql flexible insert recoredrecord with bind parambind_param or bind valuebind_value

edited body
Source Link
<?php
/**
 * This code writes data in database. It also takes care of sql injection case
 *
 * Entry function name : mainFunc
 * Entry function arguments : 
 * $sendata$payload = [
 *   'tableName' => 'table_name',
 *   'data' => ['column1_name' => column1_value, 'column2_name' => column2_value, etc]
 * ];
 */

Class AddDBEntry {
   private $dbName;
   private $dbUserName;
   private $dbPassword;
   private $dbHost;
   private $mysqli;

  // $stmt = The SQL Statement Object
  // $param = Array of the Parameters
  public function dynamicBindVariables($stmt, $params) {
    if ($params != null) {
      // Generate the Type String (eg: 'issisd')
      $types = '';
      foreach($params as $param) {
        if(is_int($param)) {
          // Integer
          $types .= 'i';
        } elseif (is_float($param)) {
          // Double
          $types .= 'd';
        } elseif (is_string($param)) {
          // String
          $types .= 's';
        } else {
          // Blob and Unknown
          $types .= 'b';
        }
      }

      // Add the Type String as the first Parameter
      $bind_names[] = $types;

      // Loop thru the given Parameters
      for ($i=0; $i<count($params); $i++) {
        // Create a variable Name
        $bind_name = 'bind' . $i;
        // Add the Parameter to the variable Variable
        $$bind_name = $params[$i];
        // Associate the Variable as an Element in the Array
        $bind_names[] = &$$bind_name;
      }
       
      // Call the Function bind_param with dynamic Parameters
      call_user_func_array(array($stmt,'bind_param'), $bind_names);
    }
    return $stmt;
  }

  public function mainFunc($payLoad) {
    $tableName = $payLoad['tableName'];
    $data = $payLoad['data'];

    $this->mysqli = new mysqli($this->dbHost, $this->dbUserName, $this->dbPassword, $this->dbName);

    if ($this->mysqli->connect_errno) {
      echo  "Failed to connect to MySQL: (" . $this->mysqli->connect_errno . ") " . $mysqli->connect_error;
      die();
    }
    
    $stmtString = 'insert into ' . $tableName . ' (' . implode(', ', array_keys($data)) . ')' . ' values ' . '(' . str_repeat('?, ', count($data) - 1) . '?)';
    
    $params = array_values($data);
    if (!($stmt = $this->mysqli->prepare($stmtString))) {
      echo "Unable to prepare statement";
      // stop here, $stmt is not set, cannot continue
      die();
    }

    $stmt = $this->dynamicBindVariables($stmt, $params);
    $stmt->execute(); 
   
    if ($stmt->affected_rows <= 0) {
      echo "Error in insert";
    }
    $stmt->close();
  }
}
<?php
/**
 * This code writes data in database. It also takes care of sql injection case
 *
 * Entry function name : mainFunc
 * Entry function arguments : 
 * $sendata = [
 *   'tableName' => 'table_name',
 *   'data' => ['column1_name' => column1_value, 'column2_name' => column2_value, etc]
 * ];
 */

Class AddDBEntry {
   private $dbName;
   private $dbUserName;
   private $dbPassword;
   private $dbHost;
   private $mysqli;

  // $stmt = The SQL Statement Object
  // $param = Array of the Parameters
  public function dynamicBindVariables($stmt, $params) {
    if ($params != null) {
      // Generate the Type String (eg: 'issisd')
      $types = '';
      foreach($params as $param) {
        if(is_int($param)) {
          // Integer
          $types .= 'i';
        } elseif (is_float($param)) {
          // Double
          $types .= 'd';
        } elseif (is_string($param)) {
          // String
          $types .= 's';
        } else {
          // Blob and Unknown
          $types .= 'b';
        }
      }

      // Add the Type String as the first Parameter
      $bind_names[] = $types;

      // Loop thru the given Parameters
      for ($i=0; $i<count($params); $i++) {
        // Create a variable Name
        $bind_name = 'bind' . $i;
        // Add the Parameter to the variable Variable
        $$bind_name = $params[$i];
        // Associate the Variable as an Element in the Array
        $bind_names[] = &$$bind_name;
      }
       
      // Call the Function bind_param with dynamic Parameters
      call_user_func_array(array($stmt,'bind_param'), $bind_names);
    }
    return $stmt;
  }

  public function mainFunc($payLoad) {
    $tableName = $payLoad['tableName'];
    $data = $payLoad['data'];

    $this->mysqli = new mysqli($this->dbHost, $this->dbUserName, $this->dbPassword, $this->dbName);

    if ($this->mysqli->connect_errno) {
      echo  "Failed to connect to MySQL: (" . $this->mysqli->connect_errno . ") " . $mysqli->connect_error;
      die();
    }
    
    $stmtString = 'insert into ' . $tableName . ' (' . implode(', ', array_keys($data)) . ')' . ' values ' . '(' . str_repeat('?, ', count($data) - 1) . '?)';
    
    $params = array_values($data);
    if (!($stmt = $this->mysqli->prepare($stmtString))) {
      echo "Unable to prepare statement";
      // stop here, $stmt is not set, cannot continue
      die();
    }

    $stmt = $this->dynamicBindVariables($stmt, $params);
    $stmt->execute(); 
   
    if ($stmt->affected_rows <= 0) {
      echo "Error in insert";
    }
    $stmt->close();
  }
}
<?php
/**
 * This code writes data in database. It also takes care of sql injection case
 *
 * Entry function name : mainFunc
 * Entry function arguments : 
 * $payload = [
 *   'tableName' => 'table_name',
 *   'data' => ['column1_name' => column1_value, 'column2_name' => column2_value, etc]
 * ];
 */

Class AddDBEntry {
   private $dbName;
   private $dbUserName;
   private $dbPassword;
   private $dbHost;
   private $mysqli;

  // $stmt = The SQL Statement Object
  // $param = Array of the Parameters
  public function dynamicBindVariables($stmt, $params) {
    if ($params != null) {
      // Generate the Type String (eg: 'issisd')
      $types = '';
      foreach($params as $param) {
        if(is_int($param)) {
          // Integer
          $types .= 'i';
        } elseif (is_float($param)) {
          // Double
          $types .= 'd';
        } elseif (is_string($param)) {
          // String
          $types .= 's';
        } else {
          // Blob and Unknown
          $types .= 'b';
        }
      }

      // Add the Type String as the first Parameter
      $bind_names[] = $types;

      // Loop thru the given Parameters
      for ($i=0; $i<count($params); $i++) {
        // Create a variable Name
        $bind_name = 'bind' . $i;
        // Add the Parameter to the variable Variable
        $$bind_name = $params[$i];
        // Associate the Variable as an Element in the Array
        $bind_names[] = &$$bind_name;
      }
       
      // Call the Function bind_param with dynamic Parameters
      call_user_func_array(array($stmt,'bind_param'), $bind_names);
    }
    return $stmt;
  }

  public function mainFunc($payLoad) {
    $tableName = $payLoad['tableName'];
    $data = $payLoad['data'];

    $this->mysqli = new mysqli($this->dbHost, $this->dbUserName, $this->dbPassword, $this->dbName);

    if ($this->mysqli->connect_errno) {
      echo  "Failed to connect to MySQL: (" . $this->mysqli->connect_errno . ") " . $mysqli->connect_error;
      die();
    }
    
    $stmtString = 'insert into ' . $tableName . ' (' . implode(', ', array_keys($data)) . ')' . ' values ' . '(' . str_repeat('?, ', count($data) - 1) . '?)';
    
    $params = array_values($data);
    if (!($stmt = $this->mysqli->prepare($stmtString))) {
      echo "Unable to prepare statement";
      // stop here, $stmt is not set, cannot continue
      die();
    }

    $stmt = $this->dynamicBindVariables($stmt, $params);
    $stmt->execute(); 
   
    if ($stmt->affected_rows <= 0) {
      echo "Error in insert";
    }
    $stmt->close();
  }
}
Source Link
Loading