Is the method Doctrine_Table::find() deprecated? - php

I had a problem with the method Doctrine_Table::find(), since it's thorowing an exception of
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
I solved the problem by using Doctrine::getTable('City')->findOneById($id); instead and it works fine.
When I tried to invistigate about the problem I was surprised since no documentation about the method Doctrine_Table::find() in the official website.
Any one knows what's the problem? is it deprecated?
BTW it's exists on the actual code! of the version (1.2.1).
more info about the database:
CREATE TABLE IF NOT EXISTS `country` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(64) NOT NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci;
CREATE TABLE IF NOT EXISTS `city` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(64) NOT NULL ,
`country_id` INT NOT NULL ,
PRIMARY KEY (`id`, `country_id`) ,
INDEX `fk_city_country` (`country_id` ASC) ,
CONSTRAINT `fk_city_country`
FOREIGN KEY (`country_id` )
REFERENCES `country` (`id` )
ON DELETE CASCADE
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci;
What's weird is that both Doctrine_Table::find(), and Doctrine_Table::findOneById() works fine on Country table!.
PS: I realize that Doctrine_Table::findOneById() is a __call() generated method. And that make me confused more, why the actual find() method can't behave as expected (is my expectation wrong or what)!

Oh my bad. I didnt see it earlier, shame on me =p
Your table has two primary keys (id and country_id), so the find method requires you to pass both parameters to the find method.
You could instead use the magic methods:
Doctrine::getTable('City')->findOneById(1)

As of v 1.2.1, Doctrine_Table::find() is NOT deprecated
You can check the official documentation on http://www.doctrine-project.org/documentation/manual/1_2/en/component-overview#table:finder-methods
As for the "invalid parameter number" error, it means you query has more or fewer parameters than expected, most often you used a token (?) and forgot to add the parameter to it
Doctrine_Query::create()
->from('User u')
->where('u.name = ?', 'Jonh')
->andWhere('u.is_active = ?')
The example i used have two tokens '?', but only one parameter 'jonh', it would throw the same error: "Invalid parameter number: number of bound variables does not match number of tokens"

Related

Splitting a string with Swift using a PHP-equivalent regular expression (#\n\s*\n#Uis)

I need to split a given multi-line string (sample here) using a regular expression with Swift. With PHP (the language I use for building web applications) I do this (after removing comments and substituting some tokens):
// split the file contents in fragments
$fragments = preg_split("#\n\s*\n#Uis", $contents);
And this is what I get if execute preg_split over the code sample:
Array
(
...
[2] =>
CREATE TABLE IF NOT EXISTS c_search_history (
entry_id BIGINT(64) UNSIGNED NOT NULL AUTO_INCREMENT,
entry_date_added DATETIME NOT NULL,
entry_language CHAR(2) NOT NULL DEFAULT 'es',
entry_query TEXT NOT NULL,
PRIMARY KEY (entry_id),
INDEX (entry_date_added),
INDEX (entry_language)
) ENGINE=InnoDB DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_520_ci;
[3] =>
CREATE TABLE IF NOT EXISTS c_search_weight_entries (
entry_id BIGINT(64) UNSIGNED NOT NULL AUTO_INCREMENT,
entry_date DATETIME NOT NULL,
entry_model VARCHAR(175) NOT NULL,
entry_model_id BIGINT(64) UNSIGNED NOT NULL,
entry_value DOUBLE NOT NULL,
PRIMARY KEY (entry_id),
INDEX (entry_date),
INDEX (entry_model),
INDEX (entry_model_id),
INDEX (entry_value)
) ENGINE=InnoDB DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_520_ci;
...
)
The goal for this is to take an .sql file and flatten its contents so each function, table, procedure, trigger or view definition becomes a one-liner for later execution. The problem is I'm fairly new to Swift and I haven't been able to translate the #\n\s*\n#Uis regular expression into something usable for NSRegularExpression.
I tried to use this solution but it outputs nothing for me (but I may be that I have used it in the wrong way or I don't understand how it really works).
Can you give me a hint? Any help would be greatly appreciated :)
After doing, undoing and trying different approaches, seems the only thing I needed to do was to substitute #\n\s*\n#Uis with \\n\\s*\\n and it worked. I still need to do some serious research on NSRegularExpression and a lot of other Swift concepts but, for now, that did the trick :)

Switch from mySQL to mariaDB timestamp messup

I have switched from MySQL to MariaDB which has caused some "minor" problems. One has been bugging me for hours now and i can't find the solution.
I moved my database by exporting it from MySQL and importing it into MariaDB which went well..
When one of my update queries did not work i narrowed it down to this function in my database handler:
public function updateEquipment($type,$product,$acquisition,$calibration_interval,$equipment_no,$inspection_date,$equipment_id,$active)
{
$stmt = $this->conn->prepare("UPDATE equipment SET type = :type, acquisition = :acquisition, calibration_interval = :calibration_interval, equipment_no = :equipment_no, product = :product, inspection_date = :inspection_date, active = :active WHERE id = :equipment_id");
$stmt->bindParam(":equipment_id", $equipment_id,PDO::PARAM_INT);
$stmt->bindParam(":type", $type,PDO::PARAM_STR);
$stmt->bindParam(":acquisition", $acquisition,PDO::PARAM_STR);
$stmt->bindParam(":calibration_interval", $calibration_interval,PDO::PARAM_STR);
$stmt->bindParam(":equipment_no", $equipment_no,PDO::PARAM_STR);
$stmt->bindParam(":product", $product,PDO::PARAM_STR);
$stmt->bindParam(":inspection_date", $this->formatDateStrToTimeStamp($inspection_date),PDO::PARAM_STR);
$stmt->bindParam(":active", $active,PDO::PARAM_INT);
return $stmt->execute();
}
formatDateStrToTimeStamp function:
private function formatDateStrToTimeStamp($inspection_date)
{
$day = substr($inspection_date,0,2);
$month = substr($inspection_date,3,2);
$year = substr($inspection_date,6,4);
return date('Y-m-d H:i:s', strtotime($year."-".$month."-".$day));
}
As you can see, i have switched out the binding of my inspection_date with a string representing the timestamp i want to update. I tested the statement WITHOUT updating my timestamp and then it was working as expected. As soon as i add the timestamp (in my case i have inserted a static timestamp) the row will NOT update and execute does not return (it should return true or false).
Heres my table structure:
CREATE TABLE `equipment` (
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`type` text NOT NULL,
`acquisition` text NOT NULL,
`calibration_interval` text NOT NULL,
`equipment_no` text NOT NULL,
`product` text NOT NULL,
`inspection_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`active` int(11) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Question: Are timestamps treated different in mariaDB, because i have not made any changes to my code since the switch, and i have simply imported my database from the export i made from my MySQL database.
After debugging my pants off (because im not very good at debugging web applications) i finally found the answer to my problem.
PDO's bindparam must bind a variable to a placeholder or questionmark which is also stated in the pdo documentation. In my case i tried both inserting a string directly when binding, and the original code with the error used the return value of a timestamp formater. In both cases i didn't use a variable when binding to my placeholder, hence the error....
I came across the the error when i debugged the function using Chrome's Advanced Rest Client which revealed an error: "Only variables should be passed by reference".
Solution 1:
$inspect = $this->formatDateStrToTimeStamp($inspection_date);
$stmt->bindParam(":inspection_date", $inspect,PDO::PARAM_STR);
Solution 2:
As pointed out by Ryan Vincent in the comments use bindValue instead (see his comment for further inspiration)
But still a bit confused:
I'm still a bit confused though, as the code previously ran on another host without problems. I cannot remember the PHP version or anything, but if someone could confirm that it was possible in previous version it would explain why...

mysql lock tables causing certain inserts to fail randomly

I recently adding locking to a query to prevent a deadlock. This problem is solved, but now I am having a problem where inserts into one table are randomly failing with no cause. I
I have turned on the general query log to see exactly what is happening. Is there any other way to debug this to see exactly what is happening or have any ideas of the cause?
If I perform the following lock:
$this->db->query('LOCK TABLES '.$this->db->dbprefix('customers').' WRITE, '.$this->db->dbprefix('sales').' WRITE,
'.$this->db->dbprefix('store_accounts').' WRITE, '.$this->db->dbprefix('sales_payments').' WRITE, '.$this->db->dbprefix('sales_items').' WRITE,
'.$this->db->dbprefix('giftcards').' WRITE, '.$this->db->dbprefix('location_items').' WRITE,
'.$this->db->dbprefix('inventory').' WRITE, '.$this->db->dbprefix('sales_items_taxes').' WRITE,
'.$this->db->dbprefix('sales_item_kits').' WRITE, '.$this->db->dbprefix('sales_item_kits_taxes').' WRITE,'.$this->db->dbprefix('people').' READ,'.$this->db->dbprefix('items').' READ
,'.$this->db->dbprefix('employees_locations').' READ,'.$this->db->dbprefix('locations').' READ, '.$this->db->dbprefix('items_tier_prices').' READ
, '.$this->db->dbprefix('location_items_tier_prices').' READ, '.$this->db->dbprefix('items_taxes').' READ, '.$this->db->dbprefix('item_kits').' READ
, '.$this->db->dbprefix('location_item_kits').' READ, '.$this->db->dbprefix('item_kit_items').' READ, '.$this->db->dbprefix('employees').' READ , '.$this->db->dbprefix('item_kits_tier_prices').' READ
, '.$this->db->dbprefix('location_item_kits_tier_prices').' READ, '.$this->db->dbprefix('location_items_taxes').' READ
, '.$this->db->dbprefix('location_item_kits_taxes'). ' READ, '.$this->db->dbprefix('item_kits_taxes'). ' READ');
foreach($items as $line=>$item)
{
if (isset($item['item_id']))
{
$cur_item_info = $this->Item->get_info($item['item_id']);
$sales_items_data = array
(
'sale_id'=>$sale_id,
'item_id'=>$item['item_id'],
'line'=>$item['line'],
'description'=>$item['description'],
'serialnumber'=>$item['serialnumber'],
'quantity_purchased'=>$item['quantity'],
'discount_percent'=>$item['discount'],
'item_cost_price' => $cur_item_info->cost_price,
'item_unit_price'=>$item['price']
);
$this->db->insert('sales_items',$sales_items_data);
}
...
...
}
$this->db->query('UNLOCK TABLES');
Table:
+--------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| phppos_sales_items | CREATE TABLE `phppos_sales_items` (
`sale_id` int(10) NOT NULL DEFAULT '0',
`item_id` int(10) NOT NULL DEFAULT '0',
`description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`serialnumber` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`line` int(3) NOT NULL DEFAULT '0',
`quantity_purchased` decimal(23,10) NOT NULL DEFAULT '0.0000000000',
`item_cost_price` decimal(23,10) NOT NULL,
`item_unit_price` decimal(23,10) NOT NULL,
`discount_percent` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`sale_id`,`item_id`,`line`),
KEY `item_id` (`item_id`),
CONSTRAINT `phppos_sales_items_ibfk_1` FOREIGN KEY (`item_id`) REFERENCES `phppos_items` (`item_id`),
CONSTRAINT `phppos_sales_items_ibfk_2` FOREIGN KEY (`sale_id`) REFERENCES `phppos_sales` (`sale_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci |
+--------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.06 sec)
Then insert into a bunch of tables but randomly I am getting an error where data does NOT make it into sales_items, but correctly makes it into other tables using the item_id foreign key...is there a scenario that can causes inserts to fail randomly because of the locks? I am going to turn on the general query log to see what is happening but I cannot track it down. This never happened before until I added the locking.
Turned out it was related to mysql 5.6 default strict mode setting. Not related to lock

PHP & MySQL, Good query is failing

I am having an odd issue with PHP and MySQL.
In attempt to create a table from PHP, I have pasted in the query I need, which executes successfully outside of the PHP environment, into PHP.
$CREATE_PAGES = "DROP TABLE IF EXISTS `MyDatabase`.`pages`;
CREATE TABLE `MyDatabase`.`pages` (
`Page_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`Page_File` varchar(1000) NOT NULL,
`Page_Description` varchar(1000) NOT NULL,
`Page_Message` longtext NOT NULL,
PRIMARY KEY (`Page_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;";
$result= mysql_query($CREATE_PAGES,$link);
if(!($result)){
echo mysql_error();
echo $CREATE_PAGES;
}
Then I get the standard error message
. . . for the right syntax to use near 'CREATE TABLE `MyDatabase`.`pages` ( `Page_ID` int(10) unsigned NOT NULL' at line 2
However, the odd part is that when I echo the query $CREATE_PAGES I can copy and paste and it will execute just fine. How can it be a syntax error?
I know that it is not a connection error, I can pull data from another table in that database.
Is there something I am missing?
PHP call to mysql_query allows only one action at the time (as a part of SQL injection prvention I guess) so you have to split your query into two parts and call mysql_query twice.
The mysql_query() function can only execute one query at a time, whereas you can execute an arbitrary number at the command line.
From the documentation:
mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier.
To overcome this:
$dropTable = "DROP TABLE IF EXISTS `MyDatabase`.`pages`";
mysql_query($dropTable, $link);
$createPages ="CREATE TABLE `MyDatabase`.`pages` (
`Page_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`Page_File` varchar(1000) NOT NULL,
`Page_Description` varchar(1000) NOT NULL,
`Page_Message` longtext NOT NULL,
PRIMARY KEY (`Page_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;";
$result = mysql_query($createPages, $link);
if(!($result)) {
echo mysql_error();
}
From docs to mysql_query:
mysql_query() sends a unique query (multiple queries are not
supported) to the currently active database on the server that's
associated with the specified link_identifier.
mysql_query can only execute a single query, it doesn't support execution of multiple queries. It's also recommended to not end your query with a semicolon.
Look for more information in the PHP documentation.

What's wrong with this PHP-MySQL CREATE TABLE query?

First, I'm just starting to learn MySQL with PHP.
My query copy/paste directly from my IDE:
$query = "CREATE TABLE IF NOT EXISTS $table_messages (
id int(11) unsigned NOT NULL auto_increment,
show tinyint(1) unsigned NOT NULL default '0',
to varchar(255) NOT NULL default '',
from varchar(255) NOT NULL default '',
type varchar(255) NOT NULL default '',
message varchar(255) NOT NULL default '',
PRIMARY KEY(id)
) DEFAULT CHARSET=utf8 AUTO_INCREMENT=1";
$result = mysql_query( $query, $link ) OR exit ( mysql_error() );
Results in this error:
You have an error in your SQL syntax;
near 'show tinyint(1) unsigned NOT
NULL default '0' , to varchar(255) N'
at line 4
... so I add one character to show (e.g. showz) and get this error:
You have an error in your SQL syntax;
near 'to varchar(255) NOT NULL
default '' , from varchar(255) NOT
NUL' at line 5
... so I add one character to to (e.g. toz) and get this error:
You have an error in your SQL syntax;
near 'from varchar(255) NOT NULL
default '' , type varchar(255) NOT NU'
at line 6
... so I add one character to from (e.g. fromz) and IT WORKS!?
What is going on? Lol
If this question is too blatantly obvious, I'll remove it if the community thinks it would be prudent, but in the meantime I'm stumped.
BTW, I've messed with spacing, case and other things without any success.
SHOW, TO and FROM are reserved MySQL keywords. You must quote them with backticks to make them work as column names:
$query = "CREATE TABLE IF NOT EXISTS $table_messages (
`id` int(11) unsigned NOT NULL auto_increment,
`show` tinyint(1) unsigned NOT NULL default '0' ,
`to` varchar(255) NOT NULL default '' ,
`from` varchar(255) NOT NULL default '' ,
`type` varchar(255) NOT NULL default '' ,
`message` varchar(255) NOT NULL default '' ,
PRIMARY KEY(id)
) DEFAULT CHARSET=utf8 AUTO_INCREMENT=1";
It's usually good practice (though unneeded) to quote every column name this way to prevent accidental collisions with keywords as there are hundreds of them. For a full list, see http://dev.mysql.com/doc/refman/5.1/en/reserved-words.html.
You might be interested in this list of reserved words in MySQL statements. In short, if you want to use any of these as a column name (or anywhere in following queries), you have to quote them, usually in backticks:
`show` TINYINT(1) UNSIGNED NOT NULL,
...and later:
SELECT `show` FROM `varchar` WHERE `to`="France"
Just a stab in the dark, but are to and from reserved words in mysql? Could you either wrap those words in [] like [to] and [from] or, like you did, change the terms to toperson or fromperson?
This is not the answer to your problem, but it's the answer to "What's wrong with a PHP-MySQL CREATE TABLE query?" (for another googler)
Maybe not all versions of PHP are like this, but in my environment, non PDO commands like "mysql_query" throws an error when I try to make a table:
CREATE TABLE IF NOT EXISTS `actionlog`
Error:
You have an error in your SQL syntax
Works just fine with the PDO adapter.

Categories