如何在PHP中使用mySQL数据进行循环?

时间:2018-10-28 19:19:04

标签: php mysql

我正在尝试从mySQL脚本中获取最后一个ID,然后在PHP的循环中使用它来以这种方式显示每个产品,因此我不需要分别键入每个产品,也许这不是最好的解决方案,但这是原型。问题是运行时页面上什么也没有显示,如果有数字而不是$ last_id,那么它可以正常工作

@Override
protected Void doInBackground(Void... params) {
    try {
        String jsonString = Jsoup.connect(url).execute().body();
        JSONObject json = new JSONObject(jsonString);
        JSONArray list = json.getJSONObject("list").getJSONArray("item");
        // now you can use the list
    } catch (JSONException | IOException e) {
        e.printStackTrace();
    }
    return null;
}

2 个答案:

答案 0 :(得分:0)

如何确定ID顺序正确。那里可能有一个不存在的数字,因为您以后可以删除数据库中的某些行。无论如何,我通常使用PDO代替mysqli,但这是这个主意。只需阅读所有内容,然后您就可以在foreach循环中使用输出了。

$stmt = $connection->query("SELECT * FROM tab_mobiteli");

foreach ($stmt as $row) {
  // here you do what you want to do for each db entry
  // for example "echo $row['id'];"
}

答案 1 :(得分:0)

您没有执行查询,这就是为什么它什么都不显示的原因。 这是一个使用PDO查询mysql数据库的示例,详细了解here

<?php

$dbh = new PDO('mysql:dbname=test;host=localhost','root','root');

$stmt = $dbh->prepare("SELECT id FROM tab_mobiteli ORDER BY id DESC LIMIT 1");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
 if(count($results) > 0){
    for($i = 0; $i < count($results); $i++) {
        echo "<p>$results[$i]['id']</p>";
    }
  }
?>