I’m trying to dynamically add class properties into an PDO prepared statement. To achieve this I need to create an array that will grab the properties from the class, put them in an array, and add a : to the beginning of each key. Then, separate each key with a comma. The closest I’ve gotten to achieve this is using:
foreach ($property as $field)
$propertyValues = implode(", :", array_keys($property));
return $propertyValues;
}
which gives me
username, :password
I just need a way to add a : to the first key which in this case is username. So it would look like
:username, :password
Keep in mind, however, that I’m trying to make this dynamic so that I can extend its functionality to other classes, and I’m not always going to know what the first array key is.
If your interested in reading the entire class, here it is:
<?php
require_once("../config/main.php");
class Database{
protected static $dbFields = array('username', 'password');
public $dbConnection;
public $tableName = 'users';
public $id;
public $username;
public $password;
public function __construct() {
$this->connect();
}
public function connect(){
try {
$this->dbConnection = new PDO("mysql:host=".DB_SERVER."; dbname=".DB_NAME, DB_USER, DB_PASS);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
public function properties() {
$properties = array();
foreach (self::$dbFields as $field) {
if (isset($this->field) || property_exists($this, $field)) {
$properties[$field] = $this->$field;
}
}
return $properties;
}
public function property_values() {
$property = $this->properties();
$propertyValues = implode(", :", array_keys($property));
return $propertyValues;
}
public function insert(){
// this is where all the is going to happen. it's a work in progress
// $sql = "INSERT INTO". $this->tableName. " (";
// $sql .= implode(", ",array_keys($this->properties()));
// $sql .= ")VALUES(". ;
// $q = $this->db->prepare($sql);
// $q->execute(array('John', 'hula'));
}
}
$database = new Database();
$vals = $database->property_values();
print_r($vals);
?>
To get the first array key, you can use the foolproof:
Since you also need the value (cannot change the key, can only unset the old one and set a new), you can use:
However
This isn’t really the cleanest approach. As often happens, you have become fixated on tweaking “your” approach to work when there is in fact a cleaner approach available.
One approach:
Now all the property names have had a
':'added in front.Another approach would be to just manually prepend a ‘:’; webbiedave beat me to that.