How can i print the sql statement for
$entities = $query
->entityCondition('entity_type', 'node')
->propertyCondition('type', "page")
->propertyCondition('uid', $user->uid)
->fieldCondition('field_item_r1', 'value', $title)
->addTag('debug')->execute();```
Please help me to print the sql statement
You can use (string) $query (I prefer this method if possible) or add ->addTag('debug').
Related
I need to test the structure of my SQLite database which is composed by a unique table with let's say 2 columns (id, name). I can't figure out the SQL query to get the table schema of my database.
I am able to get all the content of the database using the DBI method selectall_arrayref(). However it only returns an array containing the values inside my database. This information is useful but I would like to have a SQL query which returns something like id, name (Basically, the table schema).
I tried the following queries : SHOW COLUMNS FROM $tablename but also SELECT * from $tablename (This one returns all the table content).
Here is my implementation so far :
# database path
my $db_path = "/my/path/to/.database.sqlite";
my $tablename = "table_name";
sub connect_to_database {
# Connect to the database
my $dbh = DBI->connect ("dbi:SQLite:dbname=$db_path", "", "",
{ RaiseError => 1, AutoCommit => 0 },
)
or confess $DBI::errstr;
return $dbh;
}
sub get_database_structure {
# Connect to the database
my $dbh = &connect_to_database();
# Get the structure of the database
my $sth = $dbh->prepare("SHOW COLUMNS FROM $tablename");
$sth->execute();
while (my $inphash = $sth->fetrow_hashref()) {
print $inphash."\n";
}
# Disconnect from the database
$dbh->disconnect();
}
# Call the sub to print the database structure
&get_database_structure();
I expect the output to be the structure of my table so id, name but I raise an error : DBD::SQLite::db prepare failed: near "SHOW": syntax error
I can't find the good query. Any comments or help would be greatly appreciated.
Thanks !
What you're looking for is really just the SQL lite query for the table and column information. This answer SQLite Schema Information Metadata has the full details if this query doesn't work for you, but under the assumption you're using whatever the 'recent' version mentioned in one of the answers is, you can do something like this:
# Get the structure of the database
my $sth = $dbh->prepare("<<END_SQL");
SELECT
m.name as table_name,
p.name as column_name
FROM sqlite_master AS m
JOIN pragma_table_info(m.name) AS p
ORDER BY m.name, p.cid
END_SQL
$sth->execute();
my $last = '';
while (my $row = $sth->fetchrow_arrayref()) {
my ($table, $column) = #$row;
if ($table ne $last) {
print "=== $table ===\n";
$last = $table;
}
print "$column\n";
}
After digging through the community answers I finally find a solution using the pragma table_info.
sub get_database_structure {
# Connect to the database
my $dbh = &connect_to_database ();
# Return the structure of the table execution_host
my $sth = $dbh->prepare('pragma table_info(execution_host)');
$sth->execute();
my #struct;
while (my $row = $sth->fetchrow_arrayref()) {
push #struct, #$row[1];
}
# Disconnect from the database
$dbh->disconnect ();
return #struct;
}
It returns a list of the columns name present in the table execution_host.
Thanks for the help !
I'm using PHP7 (with Droctrine 2.5.13) on Ubuntu 16.04 x64.
I'm trying to do a prepared statment to a Microsoft SQL database using a named variable like so:
$sql = 'SELECT DISTINCT
"PRODUCT"."NUMBER"
FROM
"PRODDB"."PRODUCT"
WHERE
"PRODUCT"."NUMBER" LIKE :productNumber
ORDER BY
"PRODUCT"."NUMBER" DESC';
$query = $this->db->prepare($sql);
$query ->bindParam(':productNumber' , $ofSearch);
$status = $query->execute();
$result = $query->fetchAll();
But SQL tell me that I need to use question mask instead of the named parameter
Error : sqlsrv does not support named parameters to queries, use question mark (?)
If I replace the named variable by a question mark it work fine.
The example below work fine:
$sql = 'SELECT DISTINCT
"PRODUCT"."NUMBER"
FROM
"PRODDB"."PRODUCT"
WHERE
"PRODUCT"."NUMBER" LIKE ?
ORDER BY
"PRODUCT"."NUMBER" DESC';
$query = $this->db->prepare($sql);
$query ->bindParam(1 , $ofSearch);
$status = $query->execute();
$result = $query->fetchAll();
Using question mark is a terrible way to do prepared statement as when you have very complex query with over 20 parameters it become a nightmare to maintain.
Do you have any idea if there is a solution to this problem or at least a workaround?
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 figure out how to have the execute method of an ZF2 SQL Statement class to return an array of objects rather than an array of arrays. The documentation/reference seems to lack severely in this area and the code isn't documented properly.
This is what I have (I'm using the PDO MySQL driver but that should not be relevant):
$sql = new Sql( $db );
$query = $sql->select()
->from('users')
->where('id > 1');
$stmt = $sql->prepareStatementForSqlObject( $query );
$results = $stmt->execute();
$results is now an array of arrays but I need it to be an array of objects instead. How can I specify this?
I think that most people use doctrine for ORM
http://www.jasongrimes.org/2012/01/using-doctrine-2-in-zend-framework-2/
I have been able to create simple MVC app to display the form and use information from the database. [ so sql I use SELECT ].
However, when I use 'update' or 'delete' the data in the database stay the same. I don't understand!?!
[ I use controller.php call model and pass id to match with the row in the table]
I check data that pass in there, and it did echo the value of id.
The page I load from the controller that call method in model has complete without the error (it could be that the syntax is right, but logic is wrong).
so i start to change sql statement to SELECT and it gives me the value that match with $id param'
I don't understand? any clue?
$query = JFactory::getDbo()->getQuery(true);
$db =& JFactory::getDBO();
$query = "DELETE FROM `menutables` WHERE `id2` = $id ";
$db->setQuery($query);
$db->query(); // this line I also take it out to test, it is fine but no data change either
Do you try to modify a Joomla database or a personal one?
Look at this pages :
http://docs.joomla.org/How_to_connect_to_an_external_database
http://docs.joomla.org/How_to_use_the_database_classes_in_your_script#Tips.2C_Tricks_.26_FAQ
try to use either
$query = "DELETE FROM #__menutables WHERE id2 = '$id' ";
or
$query = "DELETE FROM #__menutables WHERE id2 = '".$id."' ";
it'll work fine then.
Deleting a Record
delete query in Joomla 2.5.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
// delete all custom keys for user 1001.
$conditions = array(
$db->quoteName('user_id') . '=1001',
$db->quoteName('profile_key') . '=\'custom.%\''
);
$query->delete($db->quoteName('#__user_profiles'));
$query->where($conditions);
$db->setQuery($query);