Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I add a : to the beginning of the first array key when the first array key is unknown?
    primarykey
    data
    text
    <p>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:</p> <pre><code>foreach ($property as $field) $propertyValues = implode(", :", array_keys($property)); return $propertyValues; } </code></pre> <p>which gives me<br> username, :password</p> <p>I just need a way to add a : to the first key which in this case is username. So it would look like</p> <p>:username, :password</p> <p>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.</p> <p>If your interested in reading the entire class, here it is:</p> <pre><code>&lt;?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-&gt;connect(); } public function connect(){ try { $this-&gt;dbConnection = new PDO("mysql:host=".DB_SERVER."; dbname=".DB_NAME, DB_USER, DB_PASS); } catch (PDOException $e) { echo 'Connection failed: ' . $e-&gt;getMessage(); } } public function properties() { $properties = array(); foreach (self::$dbFields as $field) { if (isset($this-&gt;field) || property_exists($this, $field)) { $properties[$field] = $this-&gt;$field; } } return $properties; } public function property_values() { $property = $this-&gt;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-&gt;tableName. " ("; // $sql .= implode(", ",array_keys($this-&gt;properties())); // $sql .= ")VALUES(". ; // $q = $this-&gt;db-&gt;prepare($sql); // $q-&gt;execute(array('John', 'hula')); } } $database = new Database(); $vals = $database-&gt;property_values(); print_r($vals); ?&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload