Problem with a SQL statement - php

I'm trying to enter values into a database table using a form and a PHP function. The PHP seems to be fine as the SQL statement it creates looks okay, but the database always throws up an error. This is the SQL statement that my code has generated (with arbitrary values):
INSERT INTO Iteminfo ('itemName', 'itemSeller', 'itemCategory', 'itemDescription', 'itemPrice', 'itemPostage', 'itemBegin', 'itemEnd', 'buynow', 'itemPicture')
values ('gorillaz album', 'ben', 'music', 'new one ', '5.00', '1.00', '2010-03-15 14:59:51', '2010-03-16 14:59:51', '0', 'http://www.thefader.com/wp-content/uploads/2010/01/gorillaz-plastic-beach.jpg')
This throws up an error both when I use the PHP function to evaluate the query and also when I use phpMyAdmin to enter the query manually. However, I can't see anything wrong with it. Can anyone shed some light on this? All of the fields are VARCHAR values, except for itemPrice and itemPostage (which are stored as DECIMAL(4,2)) and the itemBegin and itemEnd, which are stored as DATETIMEs.

Try
INSERT INTO Iteminfo (itemName, itemSeller, itemCategory, itemDescription, itemPrice, itemPostage, itemBegin, itemEnd, buynow, itemPicture)
values ('gorillaz album', 'ben', 'music', 'new one ', '5.00', '1.00', '2010-03-15 14:59:51', '2010-03-16 14:59:51', '0', 'http://www.thefader.com/wp-content/uploads/2010/01/gorillaz-plastic-beach.jpg')
Column names should not be quoted.

Don't quote the column names in the specified list after the table (itemName, itemSeller, etc.)

Per a comment above by middus, The 5.00 and 1.00 should NOT be quoted as they are decimals and not strings.

Your column names shouldn't be strings
try removing '' in column definitions

Related

How to manually escape a boolean value for a mySQL Database insert in CakePHP?

i'm having the following code:
/** #var DboSource $db */
$db = $this->getDataSource();
var_dump($db->value($open, 'boolean'));
die;
$this->query(
'INSERT INTO foo(`client_id`, `open`, `modified`, `created`) VALUES(:clientId, :open, NOW(), NOW()) ON DUPLICATE KEY UPDATE modified = now();',
[
':clientId' => $db->value($clientId, 'integer'),
':open' => $db->value($open, 'boolean')
]
);
$open is a boolean value, the 'open'-column is defined as tinyint(1). When wrapping $open with $db->value($open, 'boolean') the result is '1', '0' (see the single quotes).
Unfortunately this output leads to a new record with open = false (as '1' is not properly inserted as true)
If I use $db->boolean($open) as option, everything's working correctly.
But I think, $db->value() should do the same job as well?
Looking at when and how DboSource::value() is being used internally, this is the expected behavior. If it wouldn't do what it does, then values wouldn't get prepared properly for Model::save() operations.
DboSource::value() internally passes the "booleanized" value (DboSource::boolean($value, true) this already adds quotes) to PDO::quote(), where the value is going to be quoted anyways no matter what, ie 0, 1, '0', '1', true, or false, it will always return a quoted value, that is '0', '1' or even '' (for false, which is equal to 0).
The problem with your code is, that values passed to the second argument of Model::query() are finally being passed to PDOStatement::execute() (.../DboSource.php#L458), which treats all values as strings and escapes them accordingly, so finally in your query a '1' will end up as '\'1\'', hence the problems.
TL;DR
This seems to be the expected behavior, it's just poorly documented. So when using the second argument of Model::query(), sanitize the values if necessary (ie cast to integers, booleans, strings, etc), but do not escape them, escape them only when you manually insert them in the actual query string (which should however be avoided whenever possible)!

Laravel update Issue

Here is my code -
$updatecompany = DB::table('Companies')
->where('ID', (int)$companyid)
->update(array(
'CompanyName' => $companyname,
'CompanyAddress' => $companyaddress,
'CompanyEmail' => $companyemail,
'ContactName' => $contactname,
'CompanyCity' => $companycity,
'CompanyState' => $companystate,
'CompanyZip' => $companyzipcode,
'CompanyPhone' => $companyphone,
));
$updatecompany is always 0. What might be the problem?
One of most possible reasons is that you are updating with the same data in the database.
There needs one out of the box solution, of course if you can do it.
So, no rows are updating, even if the SQL is correct.
Here is my suggestion:
Add a new column updatedOn in DB Table Companies.
The type should be TIMESTAMP and add attribute ON UPDATE CURRENT_TIMESTAMP.
This way you will always get row affected and hence you get return value other than 0.
You don't need to cast $companyId to an integer there. It does not help Laravel's query builder.
Use dd($companyId) and dump the variable before you run the query and find out what it is.

MySQL - Decimal cannot be NULL

Everytime I try to make an insert statement into my dastabase I get a "Incorrect decimal value: 'NULL' for column 'bounty3' at row 1" error. How do I insert a null value into a decimal datatype? Should I just make the default value 0.00?
Incorrect decimal value: '' for column 'bounty3' at row 1 Whole query: INSERT INTO songs (userid, wavURL, mp3URL, genre, songTitle, BPM, insWanted, bounty, insWanted2, bounty2, insWanted3, bounty3, insWanted4, bounty4, insWanted5, bounty5, insWanted6, bounty6, insWanted7, bounty7, insWanted8, bounty8, insWanted9, bounty9, insWanted10, bounty10) VALUES ('12534545', '/audio/wav/jqmrgpfcMichael/135259578210secreason.wav', '/audio/mp3/jqmrgpfcMichael/135259578210secreason.mp3', 'Rock/Funk', 'titlee', '120', 'bass', '20.00', 'guitar', '20.00', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '')
I tried this statement with a NULL value too. Here is the error:
Incorrect decimal value: 'NULL' for column 'bounty3' at row 1 Whole query: INSERT INTO songs (userid, wavURL, mp3URL, genre, songTitle, BPM, insWanted, bounty, insWanted2, bounty2, insWanted3, bounty3, insWanted4, bounty4, insWanted5, bounty5, insWanted6, bounty6, insWanted7, bounty7, insWanted8, bounty8, insWanted9, bounty9, insWanted10, bounty10) VALUES ('12534545', '/audio/wav/jqmrgpfcMichael/143922765110secreason.wav', '/audio/mp3/jqmrgpfcMichael/143922765110secreason.mp3', 'Rock/Funk', 'title', '110', 'bass', '110.00', 'guitar', '20.00', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL')
Oh.. you are trying to insert an empty string '' into bounty3. Replace it with NULL. I have also noticed empty strings for other possible numeric values eg bonty4. You should replace all empty strings with NULL for numeric values.
eg: mysql_query("INSERT INTO empty_number,number VALUES(NULL,1)");
EDIT: HEY HEY get the point, you cannot insert NULL to a numeric value as 'NULL' because this is a string, you should insert as NULL without any quotation marks
use blank, not null, if you want the default value.
I just dealt with this issue in MySql 5.1.61.
If the server is in strict mode, you must enter 0 instead of '' for decimal fields. Disabling strict mode allows you to just do '' to populate a null value.
Thanks, it worked using NULL when it comes empty:
$conn->bindParam(':'.$valor, ( $key[0] ? $key[0] : NULL ), PDO::PARAM_STR);
You can run this query to allow NULL values in 'bounty3' field.
ALTER TABLE songs CHANGE bounty3 bounty3 DECIMAL(10,0) NULL;
Make sure the field type allows for NULL values and that the default is NULL.
Then use:
UPDATE table_name SET date_field=IF('$date_value'='',NULL,'$date_value')
This works for inserts or updates.
I have tried using $date_value = NULL and I have even tried unset($date_value) before inserting or updating, and it never worked on my decimal fields. MySQL always converted them to 0.00. The method above was the only solution that worked for me.
Make sure that the field is "nullable" (does not have NOT NULL in its definition)
Make field's default value NULL.
Ex.: price decimal(12,2) DEFAULT NULL
Now, to test it, store some number, then '' (an empty string) into this field — it should become NULL in the end.
The field is most likely numeric. If the field is numeric then only numbers are accepted. Empty string is not accepted
insert into songs (...,bounty3) values(...,'')
neither the NULL string
insert into songs (...,bounty3) values(...,'NULL')
('NULL' which is just a string, nothing to do with the actual NULL value, so 'NULL' si similar to 'HONEY BEE' if you want).
So if the column is numeric then it will only take numbers. However if the column is NULLABLE then it will accept NULL, too. That means your insert must have
insert into songs (...,bounty3) values (..., NULL)
If you push NULL on such a column and the column has a default value then DEFAULT value will be used instead of the NULL you are pushing.
You need to make sure that your database schema allows NULL values for that column. Run describe <tablename>; in your MySQL client to see what the schema for that table is.
If the schema does not allow null then you can use alter table to change the schema. Make sure you don't specify NOT NULL for that column and you should be fine.
Another option is to make sure that in your source data, the empty cells or fields contain 'NULL' before you import them in MySQL. This way, MySQL will recognize these fields as being really NULL, and won't transform them to 0's.
It worked por me when POST data is received:
...
if ($value == '') {$value = '0.0';}
...

SQL where value combination of 0 and sha1(value, true) in CodeIgniter's Active Records returns all rows

So this is my conclusion of the real problem from a question I asked earlier here:
SQL Select Query with CodeIgniter's active records and 'where sha1' returns first row entry
I'm also double posting in the CodeIgniter forum:
http://codeigniter.com/forums/viewthread/194502/ (latest progress...)
You can get several code snippets from both.
In short, the problem I am having is the following and I'm not sure who's really the culprit:
I am using an array as shown below to define the 'where' in a select query for an active records function. The query gives me all the rows in the table if used in the certain combination outlined below.
pasting---
it actually looks like this combination of error only happens when sha1 returns raw output data and email < 1 For instance:
$where = array(
'email' => 0,
'password' => sha1(false, true), # sha1($this->input>post('password'), true);
);
if sha1(false, true) is changed to sha1(whatever) there is no error. (‘whatever’ includes strings, booleans, etc.)
if array is unchanged and 'email' => 0 is changed to 'email' => '0' which happens in the SQL QueryA, then it works correctly. If I remove the ‘‘s from the value in QueryA as in Active Records then I get all the rows again …
Also, I do not get any rows (which is correct) when 'email' is > 0. i.e. 'email' => 1 (2,3,etc) and even when 'email' => null.
The combination of ‘email’ = 0 and sha1(‘any value’, true) results in returning EVERY row in the table in the Active Records because there’s no quotes added to the value 0. Quotes are however added around the ‘password’ = ‘value’. If there are no quotes around the raw hash, then SQL returns an Error and prevents the script from running.. (which is better than returning ever row…)
This could be an SQL error since it only happens on a value of 0... but is it user error to not quote a where value? If so, then should Active Records should quote the value for me automatically if it is an integer or not? It seems to do it for string values, but not integers (false = 0, true = 1)...
If you want the same result in your queries, write the two equal. In QUERY1 you define your terms as follows:
WHERE `email` = \''.$data['email'].'\'
AND `password` = \''.$data['password'].'\'
in QUERY2
# data for sql query
$where = array(
'email' => $this->input->post('email'),
'password' => sha1($this->input->post('password'), true);
);
For QUERY1 and QUERY2 are equal, QUERY2 would be:
# data for sql query
$where = array(
'email' => "'".$this->input->post('email')."'",
'password' => sha1($this->input->post('password'), true);
);
Codeigniter can not determine by itself that 0 should not be a number. You do it yourself as QUERY1.

find by column name cakePHP

Hello I have been trying to understand how to get data from model by the name of field. I am using cakePHP, and I need to retreive a column's data from a table. The syntax is
> "select name from permissions"
So I tried to find out on book.cakephp.org, so I got the field function, but that only gives me the first value, while I have more than one values for this.
I tried do a
$this->Model->find(array('fields'=>'Model.fieldName'));
but I understood that the syntax itself is flawed.
Can somebody let me know what is the method to query based on column name.
$this->Model->find(array('fields'=>'Model.fieldName'))
You forgot the array function. Also:
$this->Model->find(array('fields'=>array('Model.fieldName')))
will work.
findAllBy will find all records based on the field name.
$this->Model->findAllBy<fieldName>(string $value, array $fields, array $order, int $limit, int $page, int $recursive);
For eaxample:
$this->Permission->findAllByName('Some Name');
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#findallby
Found it... hope it will help someone.
$workshop_lists = ClassRegistry::init('Workshop')->find('all',array(
'fields'=>array('user_id', 'title')
),
array(
'conditions' => array('user_id' => $this->Auth->user('id')),
'group' => 'Workshop.user_id',
'order' => 'posted DESC',
));
There is no way you can query out based on column name using one of the cake methods. You have to use the query method.
Syntax: $this->Model->('Select columnname from table');
$this->Model->find('all',array('fields'=>array('Model.fieldName')))
it works for me everytime.
If I understood well and you want not only 1 value but the whole values in the column 'name' from the table 'permissions'. In that case you could use:
$this->Model->find('list',$params);
(see explanation for 'find' here)
for the '$params' part you would use:
$params=array('fields'=>array('name'));
or putting all in a single line:
$arrayOfNames= $this->Model->find('list',array('fields'=>array('name')));
This will give you an array '$arrayOfNames' wich key is the 'id' (primary key) in 'permissions' table and wich value is the corresponding name in the field 'name' from the same table. This is the array would be something like:
'id'=>'name'
[23]=>'name1'
[28]=>'name2'
[29]=>'name3'
............
very much like I think you want. Hope it helps.
$this->Model->find('list', ['valueField' => 'fieldName']);

Categories