Uncaught PDOException when using åäö - sql-server

I use to use sqlsrv_connect but changed it to PDO.
Now i got this syntax error when using åäö.
When i used sqlsrv_connect i could do this:
SELECT Order, [Benämning], [Vår ref] FROM table
and it worked.
Now i'm trying to figure out how to do it with PDO.
So i tried:
SELECT Order, [Benämning], Antal FROM table
And got this error:
Operand type clash: text is incompatible with float
And i tried:
SELECT Order, Benämning, Antal FROM table
And i got error:
Incorrect syntax near '�'.
In the connection i added utf8:
$sql = new PDO("odbc:Driver=$driver;server=$serverName,$port;Database=$database;ConnectionPooling=0", $uid, $pwd,
array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
)
);
Now, when pasting this i can se: PDO::MYSQL_ATTR_I... I'm connecting to SQL.. not MYSQL. Can this be the problem?
If i remove the "Benämning" column and just select columns without åäö or space the select works just fine.
UPDATE
I got åäö to work with sqlsrv instead of odbc.

You simply need to use the same driver (PHP Driver for SQL Server) and the same connection options when you create the PDO instance.
<?php
...
try
$sql = new PDO("sqlsrv:Driver=$driver;server=$server,$port;Database=$database", $uid, $pwd);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
...
} catch( PDOException $e ) {
...
}
try {
$sql = "SELECT [Vår ref], ... FROM ...";
$stmt = $conn->prepare($sql);
$stmt->execute();
} catch( PDOException $e ) {
...
}
?>
Some additional notes:
You need to quote the column name ([Vår ref]) to make the string literal a valid SQL Server identifier.
Use driver specific PDO connection attributes (PDO::SQLSRV_xxx) to add driver specific features. The PDO::MYSQL_ATTR_INIT_COMMAND option is useful if you connect to MySQL instance.

Related

How use CodeIgniter querybuilder with inserting data to MSSQL (newid() )

For id i use uniqueidentyfier, and in queries insert i write: newid() in, but, how do this in Query builder?
{
$db = \Config\Database::connect();
$data = [
'id' => 'newid()',
'id_zgloszenia' => $idpp,
'response' => $response_pp,
'header_response' => $head_res,
'data_datetime' => 'getdate()',
];
$builder = $db->table('DOM5_PP_LOGI');
$builder->insert($data);
}
I try like above, and also: $builder->set('id', uniqid());
But i had error:
[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Conversion failed when converting from a character string to uniqueidentifier.
You can try this to generate UUID by MSSQL:
$builder->set('id', 'NEWID()', FALSE);
Explain: set() will also accept an optional third parameter ($escape), that will prevent data from being escaped if set to FALSE. To illustrate the difference, here is set() used both with and without the escape parameter.
You can get find out more here: https://codeigniter.com/userguide3/database/query_builder.html#id8

CakePHP 3 format date in select query

I am using CakePHP 3 in my project and I came across of a need to format date for date_joined and date_inactivefield in my report. I can use native select query with date function to format date for the field, but in CakePHP, I am not sure how can I integrate date format in select query.
$query = $this->CustomersView->find();
$query->select(['id','contact_person',''date_joined',
'date_inactive','comments','status']);
$query->toArray();
UPDATE
I also tried one of the example from CakePHP online resource
$date = $query->func()->date_format([
'date_joined' => 'literal',
'%m-%d-%y' => 'literal'
]);
$query->select(['id','contact_person',''date_joined',
'date_inactive','comments','status']);
$query->toArray();
But it throws me error below:
'Error: SQLSTATE[42000]: Syntax error or access violation: 1064 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 '%m-%d-%y)) AS `datejoined`, CustomersView.date_inactive AS `CustomersView__date_' at line 1'
SQL query generated by CakePHP:
SELECT CustomersView.id AS `CustomersView__id`,
CustomersView.contact_person AS `CustomersView__contact_person`,
(date_format(date_joined, %m-%d-%y)) AS `datejoined`,
CustomersView.date_inactive AS `CustomersView__date_inactive`,
CustomersView.comments AS `CustomersView__comments`,
CustomersView.status AS `CustomersView__status`
FROM customers_view CustomersView
Any help is really appreciated. :)
Thanks,
Ray
If the date fields are of an appropriate type in your schema (e.g. DATETIME), Cake will return DateTime objects that can be formatted using plain PHP - you don't need to do it in the select.
Example:
$query = $this->CustomersView->find();
$query->select(['id','contact_person','date_joined',
'date_inactive','comments','status']);
$array = $query->toArray();
foreach ($array as $row) {
echo $row["date_joined"]->format("dMY");
}
Let's say for example that your query only returned one row, and the date_joined field here was set to 2015-12-21 23:55:00. The above code would simply print out 21Dec2015.
You can use the DATE_FORMAT($field, %d-%m-%Y) from MySQL.
Here it is an example:
$query = $this->CustomersView->find();
$query->select(['id','contact_person',''DATE_FORMAT(date_joined, "%d-%m-%Y")',
'date_inactive','comments','status']);
Fixed the problem with below code:
$query = $this->CustomersView->find();
$date = $query->func()->date_format([
'date_joined' => 'literal',
"'%m-%d-%y'" => 'literal'
]);
$query->select(['id', 'contact_person', 'date_joined' => $date,
'date_inactive', 'comments', 'status']);
$query->toArray();

Column "" declared twice in table "status" in Propel 2

I'm trying to reverse generate a schema from a MSSQL database using Propel 2. I've set up my YAML configuration file as usual:
dbname:
adapter: mssql
classname: Propel\Runtime\Connection\ConnectionWrapper
dsn: "dblib:host=123.456.789.012;dbname=dbname"
user: username
password: password
attributes:
When I run the command propel reverse 'dbname' I receive the error:
[Propel\Generator\Exception\EngineException]
Column "" declared twice in table "Status"
Which is obviously thrown here:
https://github.com/propelorm/Propel2/blob/master/src/Propel/Generator/Model/Table.php#L499
#r499
Why does Propel attempt to add 'empty' columns? My SQL server management studio does not display empty columns at all when I look at the design of the DB table Status, it only displays the two columns it contains (uid and name).
Edit:
So I went digging into the code of Propel, and it seems to go wrong here:
https://github.com/propelorm/Propel2/blob/62859fd0ed3520b7d7afbbdeac113edaf160982b/src/Propel/Generator/Reverse/MssqlSchemaParser.php#L124
protected function addColumns(Table $table)
{
$dataFetcher = $this->dbh->query("sp_columns '" . $table->getName() . "'");
foreach ($dataFetcher as $row) {
$name = $this->cleanDelimitedIdentifiers($row['COLUMN_NAME']);
$table->getName() correctly returns the right table name. When I print dataFetcher it's a PDO object. However:
$row gives the following array:
Array(
[0] => My DBname
[1] => My DBprefix
[2] => Status
[3] => uid
[4] => 4
[5] => int identity
etc. no string indices hence COLUMN_NAME is empty.
(Posted on behalf of the OP):
This is a bug in the Propel MSSQL schema parser: https://github.com/propelorm/Propel2/issues/863.

Doctrine2 issue with running GROUP BY against a MSSQL

I'm trying to run a custom query on my DB with Doctrine2 using the following:
$qb = $em->createQueryBuilder();
$qb->select(array('c', 'count(uc) as numMembers'))
->from('AcmeGroupBundle:Group', 'c')
->leftJoin('c.members', 'uc', 'WITH', 'uc.community = c.id')
->groupBy('c')
->orderBy('numMembers', 'DESC')
->setFirstResult( $offset )
->setMaxResults( $limit );
$entities = $qb->getQuery()->getResult();
This query runs flawlessly on my local MySQL DB. But when I try to run it against my production DB (MSSQL), i get the following error:
SQLSTATE[42000]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Column 'Group.discr' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
I do have a discriminator column because I have classes inheriting from Group.
Any suggestions on how should I change the query to make it compatible with MSSQL?
Thanks!

how to connect SQL Server with perl

I know there is a similar question: Connect to SQL Server 2005 from Perl and do a SELECT , but I tried the accepted answer and am unable to get it to work.
Assuming I have a db named test, and would love to do a select from mytable
(select id, name from mytable)
Code is from the link above with updated dsn:
use strict;
use warnings;
use DBI;
# Insert your DSN's name here.
my $dsn = 'database=test'
# Change username and password to something more meaningful
my $dbh = DBI->connect("DBI::ODBC::$dsn", 'username', 'password')
# Prepare your sql statement (perldoc DBI for much more info).
my $sth = $dbh->prepare('select id, name from mytable');
# Execute the statement.
if ($sth->execute)
{
# This will keep returning until you run out of rows.
while (my $row = $sth->fetchrow_hashref)
{
print "ID = $row->{id}, Name = $row->{name}\n";
}
}
# Done. Close the connection.
$dbh->disconnect;
This is what I got when running the script:
Can't connect to data source 'ODBC::database=test' because I can't work out what
driver to use (it doesn't seem to contain a 'dbi:driver:' prefix and the DBI_DR
IVER env var is not set) at script.pl line 9
Looks like the problem is in the dsn but I have no idea how to fix it (I am on sql 2005, active perl 5.10 and windows xp).
Edit:
I used the following code to verified whether ODBC is installed.
use DBI;
print join (", ", DBI->installed_versions);
Output:
It looks like ODBC is indeed in the list.
ADO, CSV, DBM, ExampleP, File, Gofer, ODBC, SQLite, Sponge, mysql
What am I missing?
I got the same error with SQLite just now, and it looks like you did the same thing wrong as me. Note the number of colons in the first argument - this is the wrong format:
my $db = DBI->connect('DBI::SQLite::dbname=testing.db', '', '', {RaiseError => 1, AutoCommit => 1});
There should actually only be two colons, not two pairs of colons in the first argument:
my $db = DBI->connect('DBI:SQLite:dbname=testing.db', '', '', {RaiseError => 1, AutoCommit => 1});
Question answered despite its age because it's still top of the results in Google for this particular error message
Try setting your DSN to something like:
my $dbh = DBI->connect("dbi:ODBC:test", 'username', 'password')
If that doesn't work, ensure you have DBD::ODBC installed by running:
perl -MDBI -e 'DBI->installed_versions;'
Assume SQL server is located on local server, connection below can be right:
my $DSN = "driver={SQL Server};Server=127.0.0.1;Database=test;UID=sa;PWD=123456";
my $dbh = DBI->connect("dbi:ODBC:$DSN");

Resources