PHP MySqli - How to Generate Insert Statements for a Table
Below code will generate a Sql Insert Statement for all the records(you can also add some condition) of the database table.
<?php
class InsertStatements
{
public $mysqli = null;
public $fields;
public function __construct()
{
// host , username , password , databasename , port
$this->mysqli = new mysqli('localhost','root','mypassword','mydatabase',3306);
}
public function generateFieldsArray($result){
while($fieldInfo = $result->fetch_field()){
$this->fields[]= $fieldInfo->name;
}
}
public function getColumnNames($result){
$this->generateFieldsArray($result);
$columnsStatement="";
for ($i=0; $i < count($this->fields); $i++) {
if($i == count($this->fields)-1){
$columnsStatement=$columnsStatement.$this->fields[$i];
}
else{
$columnsStatement=$columnsStatement.$this->fields[$i].",";
}
}
return $columnsStatement;
}
public function getValues($result){
$s="";
while($row=$result->fetch_assoc()){
$s = $s."(";
for($i=0 ; $i<count($this->fields) ; $i++){
$s = (gettype($row[$this->fields[$i]]) == 'string') ? $s."'".$row[$this->fields[$i]]."'" : $s.$row[$this->fields[$i]];
if($i < count($this->fields)-1){
$s=$s.",";
}
}
$s = $s."),";
}
$s[strlen($s)-1]=";";
return $s;
}
public function generate($tableName){
// You can add WHERE clause
// For eg: SELECT * from TABLE where ID > 100
$qry="SELECT * FROM {$tableName}";
if($stmt = $this->mysqli->prepare($qry)){
$stmt->execute();
$result=$stmt->get_result();
// Generated Format
// INSERT INTO table(id,name) VALUES(1,'The Web Blinders'),(2,'Programming');
return "INSERT INTO {$tableName}({$this->getColumnNames($result)}) VALUES{$this->getValues($result)}";
}
}
}
// Make sure you change values in constructor
$is=new InsertStatements();
// there you go! Your insert statement
echo $is->generate("yourTableName");
ALTERNATE TITLES