回聲/打印結果中foreach循環我需要可變code
從URL,所以我$codes = $_GET['code'];
(URL例如website.com/update?code[]=7291&code[]=9274&code[]=8264&
),那麼我SELECT firstname FROM guests WHERE invitecode = $codes"
然後我輸出數據和後來在設定爲$relatives = $row["firstname"]
,然後我需要的文件回顯/打印print $relative
。搜索數據庫使用PHP
爲什麼這不適合我?
... connection made ...
$codes = $_GET['code'];
$sql = "SELECT firstname FROM guests WHERE invitecode = $codes";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$relatives[] = $row["firstname"];
}
}
foreach ($relatives as $relative) {
print $relative;
}
更新:
所以現在使用:
<?php
$codes = $_GET['code'];
$thecodes = "";
foreach($codes as $vals)
$thecodes .= (int)$vals . ",";
if($thecodes != "")
{
$thecodes = trim($thecodes, ",");
$sql = "SELECT firstname FROM guests WHERE invitecode IN ($thecodes)";
$result = mysqli_query($conn, $sql);
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$relatives[] = $row["firstname"];
}
}
foreach ($relatives as $relative) {
print $relative;
}
}
else
{
}
?>
它的工作原理,但我想進入foreach ($relatives as $relative) { echo $relative; };
成這樣$message = $firstname . " " . $lastname . " will be coming to your event. " . ;
值。
最後它會變成這樣:$message = $firstname . " " . $lastname . " will be coming to your event. " . foreach ($relatives as $relative) { echo $relative . " "; };
。
由於某些原因,當我將它們結合起來時它不起作用。
將它們插入到一個SQL語句時,請使用用戶控制變量妥善處理:?如何防止SQL注入的PHP]( https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – MatsLindh
我會*高*建議不要對循環內的每個代碼做一個單獨的查詢。這可笑的效率很低。建立一個'WHERE'子句,然後使用一個查詢,然後使用PHP來構建你想要的結構是很容易的。無論如何,在「foreach」中的查詢是一個非常糟糕的主意。我從來沒有說過,除非這是一個個人項目,否則沒有其他人可以訪問它。 –