如果我从 SQL 收集多行数据,我将不得不使用 foreach 循环或其他方法来正确显示该数据。如何在不使用 foreach 循环的情况下使用这些 PHP 字符串?
以下是我的 SQL 查询
$results = $mysqli->query('SELECT * FROM specs where id in ('.$id1.','.$id2.','.$id3.','.$id4.') ');
它将产生来自 4 个不同行的数据。
上面的代码只是一个示例,下面是我在页面中使用的确切代码。
try{
$pdo = new PDO("mysql:host=localhost;dbname=databse", "user", "password");
// Set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
}
// Attempt select query execution
try{
$sql = "SELECT * FROM specs WHERE id IN($id1,$id2,$id3,$id4)";
$result = $pdo->query($sql);
$results = $result->fetchAll();
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
// Close connection
unset($pdo);
目前,数据使用以下方式显示
<tr>
<td>Brand</td>
<?php foreach ($results as $result){ ?>
<td> <strong><?php echo $result['brand']; ?></strong> </td>
<?php } ?>
</tr>
总共会有 4 个结果,我想分别使用这 4 个结果。如果结果是 Samsung、Sony、Apple、LG - 我如何仅使用 PHP 字符串来回显“Apple”?
森栏