$sql = "SELECT * FROM item";
$stmt = $conn->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$data['result_2'] .= '
<div class="col-sm-4 col-md-4">
<div class="content-boxes style-two top-column clearfix animated flipInY" style="opacity: 1;">
<div class="content-boxes-text">
<form action="php/additem.php" method="post" class="form-inline pull-right">
<h4>'.$row['itemName'].'</h4><input type="hidden" name="itemName" value="'.$row['itemName'].'">
<img src="../wholesale/img/sourdough.jpg" class="img-reponsive">
<p>'.$row['description'].'</p><input type="hidden" name="description" value="'.$row['description'].'">
<div class="form-group">
<label class="sr-only" for="exampleInputAmount">Qty</label>
<div class="input-group">
<input type="number" name="qty" class="form-control" id="exampleInputAmount" placeholder="How Many?">
</div>
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
<!-- //.content-boxes -->
</div>
';
}
我希望能够在此result_2字符串中添加if语句。 这是用于显示产品,我想根据用户会话值显示价格? 例如。
if ($_SESSION['customer_x'] == a) {
display price a
}
else if ($_SESSION['customer_x'] == b) {
display price b
}
这是能够将if语句添加到JSON查询的正确方法吗?
答案 0 :(得分:3)
开始你的while循环后,在那里放一个if else,
$price ="";
if ($__SESSION['customer_x'] == a) {
$price='display price a';
}
else if ($_SESSION['customer_x'] == b) {
$price='display price b';
}
现在以你想要的html
回显这个价格这种方式更为简洁,而且不那么混乱
答案 1 :(得分:1)
您可以使用ternary if operator在字符串中包含条件语句,例如
$bool = false;
echo "The value of \$bool is " . ($bool == true ? "TRUE" : "FALSE");
答案 2 :(得分:1)
要补充一点,你可以继续这样做,但是:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){ // the next of the content
$priceOfSession = ($__SESSION['customer_x'] == a) ? 'pricea' : 'priceb';
$data['result_2'] .= '
<div class="col-sm-4 col-md-4">
'.$priceOfSession.'
</div>
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
</div>
&#39 ;; }
因此,如果您只想评估两个条件,如果您需要,只需将其添加到那里。在定义值之前添加$行。