In the old cakePHP 2.X I used this statement:
$this->Products->query('TRUNCATE TABLE products;');
which was the only way I could get my ids reset to 1. Now in cakephp 3.X this does not seem to truncate the table at all.
I have tried:
deleteAll();
Which works but seems to always need a condition but most importantly does not reset the ID;
query()->delete()->execute();
Deletes everything but does not reset the ids.
Does anyone know how to accomplish this in Cakephp 3.2
Include "ConnectionManager" namespace in the controller
use Cake\Datasource\ConnectionManager;
Create connection string and execute query in your action
$connection = ConnectionManager::get('default');
$results = $connection->execute('TRUNCATE TABLE tableName');
The way you can execute arbitrary queries in CakePHP3 is:
$connection = \Cake\Datasource\ConnectionManager::get('default');
$connection->execute('TRUNCATE TABLE products');
http://book.cakephp.org/3.0/en/orm/database-basics.html#database-basics
Related
I've managed to create a module that can connect to a second database next that one from the shop. It started an setup script to create the new table and I inserted one test data.
So far so good.
Now I want to get that data inside an observer.
I can get the model and the collection. Bbut when I count that collection it returns null. When I try getSelectSql(true) on that model that query looks like:
SELECT `main_table`.* FROM `custom_table` AS `main_table`
Running that query in the database returns my added test data.
app/etc/local.xml
<config>
<global>
<resources>
<external_db>
<connection>
<host><![CDATA[127.0.0.1]]></host>
<username><![CDATA[db_user]]></username>
<password><![CDATA[db_pass]]></password>
<dbname><![CDATA[external_db]]></dbname>
<active>1</active>
</connection>
Observer
public function validateRequest(Varien_Event_Observer $observer) {
try {
$collection = Mage::getModel('custom_module/custom_table')->getCollection();
$items = $collection->getItems();
That returns me the following exception:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'shop.custom_table' doesn't exist, query was: SELECT main_table.* FROM custom_table AS main_table
It looks like magento isn't able to choose the correct connection.
But I can't find the way to change that in a magento way.
The only way it works is:
$resource = Mage::getSingleton('core/resource');
$conn = $resource->getConnection('externaldb_read');
$results = $conn->query('SELECT * FROM custom_table');
I would like to do it without creating raw queries.
use setConnection() method before you load your collection. The Argument should be a valid core/resource object with your database selected.
I'm trying to figure out a way to use WPDB to load a whole row or single cells/fields from another table (not the Wordpress-DB) and displaying them in a shortcode. I have a bunch of weatherdata-values, I need the latest row (each column is another data-type (temp, wind, humidity, etc) of the database for a start.
Sadly, the plugin that would do everything that I need, SQL Shortcode, doesn't work anymore. I found this now:
https://de.wordpress.org/plugins/shortcode-variables/
Though I still need to use some PHP/PDO-foo to get the data from the database.
By heavy copy&pasting I came up with this:
<?php
$hostname='localhost';
$username='root';
$password='';
$dbname='sensordata';
$result = $db->prepare(SELECT * FROM `daten` WHERE id=(SELECT MAX(id) FROM `daten`););
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
$data = $row['*'];
}
echo $data;
?>
But obviously it's not working. What I need to get it done with WPDB?
kind regards :)
Just in case anyone else needs this in the future. I used this now:
//connect to the database
<?php
$dbh = new PDO('mysql:host=localhost;dbname=databasename', 'dbuser',
'dbpasswort');
//query the database "databasename", selecting "columnname" from table "tablename", checking that said column has no NULL entry, sort it by column "id" (autoincrementing numeric ID), newest first and just fetch the last one
$sth = $dbh->query("SELECT `columnname` FROM `tablename` WHERE `columnname` IS NOT NULL order by id desc limit 1")->fetchColumn(0);
//print the value/number
print_r($sth);
?>
By using "SELECT colum1, colum2,... FROM" You should get all the columns, could be that fetchColumn needs to be replaced with something different though.
I want to execute query in my yii2 application. I'm using PostgreSQl. There is a table called list inside the user schema. If I try to build any query it returns 1. My code is here:
$numUsers = Yii::$app->db->createCommand('
SELECT COUNT(*) FROM "user"."list"
')->execute();
Please show me my mistake in the query above.
This is not related to the DB type in Yii2 if you want the result of a single value you should use queryScalar() instead of execute()
$numUsers = Yii::$app->db->createCommand('
SELECT COUNT(*) FROM "user"."list" ')->queryScalar();
I can limit the size of characters of table field in mysql as simple
SELECT NID,LEFT(BODY, 10) AS text FROM tablename
but how can i get the same result in codeigniter Active Record
I tried this code
$this->db->select('NID, LEFT(BODY,10)');
$query = $this->db->get_where('tablename');
but not working
is it possible to make that in codeigniter Active Record ??
I've been able make it work in Codeigniter using a syntax like this:
$this->db->select('NID, LEFT(BODY,10) BODY', false);
$query = $this->db->get_where('tablename');
as stated in: http://ellislab.com/forums/viewthread/201014/#940615
adding 'false' to select, avoids the automatic backtics
also, after left(BODY, 10), you must add the name the new chopped field will use:
select('NID, LEFT(BODY,10) BODY'
otherwise, Codeigniter will output an Undefined property error.
I hope it works!
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);