首页 > 解决方案 > 使用其他数据库中的变量执行函数

问题描述

我正在尝试使用来自其他数据库的值执行一个函数。

我正在使用带有 2 个 DB、Postgresql 和 MariaDB 的框架 CakePHP 4.x。

在 Controller/Programscontroller.php 中:

use Cake\Datasource\ConnectionManager;

public function pro()
{    $connection = ConnectionManager::get('default');// Postgresql,in this one i have my function test(character varying,bigint,bigint)
     $connection2 = ConnectionManager::get('test');// MariaDB, in this one i want some variables
     $data = $connection2->execute('SELECT stuffs from stuff'); //My $data i want
      foreach ($data as $data) //I declare here 3 variables, to save some $data
    {  $w1=$data['cod_item']; 
       $w2=$data['fecha_solicitud_pago'];
       $w3=$data['monto_total'];
       $connection->execute('SELECT test(w1,w2,w3)');//here is my problem
      }    
}

我执行并出现错误 SQLSTATE [42703]:未定义的第 7 列,不存在列 w1。如何定义我的 3 个变量 w1、w2、w3 并在其他 DB 的函数中使用它们的正确方法。

标签: postgresqlcakephpmariadbcakephp-4.x

解决方案


我看到两个问题:

1. $connection->execute('SELECT test(w1,w2,w3)');没有使用php变量。它应该是:

$connection->execute("SELECT test($w1,$w2,$w3)");

请注意,您必须使用双引号才能在字符串中使用变量。

2.您必须以正确的形式使用该功能。如果函数接收到 (text,date,number) 你必须相应地发送它:

$connection->execute("SELECT test('$w1','$w2',$w3)");
// or, for more accuracy
$connection->execute("SELECT test('$w1'::text,'$w2'::date,$w3)");

当你这样做时,$connection->execute()你正在执行一条 SQL 语句,所以它必须写得很好。上面的例子在 POSTGRESQL 中会被解释为:

SELECT test('asbd'::text,'2020-02-05'::date,39021)

假设 php 变量具有这些值。


推荐阅读