lefty55104
lefty55104

Reputation: 127

Combine mysqli queries for html select with current selected

I have multiple html selects with the current mysqli value selected. Currently I have two queries to accomplish this. Is there a way to combine the two queries into one? I have too many mysqli queries in my application and am trying to find ways to limit and combine them.

<?php
    echo '<select name="companyedit"><option value="">None</option>';
    $currcoQuery = mysqli_query($link, "SELECT id FROM Company WHERE id = $company");
    $currco = mysqli_fetch_assoc($currcoQuery);
    $allcoQuery = mysqli_query($link, "SELECT id, name FROM Company ORDER BY name");
    while($allco = mysqli_fetch_assoc($allcoQuery)){
        echo '<option value="'.$allco['id'].'"';
        if($currco['id'] == $allco['id']) echo 'selected';
        echo '>'.$allco['name'].'</option>';
    }
    mysqli_data_seek($allcoQuery, 0);
    echo '</select>';
?>

Another example is:

<?php
    echo '<select name="marked"><option value="">None</option>';
    $curmaterialQuery = mysqli_query($link, "SELECT marked FROM Materials WHERE id = ".$materialed);
    $curmaterial = mysqli_fetch_assoc($curmaterialQuery);
    $allmaterialQuery = mysqli_query($link, "SELECT id, name FROM Marked WHERE `assoc` = 'mat'");
    while($allmaterial = mysqli_fetch_assoc($allmaterialQuery)){
        echo '<option value="'.$allmaterial['id'].'"';
        if($curmaterial['id'] == $allmaterial['id']) echo 'selected';
        echo '>'.$allmaterial['name'].'</option>';
    }
    mysqli_data_seek($allmaterialQuery, 0);
    echo '</select>';
?>

Upvotes: 0

Views: 151

Answers (1)

Andresch Serj
Andresch Serj

Reputation: 37398

For your first example, you get ALL companies with one query but before select a single one. That's "double trouble". Try this:

<?php
    echo '<select name="companyedit"><option value="">None</option>';
    $allcoQuery = mysqli_query($link, "SELECT id, name FROM Company ORDER BY name");
    while($allco = mysqli_fetch_assoc($allcoQuery)){
        echo '<option value="'.$allco['id'].'"';
        if($company == $allco['id']) echo 'selected';
        echo '>'.$allco['name'].'</option>';
    }
    mysqli_data_seek($allcoQuery, 0);
    echo '</select>';
?>

For your second example i'd need more context to give a better solution. It is hard to optimize queries without knowing the table structure.

Upvotes: 1

Related Questions