php - foreach loop accepts only the first index of array -


i made simple example in php, objective insert values of array database. field names array keys , field values array values. chose object-oriented style querying because i'm practising oop. when looped it, issue this: code accepts first index of array, "name"; supposed accept 4 values since table consists of 4 fields (name, email, username, password). result in database name field has value, rest of fields null. here code:

<?php  class user {     public static function insert($table, $table_fields = array()) {         if(count($table_fields)) {             foreach($table_fields $field_name => $field_value) {                 return "insert $table ($field_name) values ('$field_value')";             }         }         return false;     } }  $connect = mysqli_connect('localhost', 'root', '', 'sample');  mysqli_query($connect, user::insert('users', array(     'name' => 'sample name',     'email' => 'samplename@samplemail.com',     'username' => 'sampleusername',     'password' => '12345' )));  ?> 

i want know what's wrong code, , give me more gratitude if give me tips improvement.

code bellow make example work, if still want use foreach need put return after it.
, comments pointed need use prepared statements or library build queries.

   <?php  class user {     public static function insert($table, $table_fields = array()) {         if(count($table_fields)) {             return "insert $table ('".implode("','",array_keys($table_fields))."')                              values ('".implode("','",$table_fields)."')";         }         return false;     } }  $connect = mysqli_connect('localhost', 'root', '', 'sample'); mysqli_query($connect, user::insert('users', array(     'name' => 'sample name',     'email' => 'samplename@samplemail.com',     'username' => 'sampleusername',     'password' => '12345' ))); 

Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -