我目前在將數據插入到我的數據庫時遇到問題。我有這樣的代碼,開始插入查詢:OOP查詢,顯示2個查詢
if (Input::exists()) {
$validate = new Validate();
$link = new Link();
$validation = $validate->check($_POST, array(
'name' => array(
'related' => 'hyperlink'
),
'hyperlink' => array(
'related' => 'name'
)
));
if ($validation->passed()) {
try {
$link->create(array(
'uid' => $user->data()->id,
'name' => Input::get('name'),
'hyperlink' => Input::get('hyperlink')
));
} catch (PDOException $e) {
die($e->getMessage());
}
} else {
echo '<div class="error">';
echo '<ol>';
foreach ($validation->errors() as $error) {
echo '<li>' . $error . '</li>';
}
echo '</div>';
echo '</ol>';
}
}
運行此代碼,創建方法叫做:
public function create($fields = array()) {
if (!$this->_db->insert('user_links', $fields)) {
echo 'Something went wrong';
}
}
現在將運行該腳本插入方法:
public function insert($table, $fields = array()) {
if (count($fields)) {
$value_list = implode(", ", array_values($fields));
$keys = array_keys($fields);
$sql = "INSERT INTO `$table` (`" . implode('`, `', $keys) . "`) VALUES ({$value_list})";
if (!$this->query($sql, $fields)->error()) {
return true;
}
}
return false;
}
一切都很好,但是當它進入query()方法時,它看起來有2個查詢保存在其中。我已經聽說__destruct
,所以我想知道它是否與此有關。
這裏的查詢方法:
public function query($sql, $params = array()) {
$this->_error = false;
echo $sql;
if ($this->_query = $this->_pdo->prepare($sql)) {
$x = 1;
if (count($params)) {
foreach ($params as $param) {
$this->_query->bindValue($x, $param);
$x++;
}
}
if ($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error = true;
}
}
return $this;
}
當我在query()方法呼應$sql
,它的回聲是這樣的:
SELECT * FROM users WHERE id = ?INSERT INTO user_links (uid,name,hyperlink) VALUES (1, test, test)
的SELECT * FROM users WHERE id = ?
來自一個get()方法。但是在我爲查詢設置所有數據的代碼中,我沒有使用任何get()方法。除非要獲取輸入字段的值。 (但這不是問題)
感謝您的幫助!
EDIT 1:
選擇方法:
public function get($table, $where) {
return $this->action('SELECT *', $table, $where);
}
編輯2:
public function find($user = null) {
if ($user) {
$field = (is_numeric($user)) ? 'id' : 'email';
$data = $this->_db->get('users', array($field, '=', $user));
if ($data->count()) {
$this->_data = $data->first();
return true;
}
}
}
EDIT 3:
public function action($action, $table, $where = array()) {
if (count($where) === 3) {
$operators = array('=', '>', '<', '>=', '<=', '<>');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if (in_array($operator, $operators)) {
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if (!$this->query($sql, array($value))->error()) {
return $this;
}
}
}
return false;
}
假設你在laravel?指定你的框架 – 2015-03-13 09:46:18
純php,沒有框架。 – 2015-03-13 09:46:52
向你展示PDO Wrapper類的'select'或'get'方法,我打賭你必須通過一些其他查詢來獲取當前用戶 – Saqueib 2015-03-13 09:48:12