0
function getTowns($conn)
{
    $sql = "SELECT towns.name, towns.id, regions.name AS region_name FROM towns INNER JOIN regions ON towns.region_id = regions.id ORDER BY name ASC";
    $result = $conn->query($sql);
    $town_opt = ''; //stands for town option

    town_opt .= "<datalist id='townlist'>";
    while ($row = $result->fetch_assoc()) {
        $town_id = $row['id'];
        $town_opt .= "<option>" . $row['name'] . ", " . $row['region_name'] .  "</option>";
    }

    $town_opt .= "</datalist>";
    return $town_opt;
};

echo $town_id;
echo getTowns($conn);
//how can I echo every town id? 

This is the best I could think of, and yet it doesn't work. I tried setting a cookie but it still wasn't working the way I wanted.

1 Answer 1

1
function getTowns($conn)
{
    $sql = "SELECT towns.name, towns.id, regions.name AS region_name FROM towns INNER JOIN regions ON towns.region_id = regions.id ORDER BY name ASC";
    $result = $conn->query($sql);
    $town_opt = ''; //stands for town option

    // We first set the town_id placeholder
    $town_id = array();


    town_opt .= "<datalist id='townlist'>";
    while ($row = $result->fetch_assoc())
    {
        // We add the ID into our array
        $town_id[] = $row['id'];

        $town_opt .= "<option>" . $row['name'] . ", " . $row['region_name'] .  "</option>";
    }
    $town_opt .= "</datalist>";

    // We return an array
    return array($town_opt, $town_id);

    /* Or you could use this
    return array('town_opt' => $town_opt, 'town_id' => $town_id);

    And then use them like so:

        $towns = getTowns($conn);

        // $town_opt
        echo $towns['town_opt'];

        // $town_id
        print_r($towns['town_id]);

    */
};

$towns = getTowns($conn);

// $town_opt
echo $towns[0];

// $town_id
print_r($towns[1]);

return an array with the first value being one value you want and the second as the other

Sign up to request clarification or add additional context in comments.

2 Comments

it gives me this error message:Notice: Array to string conversion in C:\xampp\htdocs\Snatchy\book.php on line 67 Array //// line 67 is // $town_id echo $towns[1];
Check the solution, it should be print_r($towns[1])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.