sloker antonov
sloker antonov

Reputation: 13

Creating articles programmatically: you have an error in your SQL syntax;

My code:

<?php

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';

require_once JPATH_BASE . '/libraries/joomla/factory.php';

$db = JFactory::getDbo();

$query = $db->getQuery(true);

$columns = array('title', 'fulltext', 'state', 'catid', 'created_by', 'access');

$values = array('test', 'test test test', 1, 9, 889, 1);

$query
  ->insert($db->quoteName('#__content'))
  ->columns($db->quoteName($columns))
  ->values(implode(',', $values));

$db->setQuery($query);
$db->query();

Full error:

    Error displaying the error page: Application Instantiation Error: 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 
'test test, 1 , 9, 889, 1)' at line 3 SQL = INSERT INTO `cxq09_content` (`title`, `fulltext`, `state`, `catid`, `created_by`, `access`) VALUES (test, test test test, 1, 9, 889, 1)

Joomla is installed on OpenServer.

What's wrong?

Upvotes: 0

Views: 88

Answers (1)

VMai
VMai

Reputation: 10346

Quoting the values for the insert statement could be done with

$query
  ->insert($db->quoteName('#__content'))
  ->columns($db->quoteName($columns))
  ->values(implode(',', $db->quote($values)));

if your Joomla version is new enough, see the documentation to quote:

Quotes and optionally escapes a string to database requirements for use in database queries.

quote(mixed $text, boolean $escape = true) : string

Note: Accepting an array of strings was added in 12.3

If your version don't accept an array of strings, you've got to quote every single array element.

Upvotes: 2

Related Questions