I've inherited a project which we are trying to migrate to MySQL 5 from MySQL 4.0(!) and from myISAM to InnoDB. Queries are now falling down because they are being constructed using an ADODB connection's ->qstr() on all parameters, including ints. Where no value is provided I end up with:
INSERT INTO tablename VALUES ('', 'stuff'...)
where the first column is an auto_increment. This causes an error (fair enough since '' isn't an int). Is there a switch in MySQL to make it behave as it used to (I assume it just silently converted to 0?)
Edit:
I just ran a few tests and what I wrote below won't help you at all. The error is because of the wrong datatype, and the SQL setting I suggested doesn't change that. I'll leave this answer here though, since it might be helpful to someone else.
Firstly, double check that the column really is auto increment - a couple of times I've had CREATE TABLE files where the fact that a column is auto_increment was sadly missing.
The other thing which might help is to check that NO_AUTO_VALUE_ON_ZERO is not turned on.
SET SQL_MODE='' should turn it off.
Related
I've got a page that alters a large quantity of variables in my MySQL database, and so far they've all worked great, but now all of the queries inside of a single logic-gate have stopped working for no apparent reason.
I've confirmed the following:
- The variable posted and used in the "if" statement of the gate is as it was intended
- The logic gate is triggered as intended (I can echo stuff and etc inside of it).
- The database connection is established, I am successfully running queries of various types before and after this logic gate on the same connection variable.
- The connection user has ALL PRIVILEDGES enabled, the aforementioned queries surrounding this logic gate are using similar functions successfully.
Here's the logic gate:
if (!empty($_POST["addqual"])){
$coladqual = $_POST["addqual"];
$sqlf = "ALTER TABLE users ADD UNIQUE ('$coladqual') INT( 2 ) NOT NULL";
$conn->query($sqlf);
$sqlc = "INSERT INTO competencebonus (competence,bonus)
VALUES ($coladqual,0)";
$conn->query($sqlc);
}
I've tried multiple alterations, but they don't seem to execute no matter what I do. I've got at least 20 other queries in other logic gates before and after these two and there seems to be virtually no difference between them, apart from these two just not working at all.
EDIT - Here's the error (Thanks to all of you who provided me with the error report syntax)
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''TestAA') INT( 2 ) NOT NULL UNIQUE' at line 1
What strikes me as odd is that only the closing parenthesis is around the post input (TestAA). Is it supposed to have both or neither?
I tried changing the syntax and got the following error:
Duplicate entry '0' for key 'TestAB'
The syntax was:
$sqlf = "ALTER TABLE users ADD `$coladqual` INT( 2 ) NOT NULL UNIQUE";
FINAL EDIT:
Made it work. Deleted the "NOT NULL" statement as recommended by Jeff Pucket II. Somehow this combined with the deletion of the parenthesis and use of backticks instead of apostrophe made the thing work.
Thanks for those of you who had the patience to help me with this.
It looks like you're trying to alter an existing table with a unique not null column. I would expect this to fail if any rows already exist in the table, unless your engine imputes zero. Even then this would fail if there were more than one record because of the unique constraint. Also make sure that the column name being added doesn't already exist.
To get the error using MySQLi, try:
$result = $conn->query($sqlf) or die($conn->error);
The 'unique' constraint should go at the end of your query
$sqlf = "ALTER TABLE users ADD ('$coladqual') INT( 2 ) NOT NULL UNIQUE";
Error checking depends on what flavor of MySQL you're running
I'm using PHP to suck up a CSV file, massage the data, and then import it into a MySQL InnoDB table using PDO.
The table and all varchar columns have a utf8_unicode_ci collation, and are utf8.
I have a column that is varchar(1).
When I attempt using PDO to do a certain query, I'm getting SQLSTATE 22001 Data too long for column 'HeatingOption' at row 1 error.
The query is as follows:
INSERT INTO `Config`.`BaseItemCodes`
(`BaseItemCode`, `Series`, `HeatingOption`, `StandardColor`)
VALUES ('BD1896-1W', 'BD18', 'w', 'BG')
It's interesting to me, because I'm debugging, and having PDO print out the query to the CLI. I copy/pasted the query, without modification, directly into MySQL Workbench and executed it just fine.
I'm currently creating the value from extracting it from the end of the BaseItemCode there. I'm using substr(), trim()ing it, and strtolower()ing it as well, just to make sure of everything.
The PHP script is utf8 w/o BOM, and so is the CSV file.
I'm on Windows 8.1 using PHP 5.5.7, and running MySQL 5.6.15 on a CentOS server.
I'm thinking it's some strange charset issue, but I'm not sure what to look at next.
Edit: I just attempted to change the column to 'char(1)' and it didn't help.
Edit 2: I increased the length of the column to varchar(20) and I was able to insert the data.
I'm changing my question to "Why do MySQL and PDO behave this way?"
Edit:
I double checked the data after inserting the row and increasing the length of the column, and it seems the name of the bind :HeatingOption was being passed through. So PDO wasn't binding the data for some reason, yet to be discovered.
the error clearly said it,
you should go to your database and change the lenth of that column HeatingOption to more then 1 , put it forexample varchar(25)
EDIT:
it should work with VARCHAR(1) or CHAR(1) however you may inserted spaces with this letter
example 'w '
^---//this spaces will be counted as bite, and it will be too long
This is just the strangest thing and I'm not sure why or what is happening. Everything runs fine in SQL Server but results in errors when ran in PHP.
In PHP, I build a dynamic statement that contains one to many queries or statements. It looks like this:
begin try
begin transaction
-- statement 1
UPDATE table_name SET status = 1 WHERE things='stuff';
-- dynamic: to run after inserts
exec [dbo].[SP_TEST_2];
exec [dbo].[SP_TEST_3];
exec [dbo].[SP_TEST_9];
exec [dbo].[SP_TEST_14];
commit
select 'successful' as for_php_success_message
end try
begin catch
rollback
select error_number() as for_php_error_number
,error_severity() as for_php_error_severity
,error_state() as for_php_error_state
,error_procedure() as for_php_error_procedure
,error_line() as for_php_error_line
,error_message() as for_php_error_message;
end catch
This morning, someone came to me because the front page to all of this was throwing errors at them. Warning: mssql_query() [function.mssql-query]: message: The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION. This code has been untouched for several months and hasn't had any problems. The code in the stored procedures probably has changed since then.
I copied the code over to SQL Server Management Studio to test and everything ran fine from a direct copy and paste. No errors, no warnings, just successful.
Next, I looked up transactions online and changed rollback to if ##trancount>0 rollback and this did fix the transaction error; however - I had a new error from PHP:
Array
(
[for_php_error_number] => 50000
[for_php_error_severity] => 16
[for_php_error_state] => 1
[for_php_error_procedure] => SP_TEST_Record
[for_php_error_line] => 247
[for_php_error_message] => spTEST_Record: 515: Cannot insert the value NULL into column 'TEST_DATA', table 'tempdb.dbo.#IDs________________________________________________________________________________________________________________00000001D27E'; column does not allow nulls. INS
)
(still, a reminder: no errors are returned if I run the exact code in SQL Server Mgmt Studio)
The error involves a SP that is called at the end of each of the SP_TEST_# procedures listed in the dynamic query that PHP built. I cannot copy the SP code over to here because this is work stuff and I didn't write them so I'd really prefer to not have to paraphrase them, either, because they are huge and not formatted well. I will however, show the top of SP_TEST_RECORD where the error occurs (which isn't on line 247):
ALTER PROCEDURE [dbo].[SP_TEST_Record] (
#Test_ID real=0, #debug int=1, #create_entry int=0, #autoclose bit=0, #autodelete bit=0
)
AS
BEGIN
SET NOCOUNT ON;
declare #vtest_id real; set #vtest_id=#Test_ID
declare #vdebug int; set #vdebug=#debug
declare #vcreate_entry bit; set #vcreate_entry=#create_entry
declare #vautoclose bit; set #vautoclose=#autoclose
declare #vautodelete bit; set #vautodelete=#autodelete
declare #test_date datetime; set #test_date=getutcdate()
declare #ct int;
begin try
begin tran
if object_id('tempdb..#IDs') is not null drop table #IDs
CREATE TABLE #IDs (TYC_ID int not null, TYC_TYPE_ID int not null, TYC_ENV_ID int not null, TEST_DATA nvarchar(2000) null) ON [PRIMARY]
ALTER TABLE #IDs ADD PRIMARY KEY NONCLUSTERED (TYC_ID, TYC_TYPE_ID, TYC_ENV_ID)
insert into #IDs(TYC_ID, TYC_TYPE_ID, TYC_ENV_ID, TEST_DATA)
select TYC_ID, TYC_TYPE_ID, TYC_ENV_ID, TEST_DATA from SR_TESTING where TEST_ID=#vTest_ID
So - one thing I know... some how, my PHP transaction was being ended by something in one of the stored procedures that was called by the dynamic statement and that is cause of the transaction issue. There are transactions inside of those stored procedures.
But why don't I see the null insert error in SQL Server when I run the same exact code? If there's a null insert, there's a null insert... so why would it make a difference if it was called from PHP or not?
And less importantly, how was my transaction being ended by one of the stored procedures in the beginning?
Why was thetransaction ended by the SP's when the code was ran in PHP but not when it was ran in SQL Server?
Is there some execution-concurrency-order of operations-transaction hierarchy-something going on?
I didn't want to straight delete this question because it was, at the very least, a great learning experience for me. However, it was a very localized question. I figured out the answer a while ago so I can't remember the specifics...
It was definitely caused because of something happening in one of the stored procedures that were being called down the line. I was very surprised to find out that the error bubbled up that way, especially with the PHP. I guess error scope kind of played a part in it... the PHP took the first error it saw but running the code in SQL server allowed it to fail more gracefully (so I didn't see the error there). Dunno. Troubleshooting... when in doubt - go deeper, lol...
I did research on this question and nothing I've read in the MySQL manual, in MySQL bug reports, in Stack Overflow, or in other forums has helped so far.
I have a simple mysql select query:
SELECT * FROM `Toyota` WHERE `Toyota`.`CollisionEstimatingID` = '22028589';
This query fails with mysql error code 1054
Unknown column Toyota.CollisionEstimatingID in the WHERE clause
This column DOES exist, I've checked the spelling of the database, table and column at least 30 times now. I even deleted my database and reimported. I have tried it with the backticks and without backticks, with alias' and without alias' I've tried it with explicitly named table.column syntax, and without the explicit syntax, I've tried mixing and matching all the stuff I've mentioned (backticks on the table, but not the column, on the column but not the table name), and nothing seems to work. It fails when I execute it from the mysql CLI on Ubuntu 12.04, it fails from my PHP 5.3 code, and it fails inside of phpMyAdmin. I am ready to flip a table.
When I try this though:
SELECT * FROM `Toyota`;
This works without any problems? Good god, MySQL is such a tease...
Here is the table setup as derived from show create database Toyota;
CREATE TABLE `Toyota` (
`CollisionEstimatingID` varchar(255) DEFAULT NULL,
`OE_part_number` varchar(255) DEFAULT NULL,
`Price` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
An interesting note -- I wonder if it could be character encoding problems? I did get it to work ONCE in phpMyAdmin by using the show create table Toyota and deleting everything but the "CollisionEstimatingID" and used that to form the SELECT statement. But when I tried cutting and pasting, no dice.
I tried recreating the database and tables using the utf8 character set to see if that would help, but it didn't help. I tried copying to text out of the phpMyAdmin window and into my source code -- that produced some funky characters at the beginning of the column name -- kinda like this: >>?CollisionEstimatingID only it was an 'i' with an umlaut + a double right chevron and an upside down question mark.
I'm stumped. Anyone want to test their programming mettle and help a brother out?
Like ""?
This is the UTF-8 BOM (en.wikipedia.org/wiki/Byte_order_mark).
You probably need to clean the input files first.
Your codes doesn't have any problem as i have did some testing with my SQL Server.
May be try this
SELECT * FROM Toyota WHERE Toyota.CollisionEstimatingID = '22028589'
Ok this is a new one for me. Basically I have a table articles:
id: int auto increment
title: varchar(200)
description: varchar(1000)
ctext: longtext
chtml: longtext
Now I do an insert into this table with mysql_query:
INSERT INTO articles
(title, description, ctext, chtml)
VALUES
('$title', '$description', '$text', '$html')
All values have been passed through mysql_escape_string().
The text and html here are roughly 50k in size (so I can't really post the fully query here).
Now, here's the problem: the query works. A new row is inserted. However the ctext and chtml columns are empty. This is MySQL 5.0.51a and PHP 5.2.8. No errors are raised of any kind as far as I can tell.
Now I dumped the query out to a file in /tmp and ran it with:
mysql -u username -p dbname < /tmp/query
Same thing.
I copy the query into Navicat and it... works.
So what on earth is going on?
Some random thoughts:
Have you tried controlling the text length see if it only fails at one point?
What kind of connection are you opening? Which driver?
Have you checked the encoding of your connection? Some invalid characters might be sent in.
Have you tried using parameters instead of mysql_escape_string?
Have you tried executing directly from the same file from Navicat instead of using the copy-paste? Again, might be related to an invalid character that's not passed through the copy-paste but was saved in the file.
Just to cover the basics we so often forget, how do you verify that the data is not inserted? I mean, how to you visualize it? You could have a line break that hides the first lines from 2 out of 3 means of visualization. Just a long shot, but I've seen it happen.
Addition: MySQL connections defaults to latin1, you need to use something like mysql_query("SET NAMES 'utf8'") to transfer unicode characters.
I'm not sure if this matters, but mysql_escape_string is deprecated and replaced by mysql_real_escape_string
Have you tried it with smaller text?