[英]foreach loop accepts only the first index of array
我在 PHP 中做了一個簡單的例子,目的只是將數組的值插入到數據庫中。 字段名稱是數組鍵,字段值是數組值。 我選擇面向對象的風格進行查詢,因為我正在練習 OOP。 當我循環它時,問題是:代碼只接受數組的第一個索引,即“名稱”; 它應該接受四個值,因為該表包含四個字段(姓名、電子郵件、用戶名、密碼)。 現在數據庫中的結果只有 name 字段有值,其余字段為空。 這是代碼:
<?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'
)));
?>
我想知道我的代碼有什么問題,如果你給我改進的提示,我會更加感激。
下面的代碼將使您的示例工作,如果您仍然想使用 foreach,則需要在它后面加上 return。
就像評論指出你需要使用准備好的語句或一些庫來構建你的查詢。
<?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'
)));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.