php - How to make a full dynamic insert query?
Get the solution ↓↓↓Solution:
I would do this:
class Test {
public $table;
public $fields;
public $values;
public function __construct($fields, $values, $table){
$this->fields = $fields;
$this->values = $values;
$this->table = $table;
}
public function fields_to_string(){
return "`".implode("`, `", $this->fields)."`";
}
public function properties_to_string(){
return "'".implode("', '", $this->values)."'";
}
public function insert(){
global $dbh;
$sql = "INSERT INTO `{$this->table}` (".$this->fields_to_string().") VALUES (".$this->properties_to_string().");";
$dbh->exec($sql);
echo $sql; // for test purposes
}
}
$fields = array('username', 'password');
$values = array('Mihai', 'stackoverflow');
$test = new Test($fields, $values, 'users');
$test->insert();
// INSERT INTO `users` (`username`, `password`) VALUES ('Mihai', 'stackoverflow');
Answer
Solution:
It is probably better to have the field values as a array to. This example should get you going:
class Test
{
public $table = 'users';
public $fields = array( 'id', 'username', 'password' );
public $values = array( "", "yousufiqbal", "123456" );
public function insert()
{
global $dbh;
$fields = '`' . implode( '`,`', $this->fields ) . '`';
$values = implode( ',', $this->values );
$sql = "INSERT INTO `$this->table` ( $fields ) VALUES ( $values )";
$dbh->exec( $sql );
}
}
Your next step would be to implement parameter binding, to prevent SQL injection!
Answer
Solution:
class Test {
public $fields = array('id', 'username', 'password');
public $properties = array('id' => "", 'username' => "yousufiqbal",'password' =>"123456");
public function fields_to_string(){
$fields_str = implode(',', $this->fields);
return $fields_str;
}
public function properties_to_string(){
$properties_str = implode(',', "'".$this->properties."'");
return $properties_str;
}
public function insert(){
global $dbh;
$sql = "INSERT INTO `{$this->table}` ($this->fields_to_string()) VALUES ($this->properties_to_string());";
$dbh->exec($sql);
}
}
Answer
Solution:
// some stuff here
return implode( ',', $this->fields );
For the values:
return "'" . implode( "','", $this->values ) . "'";
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: the process class relies on proc_open, which is not available on your php installation.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.