php odbc double excecutions bug - php

I am using Windows Server with MSSQL Server 2008, and a ODBC connection to WAMP on a seperate Windows Server.
Using PHP to execute database queries, and when I run INSERT queries I get two identical rows (with unique identifier as the only thing seperating them).
I have checked multiple times that it's not double posting, so it must be executing the code twice, or sending it twice, the problem is not on the PHP side, that's for sure.
For example, I run this code:
$sql = "INSERT INTO mytable(aboutPerson, fromPerson, comment)
VALUES(1,5, 'hello')";
//.. create connection to db
odbc_exec($sql);
//.. close connection to db
Out of that I get two identical rows in the table. This occurs on several tables.
Why does this occur and how can I stop it from happening? Is it a known bug in connecting WAMP to Microsoft SQL Server with ODBC?
BTW, I don't have the option of switching systems.
Any help would be very appreciated, thanks!
Edit-
An actual example by request.
$SQL = "INSERT INTO billboard (toPersonId, toGroupClass, toOfficeId, fromOfficeId,
fromType, fromId, header, msg, aboutPersonId, created, startMessageId,
fromPersonId, status, emailNote, smsNote)
VALUES (1, 0, 1, 1,
2, 1, 'cccccccccccccc', 'cccccccccccccccc', '', GETDATE(), 0,
1, 0, 0, 0)";
$resource = odbc_connect(database server url, username, password);
$statement = odbc_exec($SQL, $resource);
return odbc_free_result($statement);
I execute this code and I should get only 1 single row inserted into the table. Instead I get this, two identical rows (except for the first column, which is the primary key and is identity)
111 1 0 1 1 2 1 cccccccccccccc cccccccccccccccc 0 2012-10-10 12:56:27.773 0 1 0 0 0
110 1 0 1 1 2 1 cccccccccccccc cccccccccccccccc 0 2012-10-10 12:56:27.773 0 1 0 0 0

Related

Return BLOB column Which is Empty Or Not Empty as 1 or 0

I have a table with BLOB column that some row has BLOB, some empty.
1 Apple BLOB-8KiB
2 Banana
3 Pear BLOB-6KiB
4 Orange BLOB-7KiB
Is there any way I can use PHP MYSQL to get the array like this:
$fruit = array(
array("1",Apple,1),
array("2",Banana,0),
array("3",Pear,1),
array("4",Orange,1)
);
I just want to change the BLOB data with 1, Empty with 0 in my PHP array. Pls help.
Your select statement can use IF and ISNULL (note these are not widely implemented in the same format on different database backends, this is for MySQL).
So you would use:
SELECT ID, Name, IF(ISNULL(BlobField), 0, 1) FROM TableName
IF allows you to choose one of two values according to a logical operation.
ISNULL returns true or false according to whether or not the value is NULL

SQL: INSERT 1 if value=0 and 0 if value=1

I have data from an SQL query that is 'fileUnavailable' and need to insert into another table that is 'fileAvailable.' The values are either 1 or 0 and I need to do an SQL insert. Since fileUnavaiable and fileAvailable are opposite, I'd need to change the first value to either 1 if it's 0 or 0 if it's 1. Originally, I was thinking to just do an if, else statement to change the value, but that seems bulky and seems too simple for there not to be a method already.
I'm mostly curious as to whether or not SQL has something like !(fileUnavailable) but works for 1 and 0 because these values are ints in my db.
Pseudo:
INSERT INTO table (fileAvailable) VALUES ( NOT($fileUnavailable));
Use a hint with ABS:
UPDATE table SET field = ABS(field - 1)
So if field is 1, then field - 1 is 0, abs(0) is still 0.
And if field is 0, then field - 1 is -1, abs(-1) is 1.
ABS() man page.
For query you provided in a question:
INSERT INTO table (fileAvailable) VALUES ( ABS($fileUnavailable - 1) );
I found this from another stack overflow question.
INSERT INTO `table` SET `my_bool` = NOT my_bool
Update a boolean to its opposite in SQL without using a SELECT

How to parse tab-delimited file into mysql database

I was tasked with parsing a tab-delimited file and inserting the values into the database. Find a selection of the tab-delimited file below.
"030-36-2" 0 0 14 "P"
"030-38-2" 0 0 14 "S"
"030-40-2" 0 0 14 "S"
"031-2-2" 1 0 "O"
"031-3-2" 4 0 "O"
"032-36-26" 0 0 14 "S"
"032-38-26" 0 0 14 "S"
"032-40-26" 0 0 14 "S"
"070-140-161" 0 0 14 "S"
"070-140-162" 2 0 "D"
"070-83-161" 0 0 14 "S"
I'm using fgetcsv with my delimiter set to a tab (9) but upon executing the code I am only getting a small percentage of total values inserted into the database.
This is my code:
if(($handle = fopen("mytabdelimitedfile.txt","r"))!==FALSE){
fgetcsv($handle, 0,chr(9));
while(($data = fgetcsv($handle,1000,chr(9)))!==FALSE){
print_r($data[0]);
$result = mysql_query("INSERT INTO $table (col1,col2,col3,col4,col5) VALUES('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]')");
}
}
The first 4 records are not inserted but it starts with "031-3-2", then skips down to "070-140-162". I fear the result may have to do with some values missing but I cannot seem to discern a pattern.
Does anyone have any insight regarding this? Does the issue have to do with some values missing? Is there any workaround? (I don't have any control over source data)
Also another note: when I use Excel => import data from text => tab-delimited, the results are perfect. But of course I cannot use Excel as the data is updated on an hourly basis. Please, any point in the right direction would be GREATLY appreciated.
Like VMai saide, use LOAD DATA INFILE
LOAD DATA LOCAL INFILE 'mytabdelimitedfile.txt'
INTO TABLE table_name
FIELDS
TERMINATED BY '\t'
OPTIONALLY ENCLOSED BY '"'
(col1,col2,col3,col4,col5)
Also, I really hope those aren't your actual column names.
And don't rely on Excel as an example for anything. It hasn't handled CSV in a sane manner since at least 2007.

PHP and SQLSRV isn't inserting all the rows it should

I'm utilizing PHP 5.5 and connecting to a MS SQL database. Connection works as expected. I'm attempting to do a mass insert (around 2000 rows). Rather than using PHP to run 2000 INSERT statements, I'm sending a query like so:
DECLARE #count INT
SET #count = 0
WHILE(#count < 2000)
BEGIN
INSERT INTO Table (Field1, Field2)
VALUES ('data1', 'data2')
SET #count = (#count + 1)
END
When I plug this query directly into SQL Server Mangement Studio, it inserts 2000 rows as expected. When I run the query via PHP like so:
$connectInfo = array ("UID"=>'user',"PWD"=>'#pass',"Database"=>"database", "ReturnDatesAsStrings"=>true);
$link = sqlsrv_connect("dataserver",$connectInfo);
$query = "DECLARE #count INT
SET #count = 0
WHILE(#count < 2000)
BEGIN
INSERT INTO License (Field1, Field2)
VALUES('data1','data2')
SET #count = (#count + 1)
END";
if(!$foo = sqlsrv_query($link,$query)) {
die(print_r(sqlsrv_errors(), true));
}else{
die("hooray beer time!");
}
This only inserts 524 rows in the table, not the expected 2000 (and some times it's 309 rows, X rows, its erratic). It doesn't error out, and I get "hooray beer time!" after every script run. By default, sqlsrv_query() function has no time limits, I thought. Has anyone run into anything like this before? It has me baffled.
Ahh, it seems that after each insert in the While loop, SQL returns a little row of Text that says (1) row affected (or something to that tune). Turning this off via:
SET NOCOUNT ON
has remedied this issue. Thanks all!

sql statement to chose the value of a field in the last entry

I have created a mysql database table which has two fields, serial # (primary key, auto increment) and version.
What I want to do is for every insert that I do to this database, set the version value to be 1, then 2, 3, 4, 5 and then back down to 1 again.
I can imagine doing this by pulling out the last entry in the table before doing an insert. How can I do this? Is there an easier way? I am using PHP.
You can use the built in MySQL Triggers: http://dev.mysql.com/doc/refman/5.0/en/triggers.html
You can create a database trigger to do what you want. The syntax is something like this:
CREATE
TRIGGER `event_name` BEFORE/AFTER INSERT/UPDATE/DELETE
ON `database`.`table`
FOR EACH ROW BEGIN
-- trigger body
-- this code is applied to every
-- inserted/updated/deleted row
END;
Edit:
Triggers are created directly in the database side. You can connect using the MySQL CLI or the PHPMyAdmin to run the query.
Also, a lazy solution may be to use a query similar to what aaaaaa123456789 suggested:
SELECT (
(SELECT version FROM <table name here> ORDER BY id DESC LIMIT 0, 1) % 5
) + 1 as version;
The modulos (%) operator returns the rest of the division of the two numbers and can be used to limit your increments.
Ex.:
1 % 5 = 1
2 % 5 = 2
3 % 5 = 3
5 % 5 = 0
7 % 5 = 2
10 % 5 = 0
PS.: I haven't tryed this query, 'cause I'm not on my dev machine, but from my mind it works.
The easiest way is, as rcdmk suggested, to write a trigger in the database itself, that updates the version field with the corresponding value.
If a trigger is just out of the window for any reason, then you could just do SELECT version FROM <table name here> ORDER BY id DESC LIMIT 0, 1 to get the last value. In fact, bracketting that (as in, putting it between parentheses) and sending 1 + (query here) to the INSERT query as the insertion value is probably the best way to do it, since it avoids race conditions.
$next_increment = 0;
$qShowStatus = "SHOW TABLE STATUS LIKE 'yourtable'";
$qShowStatusResult = mysql_query($qShowStatus) or die ( "Query failed: " . mysql_error() . "<br/>" . $qShowStatus );
$row = mysql_fetch_assoc($qShowStatusResult);
$next_increment = $row['Auto_increment'];

Categories