Skip to content
Advertisement

Using fopen and str_replace to auto fill a select option

I have this file ‘gardens.php’, which pulls data from a table called ‘generalinfo’ and I use fopen to send that data to a file called ‘index.html’. Here is the issue, only one option is filled. I have a demo running here Garden Demo <– this is a new updated page and location, there are more errors than I have locally If anyone could help me fix them Username:stack1 Password:stack1

Is there a better way to achieve what I want to?

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 SNIPPET

<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();
?>

Advertisement

Answer

Do you use this snippet in some other PHP file as well? If not you can just integrate into your gardens.php file:

<?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>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement