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


Extract associative array index name to automatch the database column name

下面是我的代码-

$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'])";

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

不能在" -引号字符串中引用数组键:

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注入攻击。