如何使用循环(在php中)在一个页面中显示多个fetch函数?

如何使用循环(在php中)在一个页面中显示多个fetch函数?,php,html,mysql,loops,Php,Html,Mysql,Loops,我试图显示每个大陆的国家,因此在一个页面中,我为每个大陆设置了一些按钮,我想要的是:当用户单击按钮时,用户选择的大陆国家将显示出来。但是,问题是:我只能单击按钮并仅显示我在代码中编写的第一个请求的国家,而当我在另一个大陆上第二次单击按钮时,这些国家没有显示。我得到了这些错误: 非洲变量尚未定义 致命错误:未捕获错误:调用成员函数获取空值 以下是两个第一个请求和两个第一个循环: <?php if (isset($_POST['africa']) ) { $africa=$baseb

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

非洲变量尚未定义

致命错误:未捕获错误:调用成员函数获取空值

以下是两个第一个请求和两个第一个循环:

<?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>

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

我会先创建业务逻辑的封装版本,这是一种模型和控制器,但如果您根本不使用任何封装,那么在这一点上,这个概念并不重要:

/vendor/MyClass/Model.php

/thisfile.php

我应该注意到,我还没有测试过这个,但它应该足以证明概念

编辑:

在重新阅读您的帖子后,您可能还试图在同一页面上获取多个国家,并通过按钮一次激活一个国家,希望您可以选择以前单击的国家。此代码在其当前状态下不会执行此操作。您需要将其创建为基于ajax的解决方案,尽管您可以保持此场景中的模型:

/ajax/country_select.php

我将在这里使用jquery

/thisfile.php


如果不运行if,变量就不存在。我会在HTML中使用select,让用户选择大陆。然后,您可以只使用select中的值。从大陆=?而且…->Executarray$\u POST['Continental']良好的代码缩进将帮助我们阅读代码,更重要的是,它将帮助您为自己的利益调试代码。您可能会被要求在几周/几个月内修改此代码,最终您会感谢我。我尝试做的概念,我们在react中应用它,我不知道它是否会在这里工作。我认为我尝试在php中应用的逻辑是不可接受的。这是一个页面,我们可以在一个页面中显示这么多组件。我尝试在php中使用相同的逻辑。我认为在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;
    }
}
<?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 ?>
<?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>
<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>