How to use Prepare methods in joomla model?
for example in pdo we use :
db->prepare('INSERT INTO tbl (`city`,`date`,`uid`,`title`) VALUES(:city,:date,:uid,:title)');
How can I do it in the Joomla!
How to use Prepare methods in joomla model?
for example in pdo we use :
db->prepare('INSERT INTO tbl (`city`,`date`,`uid`,`title`) VALUES(:city,:date,:uid,:title)');
How can I do it in the Joomla!
In Joomla, you always stick to the API which caters for the supported database types, like so:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$columns = array('city', 'date', 'uid', 'title');
$values = array($db->quote('value1'), $db->quote('value2'), $db->quote('value3'), $db->quote('value4'));
// Prepare the insert query.
$query
->insert($db->quoteName('#__tablename')) //make sure you keep #__
->columns($db->quoteName($columns))
->values(implode(',', $values));
$db->setQuery($query);
$db->query();
and for Joomla 3.x, you can replace $db->query();
with $db->execute();
As far as I know, Joomla 4 will use prepared statements in core. Here is a something I've mocked up, however have not tested:
use Joomla\CMS\Factory;
use Joomla\Database\ParameterType;
$db = Factory::getDbo();
// Your data
$city = $db->quote('London');
$date = $db->quote('21/01/2020');
$uid = $db->quote(1234);
$title = $db->quote('My Title');
// Prepared query
$query = $db->getQuery(true)
->insert($db->quoteName('#__tablename'))
->columns([
$db->quoteName('city'),
$db->quoteName('date'),
$db->quoteName('uid'),
$db->quoteName('title'),
])
->values(':city, :date, :uid, :title')
->bind(':city', $city, ParameterType::STRING)
->bind(':date', $date)
->bind(':uid', $uid, ParameterType::INTEGER)
->bind(':title', $title, ParameterType::STRING);
$db->setQuery($query);
$db->execute();
food
WHERE taste = :taste". I am using MySQL, might be that the problem? –
Caesium quote()
is unnecessary on bound values, correct? I don't have a J4 installation to test with. @Lod –
Sosthenna quote()
isn't a value sanitising method. –
Sosthenna © 2022 - 2024 — McMap. All rights reserved.