簡體   English   中英

如何在PHP變量中插入PHP變量並顯示它?

[英]How do I insert a PHP Variable inside a PHP Variable and Display it?

因此,我正在創建一個系統,該系統搜索並顯示MySQL表數據庫中的結果,並且試圖弄清楚如何將結果存儲在php變量中,以便可以格式化和處理它,而不是使用printf函數。 但是,它似乎無法理解我在變量中的內容:

<?php
if(isset($_POST['submit']))
{ 
    if(isset($_GET['go']))
    { 
        if(preg_match("/[A-Z  | a-z | 0-9]+/", $_POST['search-input']))
        { 
            $searchcondition=$_POST['search-input']; 
            //connect  to the database 
            $database = "mysql";
            $hostname = "localhost";
            $link = new mysqli($hostname, "root", "", $database);
            //$link = mysqli_connect($hostname, "root", "", $database);
            if (!$link) 
            {
                echo "Error: Unable to connect to MySQL." . PHP_EOL;
                echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
                echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
                exit;
            }
$query1 = "SELECT `Title`, `Date` FROM `search-database` WHERE `Title` LIKE '%" . $searchcondition . "%' ";
//$query1 = "SELECT `ID`,`FirstName`, `LastName`, `Email`, `PhoneNumber` FROM `test` WHERE `FirstName` LIKE '%" . $searchcondition . "%' AND `Email` LIKE '%" . $searchcondition . "%' ";
if ($result = $link->query($query1)) 
{
    /* fetch associative array */
    while ($row = $result->fetch_assoc()) 
    {
        $string = '$row["Title"], $row["Date"]'; 
        echo $string;


        /* The $string variable above is not recognizing what I just put above. When I do no single quotes, it gives an error. When I do put single quotes, it prints out the actual characters "$row["Title"], $row["Date"]" rather than what the variables actually store.

        here is the Original Code (which does work): 
        printf ("%s, %s, %s, %s, %s\n", $row["ID"], $row["FirstName"], $row["LastName"], $row["Email"], $row["PhoneNumber"]);
        */
                }


    /* free result set */
    $result->free();
}
mysqli_close($link);
    }
    else
    { 
        echo  "<p>Please enter a search query</p>"; 
    } 
} 
}
?> 

上面的$ string變量無法識別我放置在其中的內容。 當我不使用單引號時,它顯示一個錯誤。 當我用單引號引起來時,它將打印出實際字符$row["Title"]$row["Date"]而不是變量實際存儲的內容。

這是原始代碼(有效):

printf ("%s, %s\n", $row["Title"], $row["Date"]);

除了回顯存儲printf內容的單獨變量($ string)之外,如何使php顯示與原始printf函數相同的PHP,或者是否有更簡單的方法來顯示信息並仍然能夠輕松地對其進行格式化?

我只會發表評論,但我沒有足夠的觀點。 這還不夠嗎?

<?php
    $string = $row["Title"] . ", " . $row["Date"];
    echo $string;
?>

您可以連接如下所示的任何變量。

while ($row = $result->fetch_assoc()) 
{
    echo $string = $row["Title"].','. $row["Date"].'\n'; 

 }

如果您已經有了printf ,請考慮使用sprintf ,它類似於printf ,但是將結果存儲在變量中而不是打印它:

<?php
    ....
    $string = sprintf ("%s, %s\n", $row["Title"], $row["Date"]);
    ....

在這種情況下,不需要單引號。 由於您需要在字符串之間使用“,”,因此可以編寫如下代碼

$string = $row["Title"].",". $row["Date"]; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM