如何在 Joomla 中使用准备好的语句? [英] How to use prepared statements in Joomla?

查看:12
本文介绍了如何在 Joomla 中使用准备好的语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在joomla模型中使用Prepare方法?
例如在 pdo 中我们使用:

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

我怎样才能在 Joomla 中做到这一点!

How can I do it in the Joomla!

推荐答案

在 Joomla 中,您总是坚持使用迎合支持的数据库类型的 API,如下所示:

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();

对于 Joomla 3.x,您可以将 $db->query(); 替换为 $db->e​​xecute();

and for Joomla 3.x, you can replace $db->query(); with $db->execute();

据我所知,Joomla 4 将在核心中使用准备好的语句.这是我模拟的东西,但尚未测试:

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 JoomlaCMSFactory;
    use JoomlaDatabaseParameterType;

    $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();

这篇关于如何在 Joomla 中使用准备好的语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆