简体   繁体   中英

Populate select input from PHP script

I need to populate an input select with the values of a table in the moment that the page loads. This page will work as a NEW record in database or as MODIFY existing record. This is my table structure.

    CREATE TABLE `PERSONAS` (
      `ID` int(11) NOT NULL AUTO_INCREMENT,
      `NOMBRE` varchar(100) COLLATE latin1_general_ci NOT NULL,
      `CUIL` varchar(45) COLLATE latin1_general_ci DEFAULT NULL,
      `LOCALIDAD_ID` int(11) DEFAULT NULL,
      `PARTIDO_ID` int(11) DEFAULT NULL,
      `PROVINCIA_ID` int(11) DEFAULT NULL,
      PRIMARY KEY (`ID`),
      KEY `DNI` (`DNI`),
      KEY `NOM_AP` (`NOMBRE`,`APELLIDO`),
      KEY `CUIL` (`CUIL`)
    ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci$$

    CREATE TABLE `LOCALIDADES` (
      `ID` int(11) NOT NULL,
      `PARTIDO_ID` int(11) NOT NULL,
      `NOMBRE` varchar(80) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8$$

The page with the form is called legajos_abm.php so, when I want a new PERSONAS, I call the page as legajos_abm?id=null but when I need to modify PERSONAS I call it legajos_abm?id=3 with the PERSONAS.ID as parameter.

This is an example of my html form:

    <html>
    <head></head>
    <body>
        <div id=formulario>
            <form id=formularioLegajo>
                <fieldset>
                    Nombres: <input id=nombre type=text />
                    Localidad: <input id=localidad type=select />
                    <!-- The rest of the fields........ -->
                </fieldset>
            </form>
        </div>
    </body>
    </html>

What I need is to populate the select input for LOCALIDAD_ID with the results of table LOCALIDADES. When ?id=null fill it with the whole table results, when ?id=x then fill it with the field of the row x.

Hope my english haven't messed around with the question.

The solution:

    <td style="text-align:right"><label>Provincia: </label></td>
    <td><select id="cmbProvincia" name="cmbProvincia" style="width:240px">
    <option value="0">Elija la provincia...</option>;
    <?php
        require_once('dataaccess.php');
        $legajos = new legajos();
        $legajos->cmbProvincias();
    ?>
    </td>

dataaccess.php

    $con = $this->conectarDB();
    $query = 'CALL SPR_CMB_PARTIDOS('.$provincia_id.')';
    $result = $this->con->query($query);

    while($row=$this->con->fetch($result)) {
        echo '<option value="'.$row['PROVINCE_ID'].'">' .$row['PROVINCE_NAME_TX'].
        '</option>';
    }
    echo "</select>";
    $this->con->close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM