从数据库中获取行,但在需要的位置打印其中的每一行

时间:2018-12-20 17:53:02

标签: php html database

我有很多行要从数据库中检索,但是我想在我想要的确切位置打印每行,甚至只打印行。 这可能吗?如果可以,我该如何实现?

<?php 
$sql="Select * from plays where usertype=2 and idgame=$idgame";
$result=mysqli_query($link, $sql);

while($row =  mysqli_fetch_assoc($result)) {
$aword = $row['word'];
} ?>

<body>
 <div id="row">
      <span class="attemp">1 :</span>
      <span class="word"><?php print  //I want to print here only the 2nd fetched row  ?></span>
  </div>

 <div id="row">
      <span class="attemp">2 :</span>
      <span class="word"><?php print  //I want to print here only the 4th fetched row  ?></span>
  </div>  
</body>

2 个答案:

答案 0 :(得分:0)

如果在检索数据时将其存储到数组中,然后可以根据需要输出数据(记住数组是基于0的)...

$aword = [];
while($row =  mysqli_fetch_assoc($result)) {
    $aword[] = $row['word'];
} ?>

<body>
 <div id="row">
      <span class="attemp">1 :</span>
      <span class="word"><?php echo $aword[1];  ?></span>
  </div>

 <div id="row">
      <span class="attemp">2 :</span>
      <span class="word"><?php echo $aword[3];  ?></span>
  </div>  
</body>

我还建议,如果您只希望从数据中选择一列,则只选择该列,而不要选择* ...

$sql="Select word from plays where usertype=2 and idgame=".(int)$idgame;

以及关于使用准备好的语句停止SQL注入的强制性注释和一些常见错误。

答案 1 :(得分:0)

public ActionResult Create()
{
    var Dictionary = db.departments.ToList();

    if (Dictionary != null) 
    {
         ViewBag.data = Dictionary;
    }

    return View();
}

[HttpPost, ActionName("Create")]
public ActionResult CreateThroughStoreProcedure(employee emp) 
{
    if (ModelState.IsValid)
    {
        db.ShowdDetails(emp.name, emp.city, emp.gender, emp.depId);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View("Error");
}