我正在尝试将变量$check_for_e2
的值插入数据库。但是for循环插入仅一次。为什么??请帮助我。
我想每行将$check_for_e
变量数据插入成员表。但是,当我运行此代码时,它仅插入第一个名为admin的用户名。
其他用户名Sweet,kakuly
不会插入数据库。
require_once 'core/init.php';
$db = DB::getInstance();
if(isset($_POST["create_group"])) {
$g_name = $_POST['create_group']; // $g_name = 'Simple Name';
$check_for_e = $_COOKIE["CreateGroup"]; // check_for_e = 'admin,Sweet,kakuly'
$check_for_e2 = explode(',',$check_for_e);
$arrlength = count($check_for_e2);
//print_r($check_for_e2); //Array ( [0] => admin [1] => Sweet [2] => kakuly )
// GROUP ENTRY
$g_mgs = 'grp_'.time(); //GROUP IDENTY NUMBER
$db->query("INSERT INTO all_group (`g_id`, `name`, `description`, `privacy`) VALUES (?,?,?,?)",array($g_mgs,$g_name,'member','Public'));
// ASSING GROUP MEMBERS
for($x = 0; $x < $arrlength; $x++) {
echo $grp_mem = $check_for_e2[$x]; echo '<br>';
$db->insert('members', array('g_id' => $g_mgs, 'usermane' => $grp_mem, 'access' => 'member'));
}
// ASSING ME AS A GROUP ADMIN
$db->insert('members', array('g_id' => $g_mgs, 'usermane' => $username, 'access' => 'admin'));
// CREATE GROUP MESSAGES TABLE
$db->query("CREATE TABLE `ekooycf_groups`.`$g_mgs` ( `username` VARCHAR(50) NOT NULL , `message` TEXT NOT NULL , `time` VARCHAR(50) NOT NULL ) ENGINE = InnoDB CHARSET=utf8mb4 COLLATE utf8mb4_bin;");
echo $db->error();
}
DB类是
class DB {
private static $_instance = null;
private $_pdo,
$_query,
$_error = false,
$_results,
$_count = 0;
private function __construct() {
try {
$this->_pdo = new PDO('mysql:host='.Config::get('mysql/host').';dbname='.Config::get('mysql/db'), Config::get('mysql/username'), Config::get('mysql/password'));
// echo "connected";
} catch(PDOException $e) {
die($e->getMessage());
}
}
public static function getInstance() {
if(!isset(self::$_instance)) {
self::$_instance = new DB();
}
return self::$_instance;
}
public function query($sql, $params = array()) {
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)) {
//$this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo " Success";
// echo "<br>".$sql."<br>";
// print_r($params);
$x = 1;
if(count($params)) {
foreach($params as $param) {
// echo $param;
$this->_query->bindValue($x, $param);
$x++;
// echo $x."<br>";
}
}
if($this->_query->execute()) {
// echo "Success";
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error = true;
}
}
return $this;
}
public function insert($table, $fields = array()) {
if(count($fields)) {
$keys = array_keys($fields);
$values = null;
$x = 1;
foreach ($fields as $field) {
$values .= "?";
if($x < count($fields)) {
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO {$table} (`".implode('`, `', $keys)."`) VALUES ({$values})";
echo $sql;
if(!$this->query($sql, $fields)->error()) {
return true;
}
}
return false;
}
public function error() {
return $this->_error;
}
public function count() {
return $this->_count;
}
}