【问题标题】:How to display more then one fetch function in one page using loops ( in php )?如何使用循环(在 php 中)在一页中显示多个 fetch 函数?
【发布时间】:2021-08-15 20:42:39
【问题描述】:

我试图显示每个大陆的国家,所以在一个页面中我设置了一些按钮(每个大陆一个),我想要的是:当用户点击一个按钮时大陆的国家(即用户选择)将显示。但是,问题是:我只能单击按钮并仅显示我在代码中编写的第一个请求的国家,而当我第二次单击另一个按钮(另一个大陆)时,国家没有显示。我得到了这些错误:

变量“非洲”未定义。

致命错误:未捕获的错误:在 null 上调用成员函数 fetch() ..

这是前两个请求和前两个循环:

<?php
if (isset($_POST['africa']) ) {

    $africa=$baseblog->prepare('select country from countries where continent="Africa" ');
    $africaaa=$africa->execute(array());
    var_dump($africaaa);
    echo "  <br> ";

} elseif (isset($_POST['asia']) ) {

    $asia=$baseblog->prepare('select country from countries where continent="Asia" ');
    $asiaaa=$asia->execute(array());
    // var_dump($asiaaa);
    // echo "  <br> ";

}
?>

<!-- affichage des pays africa -->
<div class="divpays">
    <ul>
        <?php while ($africa1=$africa->fetch()) { ?>
        <li  style="text-align: center"> <?php echo $africa1['country'] ?> </li>
        <?php } ?>
    </ul>
</div>

<!-- affichage des pays asia -->
<div class="divpays">
    <ul>
        <?php  while ($asia1=$asia->fetch()) { ?>
        <li  style="text-align: center"> <?php echo $asia1['country'] ?> </li>
        <?php } ?>
    </ul>
</div>

【问题讨论】:

  • 不运行if时变量不存在。
  • 我会在 HTML 中使用 select 并让用户选择大陆。然后您可以只使用select 中的值。 select country from countries where continent=?...-&gt;execute(array($_POST['continent']))
  • 良好的代码缩进将帮助我们阅读代码,更重要的是,它将帮助您调试代码Take a quick look at a coding standard 为您自己的利益。您可能会被要求在几周/几个月内修改此代码,最后您会感谢我的。
  • 我正在尝试做的概念,我们将它应用在反应中,我不知道它是否可以在这里工作

标签: php html mysql loops


【解决方案1】:

您需要使用类或至少是函数的一些封装,以使其更清晰、更清晰。如 cmets 所述,您使用的是基于帖子的条件,因此可以选择 AFRICA 或 ASIA(或者当有人第一次到达此页面时),因此您不能在下面显示两个迭代,而只允许在顶部除非您设置了默认值,或者您隐藏了未在 POST 中调用的值。

我会先创建一个你的业务逻辑的封装版本(这里是一种模型和控制器,但如果你根本不使用任何封装,那么此时,这个概念没关系)

/vendor/MyClass/Model.php

<?php
namespace MyClass;

class Model
{
    private $request, $con;
    /**
     *  @note  Make sure to pass in the $_POST and your database connection.
     *         They don't have to be typed, but it helps keep things working
     *         and if you have a good IDE, it makes programming easier
     */
    public function __construct(array $request, \PDO $con)
    {
        $this->request = $request;
        $this->con = $con;
    }
    /**
     *  @note  Here you would try and fetch by the POST country.
     *         It would be better if the key was called "country" and the
     *         value would be "asia" or "africa" etc. It makes this
     *         part easier/cleaner 
     */
    public function getFromRequest(string $def = null)
    {
        # Determine what country to fetch
        if(isset($this->request['asia']))
            $country = 'asia';
        elseif(isset($this->request['africa']))
            $country = 'africa';
        # Stop and return nothing OR you are able to return a default
        if(empty($country))
            return (!empty($def))? $this->get($def) : false;
        # Return a successful selection
        return $this->get($country);
    }
    /**
     *  @note  This is just a general query engine that can be reused
     */
    public function get(string $country)
    {
        # Use the injected db connection to query
        $query = $this->con->prepare('SELECT `country` FROM `countries` WHERE `continent` = ?');
        # Execute. Presuming all your values use title case, you can
        # manipulate the string here to make sure whatever is passed
        # in will be correct
        $fetch = $query->execute([ ucwords(strtolower($country)) ]);
        # Create the loop
        while($result = $fetch->fetch(\PDO::FETCH_ASSOC)) {
            $row[] = $result;
        }
        # Return the result
        return (!empty($row))? $row : false;
    }
}

/thisfile.php

<?php
# Include the model
include_once(__DIR__.'/vendor/MyClass/Model.php');
# Create the instance, make sure to pass the post and your db connection
$MyClass = new \MyClass\Model($_POST, $baseblog);
# Fetch the country array, using "africa" as the default for when a
# $_POST is not set
$selCountry = $MyClass->getFromRequest('africa');
# Even though we are sure there will be returned an array of data, it's best
# to check that it's available first, just in case. This should still be
# error/warning-free if you removed "africa" as the default value.
if($selCountry): ?>
    <div class="divpays">
        <ul>
            <?php foreach($selCountry as $cou): extract($cou); ?>
            <li style="text-align: center">
                <?php echo $country ?>
            </li>
            <?php endforeach ?>
        </ul>
    </div>
<?php endif ?>

我应该注意,我没有对此进行测试,但它应该足以获得概念验证。


编辑:

在重新阅读您的帖子后,您可能还尝试在同一页面上获取多个国家/地区并通过一个按钮一次激活它们,希望您可以保持以前点击的国家/地区处于选中状态。此代码在其当前状态下不会这样做。您需要将其创建为基于 ajax 的解决方案,但您可以在这种情况下保持模型原样:

/ajax/country_select.php

<?php
include_once(realpath(__DIR__.'../').'/vendor/MyClass/Model.php');
$MyClass = new \MyClass\Model($_POST, $baseblog);
# Fetch the country array if set, no default
$selCountry = $MyClass->getFromRequest();
# Stop if no country
if(!$selCountry)
    return false ?>

<div class="divpays">
    <ul>
        <?php foreach($selCountry as $cou): extract($cou); ?>
        <li style="text-align: center">
            <?php echo $country ?>
        </li>
        <?php endforeach ?>
    </ul>
</div>

我这里要用jquery...

/thisfile.php

<h3>Click a country to get started!</h3>
<button class="country-selector">Africa</button>
<button class="country-selector">Asia</button>
<div id="country-drop"></div>


<script>
    $(function(){
        // Listen for button click
        $('.country-selector').on('click', function(e) {
            // Stop the button from doing whatever it would normally do
            e.preventDefault();
            // This is the default data
            var dataSet = {
                url: '/ajax/country_select.php',
                dataType: 'html',
                method: 'post',
                success: r => {
                    // We want to append into the country container
                    $('#country-drop').append(r);
                }
            };
            // Fetch the value from the button
            let sel = $(this).text();
            // Remove the button because we don't want people to use it again
            $(this).replaceWith('');
            // Create our post key, again, this would be much better if
            // the key was named "country" and the value was the country
            // name
            dataSet[sel] = true;
            // Do the ajax
            $.ajax(dataSet);
        });
    });
</script>

【讨论】:

  • 我认为我试图在 php 中应用的逻辑是不可接受的。反应它是一个页面,我们可以在一个页面中显示这么多组件。我试图在 php 中做同样的逻辑。我认为在 php 中这样做是不正确的
猜你喜欢
  • 2018-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-12
  • 1970-01-01
  • 2017-06-01
  • 1970-01-01
相关资源
最近更新 更多