So here is my problem.
I have a field in my database called maillist with the type tinyint(1). Using phpmyadmin i inserted into some fields the values 0's and 1's.
When i read from the database here is the array returned.
Array
(
[User] => Array
(
[maillist] =>
)
)
Where the maillist should be 0 or 1 because in my database all the fields on the maillist are filled.
So i decided to change the type on the field to tinyint(4) and that fixed the problem are here is the returned array.
Array
(
[User] => Array
(
[maillist] => 0
)
)
Please note that i did not change any values i just changed the type from tinyint(1) to tinyint(4).
Although the problem is fixed i would like to know what might have caused this behavior ? do i have a lack of understanding in retrieving data using cakephp ? Did i miss something important ? Or this might have been a bug.
Try var_dump($array) instead of pr($array)
pr() does not show variable types and will never show booleans as there is no true or false character.
http://codepad.viper-7.com/tUvSTu
Related
I have a table of users similar to the statement below, (relevant fields included)
CREATE TABLE User (
ID INT NOT NULL AUTO_INCREMENT,
Username VARCHAR(30) NOT NULL,
IsActive BIT NOT NULL DEFAULT 1,
PRIMARY KEY (ID)
);
When I query the table with a simple SELECT statements, I get the fields back exactly as expected.
+----------------------------+
| ID | Username | IsActive |
+----+------------+----------+
| 42 | CoolGuy92 | 1 |
+----+------------+----------+
That's all well and good. If, though, I try to run the following query, and send its output to the browser for use, I get this error on the client side when trying to parse the return: Uncaught SyntaxError: Unexpected token in JSON at position X.
SELECT JSON_OBJECT(
"ID", Users.ID,
"Username", Users.Username,
"IsActive", Users.IsActive
)
FROM Users
What is causing this parsing error?
The parsing error occurs due to your IsActive column being the BIT data type. BIT columns have a charset and collation of binary, and are thusly stored as binary. An apparent value of 1 is actually stored as 0x01. During a normal query, MySQL will output the value of a BIT column using the schema's default character set, often treating it as an integer*. So for most cases, an apparent value of 1, becomes 0x31 and 0 becomes 0x30. This allows the returned values to be readable, and easily used as numbers or strings.
In the case of JSON_OBJECT though,
Strings produced by converting JSON values have a character set of utf8mb4 and a collation of utf8mb4_bin*
By making this conversion, the field's literal value is used and is output as \u0001. This is not escaped in any way, so when your browser attempts to parse the output, it fails when it reaches such a value.
To get around this, you can cast your BIT columns to another numeric datatype in your JSON_OBJECT call, or add 0 to it*.
SELECT JSON_OBJECT(
"ID", Users.ID,
"Username", Users.Username,
"IsActive", Users.IsActive + 0
)
FROM Users
In the below query I am saving into data base an array from multiple select2 options.
Here i have a database table participants with event_id(int, not null), user_id(int, null), p_mail(varchar, null).
When I pass proper id which is in users the data gets saved properly and null will be displayed in p_email column.
But when i pass some varchar values through array, the user_id is saved as 0 which should be NULL and Null is stored in p_email which should store the values.
foreach($resources as $r) {
global $response;
$sql = "INSERT INTO participants(event_id, user_id, p_email)
SELECT $response,
CASE
WHEN EXISTS (SELECT * from users where id = '$r') THEN
'$r'
ELSE NULL
END,
CASE
WHEN EXISTS (SELECT * from users where id = '$r') THEN
NULL
ELSE '$r'
END
FROM users WHERE id = 1;";
$query_result = $conn->query($sql) or die("Failed".$sql);
this is expected where it int is passed it should be stored in user_id column if id exists otherwise if its varchar it should be stored in p_email.
Present if I store a varchar which is not in users after checking instead of storing it in p_email. it stores null in p_email and 0 in user_id.
I think the issue here is that the id column is numeric. In the first test, you are presumably passing some legitimate numerical string id, such as '123'. MySQL has no issue internally converting between '123', the string, and 123, the number. However, in your second test, you are passing something like abc. In this case, MySQL appears to be converting that to a numeric value of 0. Also, assuming the id zero does exist, you would see NULL in your email column as well.
So, I think the correction here is to just bind numbers to your insert query, assuming the id column is really numeric.
And, you should read about using prepared statements in MySQL.
I cleared this issue by using LIKE instead of '=' in the code.
I'm fairly new to mysql, and I'm trying to get up and running with it in node using node-mysql. I have created a simple table like so:
CREATE TABLE myTable (
id SERIAL,
display BOOLEAN NOT NULL DEFAULT 1,
active BOOLEAN NOT NULL DEFAULT 0
) DEFAULT CHARSET utf8 COLLATE utf8_bin;
I am inserting rows like so:
db.query('INSERT INTO myTable SET ?', {
display: myObject.display,
active: myObject.active
}, callback);
As the docs say, node-mysql converts the object i'm passing in to key value pairs. This works great if myObject.display and myObject.active are both defined. If one or both aren't, node-mysql tries to insert NULL into the columns, which is not allowed. I intended for the default value to be used in this situation, but its throwing an error about the NULL value. So my question is:
1) Is there some special syntax to use when creating a table that will use the default when a null value is given, or 2) Is there some elegant way to do this with node-mysql that doesn't involve a bunch of object parsing?
Feel free to expand your answer if you see something else I could improve. My larger goal is to learn the best way to create a robust, safe, and concise mysql insert in node.
Your SQL syntax is incorrect for an INSERT statement.
INSERT
INSERT into TableName(id, display, active)
VALUES (?, ?, ?)
UPDATE
UPDATE TableName SET display = ?
WHERE id = ?
You would then populate the ? placeholders using db.query() and passing in your arguments.
I am using wamp in win 7.
In my database, I have one table be_users, two fields: username and email, both of them are set NOT NULL.
But why I still can insert empty value and null value into field: email, see below image:
Actually, you are inserting text and they are not NULL. The text NULL is very different from NULL. You can never violate the rule if the field is set to NOT NULL.
Try executing this statement,
INSERT INTO tableName VALUES (null, null) -- will fail
it will surely fail because those are NULL. But this statement below will surely work because you are inserting string.
INSERT INTO tableName VALUES ('', 'null') -- will work
An empty value does not equal NULL, and it looks like you are inserting 'null' not NULL into the database, so you are ending up with a string 'null' not a NULL value.
Dont send NULL enclosed with quotes 'NULL' or "NULL" its getting treated as text value.
the issue is due to the data type used for thease two field. "text" you can change this to varchar(255) to use NULL. There are some issue with NULL and data type text.
Null is a keyword. If you will enter null directly then it will show you error.
Example-
insert into tablename(fieldname) values(null);
This above line will generate error(if you have mentioned not null).
I think you have enter something else. Please check again the table structure and enter new data.
Any idea why I cannot automatically update creation_time field in my table:
id | name | creation_time
creation_time-->
Type: Timestamp,
Default Value: CURRENT_TIMESTAMP
When I try to save data in cakephp by using a statement like this:
$this->Model->create();
$this->Model->save(array('name'=>'...'));
I got new data inserting to the table but without the creation time. It is abnormal that when i run an insert into Mysql statement then the field is automatically update as current timestamp.
I know that I could use created field as in Cakephp's documentation but for my case, i don't want to change the existing field name because it is a table used by other members working in the same project.
Please advise me.
In cakephp it is better to use the conventional names like "created" in your case.
The field will be datetime type. But if you wanna make your own field you have to insert manually into your field the actually date and time with a normal set example:
$this->Model->set('creation_time', CURRENT_TIMESTAMP);
where current_timestamp is your variable that you have to create and after you save your model
But the best way in cakephp is to use the convention names, isn't recommended to use unconvention names
When you call $this->Model->create(), Cake populates the data contained in $this->Model with default values. If you debug $this->Model->data
debug($this->Model->data);
You will that the creation_time is already set, but with a string:
array(
'Model' => array(
...,
'creation_time' => 'CURRENT_TIMESTAMP'
)
)
So when Cake generates the INSERT query, this one contain the creation_time field, with CURRENT_TIMESTAMP as a string:
INSERT INTO `models` (..., `creation_time`, ...) VALUES (..., 'CURRENT_TIMESTAMP', ...)
If you want to keep your creation_time field in the datatable, to generate a working query you could delete the default value before saving the data:
$this->Model->create();
unset($this->Model->data['Model']['creation_time']);
$this->Model->save(...);