簡體   English   中英

while循環不適用於多個變量php?

[英]while loop not working for more than one variable php?

我正在嘗試創建一個while循環,該循環從Mysql數據庫中檢索所有相關數據,但不適用於多個變量,我認為問題在於while循環,因為我已經回顯了sql語句並檢索了值正確的變量,代碼為:

$wherein = implode(',', $_SESSION['cart']);
$sql = "select ID, Name, Price from lamps WHERE ID = '$wherein'";
$result = mysqli_query($conn, $sql);

echo "<table style='width:100%' border='1' >";
echo "<tr>";
echo "<th> Product Name</th>";
echo "<th>Product Price </th>" ;
echo "<th>Quantity </th>" ;
echo "</tr>";

while ( $row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    echo "<tr>";
    echo "<td>" . $row['Name'] . "</td>";
    echo "<td> $". $row['Price'] . "</td>" ;
    echo "<td> <select>
        <option value= '1'>1</option> 
        <option value= '2'>2</option> 
        <option value= '3'>3</option> 
    </select>
    </td>";

    echo "</tr>";
}

echo "</table>";

我已經用代碼嘗試了很多事情,但是問題仍然存在,非常感謝您的幫助,謝謝。

</table>語句在while循環中。 因此,在第一個循環后關閉表后,其余數據可能不會在瀏覽器上顯示(它仍將出現在html源代碼中)。 通過將</table>語句移到最后一行來進行嘗試。

假設通過內插變量將具有多個ID,則應在sql中使用IN語句。

$wherein = implode("','", $_SESSION['cart']);
$sql = "select ID, Name, Price from lamps WHERE ID IN ( '$wherein' )";

渲染的輸出可以略微簡化,循環后應該關閉表! 不知道$wherein wherein的內容很難回答,但我認為IN語句似乎比直接等於=更適合用於查詢的逗號分隔值的性質=

$wherein = implode("','", $_SESSION['cart']);
$sql = "select ID, Name, Price from lamps WHERE ID IN ( '$wherein' )";
$result= mysqli_query( $conn, $sql );

echo "
    <table style='width:100%' border='1' >
        <tr>
            <th> Product Name</th>
            <th>Product Price </th>
            <th>Quantity </th>
        </tr>";

while ( $row = mysqli_fetch_object( $result ) ){
    echo "
        <tr>
            <td>{$row->Name}</td>
            <td>${$row->Price}</td>
            <td>
                <select>
                    <option value= '1'>1
                    <option value= '2'>2
                    <option value= '3'>3
                </select>           
            </td>
        </tr>";
}
echo "
    </table>";


/* Example of using an array of IDs and imploding to generate where conditions for IN clause */

$cart=array('BGL1','BJL');
/* session - cart */

$wherein=implode( "','", $cart );
/* correctly add quotes around each string */

$sql="select ID, Name, Price from lamps WHERE ID IN ('$wherein');";
/* use the new $wherein string within quotes */
echo $sql;

>> select ID, Name, Price from lamps WHERE ID IN ('BGL1','BJL');

暫無
暫無

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

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