dqv84329 2016-09-22 11:04
浏览 64

foreach循环只接受数组的第一个索引

I made a simple example in PHP, the objective is simply insert the values of the array to the database. The field names are the array keys and the field values are the array values. I chose object-oriented style for querying because I'm practising OOP. When I looped it, the issue was this: the code only accepts the first index of the array, which is the "name"; it is supposed to accept the four values since the table consists of four fields (name, email, username, password). Now the result in the database is only the name field has value, the rest of the fields are null. Here is the code:

<?php

class User {
    public static function insert($table, $table_fields = array()) {
        if(count($table_fields)) {
            foreach($table_fields as $field_name => $field_value) {
                return "INSERT INTO $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 to know what's wrong with my code, and it would give me much more gratitude if you give me tips for improvement.

  • 写回答

1条回答 默认 最新

  • dongshi4773 2016-09-22 11:13
    关注

    Code bellow will make your example work, if you still want to use foreach you need to put return after it.
    And like comments pointed you need to use prepared statements or some library to build your queries.

       <?php
    
    class User {
        public static function insert($table, $table_fields = array()) {
            if(count($table_fields)) {
                return "INSERT INTO $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'
    )));
    
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效