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
Related
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.
$content = Content::findFirst([
'conditions' => 'state = :state: AND URLid = :url: AND city = :city:',
'bind' => [
'state' => $geodata_usstates->statecode,
'url' => $company,
'city' => $geodata_geocity->city
]
]);
I want to dump the query generated for this. If I were using Laravel, I would simply do
$content->toSql();
But here I'm using Phalcon. How can I achieve the same thing in Phalcon?
Query is not available in your model. Query is build based on model using query builder, passed to Query instance and executed against your db connection.
What you could do is use the events manager and read using the db:beforeQuery event
Example here https://forum.phalconphp.com/discussion/18371/check-the-connection-before-querying-into-database
I don't believe you can output the complete query, because it's a prepared query - thus the best you'd get is:
SELECT * FROM `content` WHERE state = ? AND URLid = ? AND city = ? LIMIT 1
Personally, I don't bother trying to log queries in code. I've enabled the query log on my MariaDB server, and just check the log. The query logged is guaranteed to be the query run.
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();
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.
I have a class with a property of type byte[] that I would like to map to a varbinary(max) field in SQL Server using the new NHibernate ByCode mapping.
So far, using SchemaAction = SchemaAutoAction.Recreate in order to have NH create the schema, I've ended up with the following (the class property name is "Data"):
When mapping is not qualified in any way, I end up with a varbinary(8000) field
When mapping is map.Property(x => x.Data, m => m.Length(int.MaxValue)), I end up with an 'image' field (which, according to SQL Server docs, will not be supported in the next release of SQL Server)
When mapping is map.Property(x => x.Data, m => m.Type(TypeFactory.GetBinaryType(int.MaxValue)), I end up with a varbinary(8000) field, which just seems wrong
What am I missing?
I experienced the same problem and this has worked for me.
Property(e => e.Data, m => m.Column(cm => cm.SqlType("varbinary(MAX)")));