'How to reduce the number of function arguments and database table that has many fields in PHP
I want to pass some parameters in a method which i would use to insert data into my database. I have over 50 fields in the table i want to insert into. The challenge is that, some of this parameters are optional and so, explicitly writing the parameters and table fields would be very hectic.
I thought of public function addAd(...param){} however, i won't have control over the optional params.
For the table fields, i thought of using SELECT to get the fields then pass it as array into addTable as fields. "INSERT INTO adTable ($fields) VALUES (?,...)"
Is there any way i can solve this problem?
UPDATE
private $col_names;
private $msg;
private function getAdsFields(){
$sql = "SHOW COLUMNS FROM mall";
$stmt = $this->db->run($sql);
while ($row = $stmt->fetch()) {
if ($row['Field'] != 'defaultColID') {
array_push($this->col_names, $row['Field']);
}
}
}
public function createAd(...$params){
$this->getAdsFields();
//gets all the fields returned from getAdsFields then convert them to string
$fields = implode(',', $this->col_names);
if (empty($params)) {
$this->message("empty", "All field must be filled");
} else{
// gets the total number of parameters passed
$num = (count($params));
// loops through the numbers and pushes '?' in to the each loop;
$bind_array = [];
for ($i=0; $i < $num; $i++) {
array_push($bind_array, '?');
}
// coverts all the'?' in the array into strings;
$bind = implode(',',$bind_array);
$sql = "INSERT INTO mall ($fields) VALUES ($bind)";
$stmt = $this->db->run($sql, $params);
if ($stmt->rowCount() > 0) {
$this->message("success", "Category added successfully");
} else {
$this->message("failed", "Something Went Wrong");
}
}
return $this->msg;
}
This actually worked, however, the only set back is that i cannot specify optional parameters.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
