如何从变量传递函数中的变量

时间:2018-08-24 14:54:19

标签: php function variables

我在通过函数创建查询时遇到问题(所有其他变量均正常工作)我有一个函数无法正确打印变量(恰好是$ NomiFarmacie和$ day)

//The problem is present in this function
function Cicla($Periodo, $FarmacieRiordinate, $Query) {
    global $tabella_calendario, $count; //them works

    foreach ($Periodo as $giorno)   {
        $day = $giorno->format("Y-m-d");
        $NomiFarmacie = addslashes($FarmacieRiordinate[$count % count($FarmacieRiordinate)]);

        echo $NomiFarmacie; echo $day; //Both are correct
        print_r($Query); //Queries are not completed correctly. OUTPUT Below
        $count++;
    }
}

$FarmacieRiordinate = $_POST['elementi'];
$DataIniziale = $_POST['data1'];
$DataFinale = $_POST['data2'];
$Query = ("UPDATE $tabella_calendario SET Farmacia='$NomiFarmacie' WHERE Data='$day'");

Cicla(CalcolaPeriodo($DataIniziale, $DataFinale), $FarmacieRiordinate, $Query);

部分输出print_r($ Query)

UPDATE calendario SET Farmacia='Array' WHERE Data='1546297200'
UPDATE calendario SET Farmacia='Array' WHERE Data='1546297200'
UPDATE calendario SET Farmacia='Array' WHERE Data='1546297200'
UPDATE calendario SET Farmacia='Array' WHERE Data='1546297200'

1 个答案:

答案 0 :(得分:0)

问题是您的$Query在传递给函数之前已经作为字符串组合了。 在这种情况下,您可以使用vsprintf

function Cicla($Periodo, $FarmacieRiordinate, $Query) {
    global $tabella_calendario, $count; //them works

    foreach ($Periodo as $giorno)   {
        $day = $giorno->format("Y-m-d");
        $NomiFarmacie = addslashes($FarmacieRiordinate[$count % count($FarmacieRiordinate)]);

        echo $NomiFarmacie; echo $day; //Both are correct
        $realQuery = vsprintf($Query, array($NomiFarmacie, $day));
        print_r($realQuery); //Queries are not completed correctly. OUTPUT Below
        $count++;
    }
}

$FarmacieRiordinate = $_POST['elementi'];
$DataIniziale = $_POST['data1'];
$DataFinale = $_POST['data2'];
$Query = ("UPDATE $tabella_calendario SET Farmacia='%s' WHERE Data='%s'");

Cicla(CalcolaPeriodo($DataIniziale, $DataFinale), $FarmacieRiordinate, $Query);

您可以在此处了解有关vsprintf的更多信息:

  

http://php.net/manual/en/function.vsprintf.php