【问题标题】:While loop stuck on first query resultWhile 循环停留在第一个查询结果上
【发布时间】:2016-06-22 09:47:56
【问题描述】:

我对 php 比较陌生,并且正在将我写的搜索引擎转移到 OOP。

相关SQL连接代码/sqlconnect1类:

    public function query($query){
    $this->stmt = $this->dbh->prepare($query);
    }

    public function bind($param, $value, $type = null){     
        if (is_null($type)) {
            switch (true) {
                case is_int($value):
                    $type = PDO::PARAM_INT;
                    break;
                case is_bool($value):
                    $type = PDO::PARAM_BOOL;
                    break;
                case is_null($value):
                    $type = PDO::PARAM_NULL;
                    break;
                default:
                    $type = PDO::PARAM_STR;
            }
        }

        $this->stmt->bindValue($param, $value, $type);
    }
    public function execute(){
        return $this->stmt->execute();
    }

    public function resultset(){
        $this->execute();
        return $this->stmt->fetch(PDO::FETCH_ASSOC);
    }

While循环:

$search = new LoadSearch;
$sqlconnect1 = new sqlconnect1;
$sqlconnect1->query("SELECT * FROM data1 WHERE address_city LIKE 'austin' AND address_zip LIKE '78758'");

    //Assign Variables and Display Record Results
    while ($row1 = $sqlconnect1->resultset()){
    $Name1=$row1['name'];
    $Address1=$row1['address_1'];
    $City1=$row1['address_city'];
    $State1=$row1['address_state'];
    $ZIP1=$row1['address_zip'];
    $Country1=$row1['address_country'];
    $Phone1=$row1['phone'];
    $Website1=$row1['website'];
    $Category_11=$row1['category_1'];
    $Category_21=$row1['category_2'];
    echo"

    <!--Table 2-->  

    <table class='table2'>

        <tr>
            <td></td><td><b>$Name1</b></td>
        </tr>

        <tr>
            <td></td><td>$Address1, $City1, $State1 $ZIP1</td>
        </tr>

        <tr>
            <td></td><td>$Country1</td>
        </tr>

        <tr>
            <td></td><td>$Phone1</td>
        </tr>

        <tr>
            <td></td><td>$Category_11</td>
        </tr>

    </table>";

每当加载页面时,它都会无限期地重复第一个查询结果,并且永远不会超出第一个结果。任何建议将不胜感激。类似的设置在程序上运行良好。

【问题讨论】:

  • sqlconnect1 类到底是什么? :)
  • @Diego Mariani 就像我说的,我是新手。我认为人们通常将其命名为数据库。第一段代码来自 sqlconnect1 类,其中包含所有数据库连接信息。
  • @sectus 我尝试了 fetchAll,但它似乎返回了数据库中的所有内容。我只是假设,因为表加载,但它们永远不会填满数据。它只是在页面中无限期地重复表格,其中没有任何内容。
  • 从该函数中删除执行。在循环之前调用执行。
  • 将执行删除到结果集中,因为每次获取时,您也会执行并且总是会得到相同的结果(第一次)

标签: php


【解决方案1】:

删除$this-&gt;execute() 调用,这是因为您在每个循环迭代中调用execute,然后调用fetch。这样,您将始终检索相同的结果(第一行)

public function resultset(){
    // $this->execute(); -- Remove this line
    return $this->stmt->fetch(PDO::FETCH_ASSOC);
}

显然你需要在你的while循环之前调用$sqlconnect1-&gt;execute()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    相关资源
    最近更新 更多