PHP脚本不会插入到mysql中

时间:2014-03-13 14:34:56

标签: php mysql

我正在编写此代码,并且到目前为止它运行良好。基本上,我正在修改phpacademy OOP登录脚本以供我自己使用。我遇到问题的部分是

$user->update(array(
                    'username' => input::get('username'),
                    'name' => input::get('name'),
                    'address' => input::get('address'),
                    'group' => input::get('group'),
                    'hire_date' => input::get('hire_date'),
                    ), $user->findUser(input::get('username'), 'id'));

如果我删除group行,但是group输入,则效果会很好,但它不起作用。我确实将该组作为我的mysql数据库中的一列,所以我不确定从哪里开始。仍然有点新鲜,但学习了很多。我很感激任何人都可以给我的帮助。

更新用户页面

<?php
require_once 'core/init.php';
$user = new user();
$db = db::getInstance();
if($user->data()->group > 1) {
    session::flash('home', "You do not have permission to view this page");
    redirect::to('home.php');
}
if(!$user->isloggedin()) {
    redirect::to('index.php');
}
if(input::exists()) {
    if(token::check(input::get('token'))){
        $validate = new validate();
        $validation = $validate->check($_POST, array(
            'username' => array(
                'required' => true,
                'min' => 2
            ),
            'name' => array(
                'required' => true,
                'min' => 2,
                'max' => 50
            ),
            'hire_date' => array(
                'required' => true,
            ),
            'address' => array(
                'required' => true,
                'max' => 100
            ),
            'group' => array(
                'required' => true,
            )
        ));
        if($validation->passed()) {
            try {
                $user->update(array(
                    'username' => input::get('username'),
                    'name' => input::get('name'),
                    'address' => input::get('address'),
                    'group' => input::get('group'),
                    'hire_date' => input::get('hire_date'),
                    ), $user->findUser(input::get('username'), 'id'));
                session::flash('home', 'the details have been updated');
                redirect::to('home.php');
            } catch (Exception $e) {
                die($e->getMessage());
            }
        } else {
            foreach($validation->errors() as $error){
                echo $error, '<br>';
            }
        }
    }
}
?>
<head>
    <title>PCTSoft V1.0</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body class="main">
    <form action="" method="post" class="register">
        <div class="field">
            <label for="username">Username</label>
            <input type="text" value="" id="username" name="username"><br>
            <label for="name">Name</label>
            <input type="text" value="<?php echo escape($user->findUser(input::get('username'), 'name'));?>" id="name" name="name"><br>
            <label for="hire_date">Hire Date</label>
            <input type="text" value="<?php echo escape($user->findUser(input::get('username'), 'hire_date'));?>" id="hire_date" name="hire_date" placeholder="2014-01-01"><br>
            <label for="address">Address</label>
            <input type="text" value="<?php echo escape($user->findUser(input::get('username'), 'address'));?>" id="address" name="address" style="width:300px;"><br>
            <label for="group">Group</label>
            <input type="text" id="group" name="group" value="<?php echo escape($user->findUser(input::get('username'), 'group'));?>"><br>
            <input type="submit" value="Update">
            <input type="hidden" name="token" value="<?php echo token::generate();?>">
        </div>
    </form>
</body>

user

<?php
class user {
    private $_db,
            $_data,
            $_sessionName,
            $_cookieName,
            $_isloggedin;

    public function __construct($user = null) {
        $this->_db = db::getInstance();
        $this->_sessionName = config::get('session/session_name');
        $this->_cookieName = config::get('remember/cookie_name');
        if(!$user) {
            if(session::exists($this->_sessionName)) {
                $user = session::get($this->_sessionName);
                if($this->find($user)) {
                    $this->_isloggedin = true;
                } else {
                    $this->logout();
                }
            }
        } else {
            $this->find($user);
        }
    }
    public function update($fields, $id = null) {
        if(!$id && $this->isloggedin()) {
            $id = $this->data()->id;
        }
        if(!$this->_db->update('users', $id, $fields)) {
            throw new Exception('there was a problem updating the information');
        }
    }
    public function create($fields = array()) {
        if(!$this->_db->insert('users', $fields)) {
            throw new Exception('There was a problem creating an account');
        }
    }
    public function findUser($user = null, $column) {
        if($user) {
            $field = (is_numeric($user)) ? 'id' : 'username';
            $data = $this->_db->get('users', array($field, '=', $user));
            if($data->count()) {
                $this->_data = $data->first();
                return $this->data()->$column;
            }
        }
    }
    public function find($user = null) {
        if($user) {
            $field = (is_numeric($user)) ? 'id' : 'username';
            $data = $this->_db->get('users', array($field, '=', $user));
            if($data->count()) {
                $this->_data = $data->first();
                return true;
            }
        }
    }
    public function login($username = null, $password = null, $remember = false) {

        if(!$username && !$password && $this->exists()) {
            session::put($this->_sessionName, $this->data()->id);
        } else {
        $user = $this->find($username);
        if($user) {
            if($this->data()->password === hash::make($password, $this->data()->salt)) {
                session::put($this->_sessionName, $this->data()->id);
                if($remember) {
                    $hash = hash::unique();
                    $hashCheck = $this->_db->get('users_session', array('user_id', '=', $this->data()->id));
                    if(!$hashCheck->count()) {
                        $this->_db->insert('users_session', array(
                            'user_id' => $this->data()->id,
                            'hash' => $hash
                        ));
                    } else {
                        $hash = $hashCheck->first()->hash;
                    }
                    cookie::put($this->_cookieName, $hash, config::get('remember/cookie_expiry'));
                }
                return true;
            }
        }
      }
      return false;
    }
    public function exists() {
        return (!empty($this->_data)) ? true : false;
    }
    public function logout() {
        $this->_db->delete('users_session', array('user_id', '=', $this->data()->id));
        session::delete($this->_sessionName);
        cookie::delete($this->_cookieName);
    }
    public function data() {
        return $this->_data;
    }
    public function isloggedin() {
        return $this->_isloggedin;
    }
}

db

<?php
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'));
        } catch (PDOException $ex) {
            die($ex->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)) {
            $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;
    }
    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;
    }    
    public function get($table, $where) {
        return $this->action('SELECT *', $table, $where);
    }
    public function delete($table, $where) {
        return $this->action('DELETE', $table, $where);
    }    
    public function insert($table, $fields = array()) {
        $keys = array_keys($fields);
        $values = '';
        $x=1;
        foreach($fields as $field) {
            $values .= "?";
            if($x < count($fields)) {
                $values .= ', ';
            }
            $x++;
        }
        $sql = "INSERT INTO $table (`" . implode('`, `', $keys) . "`) VALUES ({$values})";
        if(!$this->query($sql, $fields)->error()) {
            return true;
        }
        return false;
    }    
    public function update($table, $id, $fields = array()) {
        $set = '';
        $x = 1;
        foreach($fields as $name => $value) {
            $set .= "{$name} = ?";
            if($x < count($fields)) {
                $set .= ',';
            }
            $x++;
        }
        $sql = "UPDATE {$table} SET {$set} WHERE id = {$id}";

        if(!$this->query($sql, $fields)->error()) {
            return true;
        }
        return false;
    }    
    public function results() {
        return $this->_results;
    }    
    public function first() {
        $return = $this->results();
        return $return[0];
    }    
    public function error() {
        return $this->_error;
    }    
    public function count() {
        return $this->_count;
    }
}

2 个答案:

答案 0 :(得分:1)

正如@DanFromGermany指出的那样,确实存在数据库表列转义问题。

class Db {
  public function update($table, $id, $fields = array()) {
    $set = '';
    $x = 1;
    foreach($fields as $name => $value) {
      $set .= "`{$name}` = ?"; // Mind this row. ` were added to table column name.
      if($x < count($fields)) {
        $set .= ',';
      }
      $x++;
    }
    $sql = "UPDATE {$table} SET {$set} WHERE id = {$id}";

    if(!$this->query($sql, $fields)->error()) {
      return true;
    }
    return false;
  }
}

另外,您应该阅读PDOStatement::errorInfo()。 它会报告错误。 ;)

请投票@DanFromGermany评论,如果这真的是这个答案可以帮助你。

顺便说一下:班级名称应该始终以大写字母开头。最好继续camelCase

答案 1 :(得分:0)

在MySQL中,你不能命名一个列&#34; Group&#34;因为它是reserved word。将列重命名为更具体的代码,例如userGroup。