簡體   English   中英

PHP / MySQL:如何從PHP數據庫方法獲取多個值

[英]PHP/MySQL: How to get multiple values from a PHP database method

抱歉,這個令人難以置信的新手問題,但是如果我不問的話,我會發現自己陷入了不良做法。

我有一個PHP方法,我想返回給定數據庫列的所有值,以便將內容放在HTML表單的下拉菜單中。 我顯然可以在PHP方法中構造整個HTML並將其作為字符串返回,但是我認為這是非常糟糕的做法。

由於PHP方法只能返回一個值,我想我需要多次調用該方法以填充下拉菜單,或從該方法傳遞一個數組。

對於這個(大概)常見問題,什么是一個好的解決方案? 謝謝。

好吧,數組是一個值,包含大量其他值。 因此,只需讓您的方法返回結果數組即可。

編輯:正如Hammerstein指出的那樣,您可以使用對象,但取決於上下文,其效果與數組一樣好/壞。 非常相似。

您可以使用對象作為返回類型。 所以;

class MyReturnValue 
{
  public $Value1;
  public $Value2;
}

function getMyValues() 
{
  $results = GetDatabaseValues( ); // Assume this returns an associative array

  $result = new MyReturnValue();
  $result.Value1 = $results["Value1"];
  $result.Value2 = $results["Value2"];
}

然后在代碼中,可以引用$ result.Value1等。

沒有PHP函數可以執行此操作,因此您必須從結果中形成一個數組。

$column = array()
$query = mysql_query("SELECT * FROM table ORDER BY id ASC");
while($row = mysql_fetch_array($query)){
    $column[] = $row[$key]
}

然后將$ column傳遞給您的視圖(HTML)

foreach($column as $value)
{
   echo "<li>" . $value . "</li>";
}

您可以在數組中包含數組,因此,如果您的表中有幾列,則可以將它們作為單獨的數組分配給數組:

$all_results = array();
foreach($rowInDatabase as $key => $value){
    // each row will be an array with a key of column name and value of column content depending how you get the data from the DB.
    $colname = $key;
    $colVal = $value; //this is an array
    $all_results[$colname] = $colVal; //append the current row to the array
    }

}

像這樣的代碼將用表的每行數組填充您的數組,因此,如果有十行五列,則可以使用$ all_results [1] [2]來獲得第2行第3列; (因為它們從0開始)。

不太確定我是否完全理解您想要做什么,但是您始終可以將結果從方法傳回,然后在HTML中循環遍歷。

您的方法將類似於:

public function my_method()
{
     $result = $db->query($sql_here);
     return $result;
}

然后您的HTML將是

<select>

<?

    $result = $class->my_method();

    while($row = $result->fetch_assoc())
    {
        echo '<option>'.$row['some_col'].'</option>';
    }

?>

</select>

暫無
暫無

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

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