【问题标题】:Using fopen and str_replace to auto fill a select option使用 fopen 和 str_replace 自动填充选择选项
【发布时间】:2010-04-19 16:16:30
【问题描述】:

我有这个文件 'gardens.php',它从一个名为 'generalinfo' 的表中提取数据,然后我使用 fopen 将该数据发送到一个名为 'index.html'。这是问题,只有一个选项被填写。我在这里运行了一个演示 Garden Demo 用户名:stack1 密码:stack1

有没有更好的方法来实现我想要的?

谢谢!总是。

GARDENS.PHP

<?php
    include("connect.php");
    $results = mysql_query("SELECT * FROM generalinfo");

    while($row = mysql_fetch_array($results)){
    $country = $row['country'];
    $province = $row['province'];
    $city = $row['city'];
    $address = $row['address'];


    //echo $country;
    //echo $province;
    //echo $city;
    //echo $address;

}

    $fd = fopen("index.html","r") or die ("Can not fopen the file");
        while ($buf =fgets($fd, 1024)){
            $template .= $buf;
        }

    $template = str_replace("<%country%>",$country,$template);

    echo $template;

?>

INDEX.PHP 片段

<form name="filter" method="get" action="filter.php">
    <select class="country" name="country">
        <option><%country%></option>
    </select>

</form>

CONNECT.PHP

<?php
mysql_connect("mysql.andcreate.com", "*******", "********")or die("Cannot Connect to DB");
mysql_select_db("gardencollective")or die("cannot select the DB table");
mysql_close();
?>

【问题讨论】:

  • 你的文件里只有一个&lt;%country%&gt;,怎么能替换更多呢?此外,您在 while 循环之外执行此操作,$country 将具有上一个循环的值。
  • 刚刚意识到,我忘记将本地数据库复制到服务器并重命名,实际名称显示在本地,让我现在更改它。
  • 是的,它在循环之外,如果我在循环内这样做 index.html 一遍又一遍地重复,我可能会倒着做,我应该在 gardens.php 中包含那个 sn-p文件并将其包含在 index.html 的侧边栏中

标签: php select loops options fopen


【解决方案1】:

您是否也在其他 PHP 文件中使用了这个 sn-p?如果没有,您可以直接集成到您的 gardens.php 文件中:

<?php
    include("connect.php");
    $results = mysql_query("SELECT * FROM generalinfo");
    $infos = array();
    while($row = mysql_fetch_array($results)){
        $infos[] = $row;
    }
?>

<form name="filter" method="get" action="filter.php">
    <select class="country" name="country">
        <?php foreach($infos as $info): ?>
            <option><?php echo $info['country'] ?></option>
        <?php endforeach; ?>
    </select>
</form>

【讨论】:

  • 好吧,我有点像使用 index.html 文件作为模板,并通过 fopen 将 gardens.php 中的信息添加到它
  • 我在这个页面上遇到了这个错误gardening.andcreate.com/gardens.php 这是我想让你看到的那个我在我的解释中混合了一些我必须修复的东西。
  • @Anders Kitson:看来您没有连接到数据库服务器。 connect.php 里面是什么?
  • 我为我的 connect.php 文件添加了代码,我不确定是什么原因导致相同的代码在我拥有的其他远程站点上似乎工作正常
  • @Anders Kitson:我从代码中删除了您的用户名和密码。你永远不应该在任何地方发布它! 我建议立即更改您的密码!! 无论如何,在此文件中,您正在调用mysql_close(),它会在您创建连接后立即关闭与您的数据库的连接。当然,mysql_query() 与那时没有任何联系。删除此行。
猜你喜欢
  • 1970-01-01
  • 2011-12-26
  • 2023-04-09
  • 1970-01-01
  • 2014-05-14
  • 1970-01-01
  • 2018-06-28
  • 2013-07-16
  • 1970-01-01
相关资源
最近更新 更多