[英]fetch multiple rows of same id in different variable
我有兩行包含相同ID的數據。 對於相同的ID,它在不同的行中具有不同的地址。
我想在php中獲取不同地址中的兩個地址。
我怎樣才能做到這一點? 請幫忙!
下面是代碼:
foreach($row_address as $address)
{
echo "<br> Address :" .$address;
$info=Array();
$data=explode(' ', $address );
$info[1]=$data[0];
$info[2]=$data[1];
$info[3]=$data[2];
echo "City :".$info[1];
echo "Country :".$info[2];
echo "Pin Code :".$info[3];
}
function hoteladdresstable($id)
{
global $conn;
/*$sql2 = "select AddressLine from hoteladdress where Hotel_Id= " .$id;
$result2 = mysql_query($sql2,$conn);
$row2 = mysql_fetch_assoc($result2,MYSQL_NUM);
return $row2;*/
$query = "select AddressLine from hoteladdress where Hotel_Id = " .$id;
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
$d[] = $row['AddressLine'];
}
return $d;
}
它僅在一個變量中給我兩個具有相同ID的地址。 我希望它們具有兩個不同的變量。
您已經在$d
獲得了一個地址數組。
您可以做的是:
$d = array();
while ($row = mysql_fetch_assoc($result)) {
$d[$row['Address_ID']] = $row['AddressLine'];
}
extract($d, EXTR_PREFIX_ALL, 'ad');
如果您具有地址ID 2和4,則將獲得兩個變量
$ad_2
和$ad_4
我建議您改用mysqli
。
$data = array();
while($row = mysqli_fetch_assoc($result)){
$data[] = $row;
}
return $data;
接着
foreach($data as $oneRow){
echo $oneRow['AddressLine']; //and all other stuff that you want.
}
您可以驗證它:
print_r($data);
您應該使用參數化查詢。 使用PHP的PDO:
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$STH = $DBH->prepare('select AddressLine from hoteladdress where Hotel_Id = :id');
$STH->bindParam(':name', $id);
$STH->execute();
$d = array();
while($row = $STH->fetch()) {
$d[] = $row['AddressLine'];
}
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
不想讓您的查詢受到攻擊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.