php - Slim 3 - getParsedBody() Incorrect integer value: 'NULL' -
this first attempt on slim 3. trying make simple web application, whenever trying retrieve null/empty request parameter it's string, , trying save value numeric column result in
general error: 1366 incorrect integer value: 'null' column 'last_login' @ row 1
validating each parameter seems exhausting task. know if that's option or there's i'm missing.
i had issues trying save object private fields database, appreciate comments on approach.
table design
create table `users` ( `user_id` int(10) unsigned not null auto_increment, `name` varchar(50) not null, `last_login` datetime default null, primary key (`user_id`) ) user model
class user implements jsonserializable { private $user_id; private $name; private $last_login; public function __construct($user_id = null, $name = null, $last_login = null) { if ($user_id !== null) $this->user_id = $user_id; if ($name !== null) $this->name = $name; if ($last_login !== null) $this->last_login = $last_login; } /** * getters , setters */ function jsonserialize() { return get_object_vars($this); } } userdao
class userdao { public function adduser(user $user) { $query = $this->connection->prepare('insert ' . table_users . ' value (:user_id, :name, :last_login)'); $result = $query->execute((array)$user->jsonserialize()); return $result; } } not calling jsonserialize() on execute result in
'pdoexception' message 'sqlstate[hy093]: invalid parameter number: parameter not defined
i assume pdo can't access model's private fields, wrong tho.
routes
$app->post('/user/add', function (request $request, response $response) { $input = $request->getparsedbody(); $userdao = new userdao(); $id = $input['user_id']; $name = $input['name']; $last = $input['last_login']; // set id null show difference dump between id , last_login $user = new user(null, $name, $last); var_dump($input); var_dump($user); $userdao->adduser($user); }); dump result
c:\wamp64\www\rest\app\core\routes.php:61: array (size=3) 'user_id' => string 'null' (length=4) 'name' => string 'b' (length=1) 'last_login' => string 'null' (length=4) c:\wamp64\www\rest\app\core\routes.php:62: object(user)[59] private 'user_id' => null private 'name' => string 'b' (length=1) private 'last_login' => string 'null' (length=4) i guess that's whole issue, how turn string 'null' null in efficient way.
the insert method works fine after adding jsonserialize() on excute. tried calling adduser() index.php , data inserted database.
sorry long post, i've tried remove lot of fields simplicity without leaving relative code out.
all data in request object strings. hence, if it's string "null" need manually convert null.
the easiest way solve problem stop inserting user_id it's auto increment field. i.e. correct sql statement prepare is:
$query = $this->connection->prepare('insert ' . table_users . ' (name, last_login) value (:name, :last_login)');
Comments
Post a Comment