简体   繁体   中英

Why won't truncateTable work in Joomla 3.7?

I have the following code attempting to truncate a table. The Joomla documentation makes me believe this will work, but it does not. What am I missing?

$db = JFactory::getDbo();
truncate_query = $db->getQuery(true);
//$truncate_query = 'TRUNCATE ' . $db->quoteName('#__mytable');
$truncate_query->truncateTable($db->quoteName('#__mytable'));
$db->setQuery($truncate_query);
echo $truncate_query;
exit();

If I use the line that is commented out to manually generate the SQL, it does work. The reason I am still looking to use the truncateTable function is that I am trying to include the truncation in a transaction. When I use the manual statement, the table is still truncated even if another part of the transaction fails, which is annoying since the other statements rely on data that is truncated, so if the table is emptied when it shouldn't be there is no data left to run the transaction again. Very annoying!

Here's how you call/execute your truncation query:

JFactory::getDbo()->truncateTable('#__mytable');

And now some more details...

Here is the method's code block in the Joomla source code:

 public function truncateTable($table) { $this->setQuery('TRUNCATE TABLE ' . $this->quoteName($table)); $this->execute(); } 

As you can see the truncateTable() method expects a tablename as a string for its sole parameter; you are offering a backtick-wrapped string -- but the method already offers the backtick-wrapping service. (Even if you strip your backticks off, your approach will not be successful.)

The setQuery() and execute() calls are already inside the method, so you don't need to create a new query object nor execute anything manually.

There is no return in the method, so the default null is returned -- ergo, your $truncate_query becomes null . When you try to execute(null) , you get nothing -- not even an error message.

If you want to know how many rows were removed, you will need to run a SELECT query before hand to count the rows.

If you want to be sure that there are no remaining rows of data, you'll need to call a SELECT and check for zero rows of data.

Here is my answer (with different wording) on your JSX question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM