shenkwen
shenkwen

Reputation: 3880

Joomla3: manually updating a table in the database

I've got many articles that I need to copy to a joomla+k2 site, I don't want to go to backend and add them one by one, so I am now trying to directly update the databse, partly for learning purpose.

I've created a k2 item and duplicated it until I have enough fake items, this way I just need to update the title and introtext and ignore other fields, and I've prepared the articles in JSON.

Now my first question is, where is the best place to put this .PHP file that is going to manipulate the databse? It has to have the database connection ready and not load the page. Currently I am using a copy of the index.php file under ROOT, having commented out $app->execute(); so it won't actually load the page. Although the database connection is good(I successfully "select" data from the table), it feels very awkward, and also I can't use the developer plugins like "j!dump".

Secondly and more importantly, my code doesn't work: I copy the code from this documentation and make as little change as I can, but it doesn't work, the $result is true but the table isn't updated at all. With very little knowledge about joomla coding and database, it is impossible for me to debug it by myself.

define('_JEXEC', 1);

if (file_exists(__DIR__ . '/defines.php'))
{
    include_once __DIR__ . '/defines.php';
}

if (!defined('_JDEFINES'))
{
    define('JPATH_BASE', __DIR__);
    require_once JPATH_BASE . '/includes/defines.php';
}

require_once JPATH_BASE . '/includes/framework.php';

// Set profiler start time and memory usage and mark afterLoad in the profiler.
JDEBUG ? $_PROFILER->setStart($startTime, $startMem)->mark('afterLoad') : null;

// Instantiate the application.
$app = JFactory::getApplication('site');

//mycode
$db = JFactory::getDbo();
$query = $db->getQuery(true);

$fields = array(
    $db->quoteName('title') . ' = ' . $db->quote('asdfasdf')
);

$conditions = array(
    $db->quoteName('id') . ' = 2'
);

$query->update($db->quoteName('#__k2_items'))->set($fields)->where($conditions);
$result = $db->execute();

There is no error and $db->execute() returns true, please teach me when this happens how to debug?

Upvotes: 0

Views: 847

Answers (1)

itoctopus
itoctopus

Reputation: 4261

It is OK to place the file at the same level of the index.php file, but make sure you add some kind of hash to access the file via a browser. For example, the link should be www.yourdomain.com/youfile.php?hash=1234567890

Providing a hash will prevent other people from running your file.

As for your query not working, try the following (there is no need to follow the strict Joomla query methods for a script like this):

$db = JFactory::getDbo();
$sql = "Your SQL query";
$db->setQuery($sql);
$db->query();

Upvotes: 1

Related Questions