下面是我的代碼 -提取關聯數組的索引名自動匹配數據庫列名
$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'])";
它應該會自動提取數組的索引名合適的列名。
您還需要刪除公共函數頂部的行。 – Daan
*「有人可以幫我調試嗎?」*您首先需要證明自己已經投入了很大的努力(包括研究錯誤),並且顯示第38行會有幫助。 – Anonymous
我已經在類中聲明瞭該函數,並且在類之外調用了該函數。 –