Search code examples
phpajaxdynamic-url

Dynamic url for link with php different php variables


My title may not be the good one, i tried my best.

I want to load different links through ajax, and I want them to direct them to different pages, based on the links URL they have.

the href value is php variable that is changing.

In simple case we do this : <a href = "somepage.php?varible = 'ifany' ">

But I've pages with different names and these names are changing through variable.

How can I have the page name with their extension and with the ability to send variables to that page dynamically, how can I do that ?

The following links are loaded with different href values through ajax.

if ($run = mysqli_query($connect, "SELECT `day` from `foodd_schedule` WHERE `week` = '$week' group by day"))
{
    while ($row = mysqli_fetch_assoc($run)) {
?>

    <a href="<?php echo $row['day'] . '.php'; ?>" value="<?php echo $row['day']; ?>" name="<?php echo $row['day'] ?>"><?php echo $row['day']; ?></a>

<?php
    }
}

In href value I'll have different days with that I've appended extension i.e php, I don't know is this right or wrong?

How can I append variables to the dynamically created page names?

I want to append an id to these dynamically created links.


Solution

  • This would be the code for your href value

    <?php echo $row['day'] . '.php?id=' . $id; ?>
    

    I would recommend to create a function where you would build your url. For the GET parameters use http_build_query function see the doc.

    Update:

    How to append multiple params using http_build_query, full example:

    <php
    if ($run = mysqli_query($connect, "SELECT `day` from `foodd_schedule` WHERE `week` = '$week' group by day")) {
        while ($row = mysqli_fetch_assoc($run)) {
    
            $params = [
                'id' => $id,
                'foo' => 'some string',
            ];
            $query = http_build_query($params); // generate url encoded string
    ?>
            <a href="<?php echo $row['day'] . '.php' . (!empty($query) ? '?' . $query : ''); ?>" value="<?php echo $row['day']; ?>" name="<?php echo $row['day']; ?>"><?php echo $row['day']; ?></a>
    <?php
        }
    }
    ?>