php - 如何回显 Phalcon 中的最后一个查询字符串?

标签 php mysql sql phalcon

我在 codeigniter 方面做了很多工作。在 codeigniter 中,如果需要获取最后执行的查询字符串,我们可以使用:

echo $this->db->last_query();
exit;

但目前我正在研究 phalcon 并且我在这个框架中只是处于初学者水平。我很好奇是否有办法在 phalcon 中回显最后一个查询字符串。

谢谢。

最佳答案

使用原始查询

让我们进行以下查询:

$phql = 'UPDATE `news` SET `category_id` = 5 WHERE `id` = :id';
$this->db->execute($phql, ['id' => 1]);

我们可以通过以下方法获取调试查询信息:

print_r($this->db->getSQLStatement());

UPDATE news SET category_id = 5 WHERE id = :id

print_r($this->db->getSqlVariables());

Array ( [id] => 1 )

您可以在此处找到有关数据库方法的更多信息:https://docs.phalconphp.com/en/latest/api/Phalcon_Db_Adapter_Pdo.html


使用模型

设置您的数据库连接和分析器服务:

use Phalcon\Db\Profiler as ProfilerDb;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Db\Adapter\Pdo\Mysql as MysqlPdo;

$di->set('profiler', function () {
    return new ProfilerDb();
}, true);

$di->set('db', function () use ($di) {

    $eventsManager = new EventsManager();

    // Get a shared instance of the DbProfiler
    $profiler      = $di->getProfiler();

    // Listen all the database events
    $eventsManager->attach('db', function ($event, $connection) use ($profiler) {
        if ($event->getType() == 'beforeQuery') {
            $profiler->startProfile($connection->getSQLStatement());
        }

        if ($event->getType() == 'afterQuery') {
            $profiler->stopProfile();
        }
    });

    $connection = new MysqlPdo(
        array(
            "host"     => "localhost",
            "username" => "root",
            "password" => "secret",
            "dbname"   => "invo"
        )
    );

    // Assign the eventsManager to the db adapter instance
    $connection->setEventsManager($eventsManager);

    return $connection;
});

使用它来调试您的查询:

// Send some SQL statements to the database
Robots::find();
Robots::find(
    array(
        "order" => "name"
    )
);
Robots::find(
    array(
        "limit" => 30
    )
);

// Get the generated profiles from the profiler
$profiles = $di->get('profiler')->getProfiles();

foreach ($profiles as $profile) {
   echo "SQL Statement: ", $profile->getSQLStatement(), "\n";
   echo "Start Time: ", $profile->getInitialTime(), "\n";
   echo "Final Time: ", $profile->getFinalTime(), "\n";
   echo "Total Elapsed Time: ", $profile->getTotalElapsedSeconds(), "\n";
}

有关 Profiler 服务的更多信息:https://docs.phalconphp.com/en/latest/reference/models.html#profiling-sql-statements


Phalcon Prophiler 小工具

我正在使用 Fabian Fülling 为 Phalcon 制作的一个可爱的调试小部件。您可以在此处查看存储库:https://github.com/fabfuel/prophiler下面是正在运行的小部件的示例屏幕截图:

enter image description here

关于php - 如何回显 Phalcon 中的最后一个查询字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38967900/

相关文章:

php - 如何通过 Laravel 统计独立访客并在图表中显示?

MySQL源代码缺少配置文件

MySQL 使用 group by 进行计数和平均值

sql - 未使用 Postgres 索引

python - 如何在 python 中使用 MySQLdb 模块覆盖聚合查询中的 NULL 值?

mysql - 如何在 SQL 中正确使用 GROUP BY 语句?

php - 在中等流量网站上实现消息队列的最佳方式是什么

php - SQL 防止重复插入

PHP:PDO+mysql 无法使用管道符号 (|)

mysql 将旧数据库转移到新数据库