我正在学习PHP,我正试图根据MySQL表中的值启动一个循环。
在MySQL表中,我有一个课程名称,包含start_year和duration。我想要实现的是以下代码示例:
$results = $conn->query($sql);
for (int $i = $results as $row['start_year']; $i <= $results as $row['duration']; i++) {
echo "<tr>" . $i . "</tr>";
}
任何帮助都将不胜感激!感谢
代码更新:
<thead>
<tr>
<th scope="col" class="wide" >Year</th>
</tr>
</thead>
<!-- Table body -->
<tbody>
<?php
try {
$dsn = "mysql:host=localhost;dbname=".$mysqldatabase;
// try connecting to the database
$conn = new PDO($dsn, $mysqlusername, $mysqlpassword);
// turn on PDO exception handling
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
// enter catch block in event of error in preceding try block
echo "Connection failed: ".$e->getMessage();
}
try {
$sql="SELECT *
FROM courses
WHERE courses.cid = '"". $_GET['courses'] . "'"
ORDER BY courses.title";
$results=$conn->query($sql);
if ($results->rowcount()==0){
} else {
//generate table of results
foreach ($results as $row){
$years=range($row['startYear'],$row['startYear']+$row['duration']-1);
echo "<tr><td>";
echo implode(",",$years."</td></tr>");
}
} catch ( PDOException $e ) {
echo "Query failed: " . $e->getMessage();
}
$conn = null;
?>
您可以在php手册上找到这个答案
$results = $conn->query($sql);
foreach ($results as $row){
$years=range($row['start_year'],$row['start_year']+$row['duration']-1);
echo implode(",",$years)."<br/>";
}