提取关联数组索引名称以自动匹配数据库列名称

时间:2015-07-20 14:50:03

标签: php mysqli

以下是我的代码 -

$insert_details = array("username"=>"pavan", "firstname"=>"pavan", "lastname"=>"r", "profile_about"=>"My name is Pavan R.");
$connection->insert($insert_details);    

        public function insert(array $insert_details) {

            $insert_query = "INSERT INTO user (username,firstname,lastname,profile_about) VALUES ($insert_details['username'],$insert_details['firstname'],$insert_details['lastname'],insert_details['profile_about'])";
            $run_insert_query = mysqli_query($this->mysql_con, $insert_query);

            if ($run_insert_query) {

                $select_query = "SELECT * FROM user ORDER BY id DESC LIMIT 1";
                $run_select_query = mysqli_query($this->mysql_con, $select_query);

                while ($selected_row = mysqli_fetch_array($run_select_query)) {
                    $id = $selected_row['id'];
                    $username = $selected_row['username'];
                    $firstname = $selected_row['firstname'];
                    $lastname = $selected_row['lastname'];
                    $profile_about = $selected_row['profile_about'];
                }

                $es_insert = array();
                $es_insert['body']  = array('id' => $id, 'username' => $username, 'firstname' => $firstname, 'lastname' => $lastname, 'profile_about' =>  $profile_about);
                $es_insert['index'] = 'test';
                $es_insert['type']  = 'jdbc';
                $es_insert['id']    = $id;
                $check_insert = $this->es_con->index($es_insert);

                if($check_insert) {
                    echo nl2br("Successfully inserted to both database and elasticsearch\n");
                }
            }
            else {
                echo nl2br("Failed to insert into database hence closing the connection\n");            
            }
        }

当我运行代码时,我收到以下错误 -

PHP Parse error:  syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in /var/www/html/es/combined.php on line 38

这是因为SQL查询($ insert_query)。有人可以帮我调试吗?

还有一种方法可以从数组中提取索引名称并将其传递给数据库字段。在上面的代码中,我声明了一个关联数组,其索引名称与我的数据库列名相同。是否可以获取这些数组索引名称并将SQL查询优化为 -

$insert_query = "INSERT INTO user VALUES ($insert_details['username'],$insert_details['firstname'],$insert_details['lastname'],insert_details['profile_about'])";

它应该自动从数组索引名称中提取合适的列名。

1 个答案:

答案 0 :(得分:0)

您无法引用"中的数组键 - 引用字符串:

php > echo "$arr['foo']";
PHP Parse error:  syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in php shell code on line 1

要么

$sql = "... $insert_details[username] ..."
                            ^-------^---no quotes

$sql = "... {$insert_details['username']} ..."
            ^---------------------------^---brace syntax

请注意,您很容易受到sql injection attacks的攻击。<​​/ p>