douhang5460 2016-01-26 17:14
浏览 61
已采纳

HTML / PHP - 从mysql数据库获取的输入值不会更新

So basically I have a table full of inputs and those inputs are filled with values taken from a mysql database. I am also using radio buttons to select one of those rows and then edit it, that row is supposed to be updated on the database but it keeps throwing me the "default" value, I mean, the exiting data is the old value not the new one. Here is my entire code:

    <?php
include 'config.php';

$dbname = "pruebasPHP";


$conn = mysqli_connect($servername, $username, $password, $dbname);

if (!$conn) {
    die("Conexión fallida: " . mysqli_connect_error());
}


echo '<html><head><title> Modificar datos Mysql PHP </title>
    <style>  td, th { padding: 5px; border: 1px solid black;} input {border: 0px;}</style>

    <script type="text/javascript">
    //<![CDATA[

    window.onload = function(){
        var cuantos = document.getElementById("valorI").value;

        for(var x=0; x<cuantos; x++){
            var nx = document.getElementById("n".concat(x));
            nx.readOnly = true;
            var ax = document.getElementById("a".concat(x));
            ax.readOnly = true;
            var ex = document.getElementById("e".concat(x));
            ex.readOnly = true;
        }
    }


    function escritura() {
        var cuantos = document.getElementById("valorI").value;

        for(var x=0; x<cuantos; x++){
            var radiox = document.getElementById("r".concat(x));
            if (radiox.checked) {
                document.getElementById("n".concat(x)).readOnly = false;
                document.getElementById("a".concat(x)).readOnly = false;
                document.getElementById("e".concat(x)).readOnly = false;
            }
            else {
                document.getElementById("n".concat(x)).readOnly = true;
                document.getElementById("a".concat(x)).readOnly = true;
                document.getElementById("e".concat(x)).readOnly = true;
            }
        }
    }

    //]]>
    </script>


    </head><body><center></br>';

if (isset($_POST['modificar'])) {
    if(isset($_POST['radio'])){


        $datos = $_POST['radio'];
        $datosSeparados = explode(":", $datos);

        $sql = 'UPDATE tabla1 SET 
                firstname="'.$datosSeparados[0].'", 
                lastname="'.$datosSeparados[1].'", 
                email="'.$datosSeparados[2].'"
                WHERE id='.$datosSeparados[3].';';

        echo $sql;

        if (mysqli_query($conn, $sql))
            echo 'El registro con el ID=<b>' . $datosSeparados[3] . '</b> se ha modificado satisfactoriamente. </br>';
        else 
            echo 'Error. Ha ocurrido un problema tratando de modificar el registro con ID=<b>' . $datosSeparados[3] . '</b>: </br> ' . mysqli_error($conn);
    }
}

echo '<form action="" method="post"> Registros a modificar:<br/><table>';


$sql = "SELECT id, firstname, lastname, email from tabla1;";
$resultado = mysqli_query($conn, $sql);


    echo '<tr>';
if ($fila = mysqli_fetch_assoc($resultado)){ 
    foreach($fila as $x => $x_value) {
        echo '<th>' . $x . '</th>';
    }
}
    echo '</tr>';

if (mysqli_num_rows($resultado) > 0) {

    $i = 0;

    while($fila = mysqli_fetch_assoc($resultado)) {

        echo '
        <tr>
            <td> ' . $fila["id"] . '</td>
            <td><input type="text" id="n' . $i . '" name="nombre" value="' . $fila["firstname"] . '" /></td>
            <td><input type="text" id="a' . $i . '" name="apellidos" value="' . $fila["lastname"] . '" /></td>
            <td><input type="text" id="e' . $i . '" name="email" value="' . $fila["email"] . '" /></td>
            <td><input type="radio" id="r' . $i . '" name="radio" value="'.$fila["firstname"].':'.$fila["lastname"].':'.$fila["email"].':'.$fila["id"].'" onchange="escritura();" /></td>
        </tr>
        ';

        $i++;
    }

    echo '<input type="hidden" id="valorI" value="'. $i . '"/>';
} 




echo '
    </table>
    <br/>
    <input type="submit" name="modificar" value="Modificar">
    <input type="reset" value="Limpiar">
    </form>';

echo '</center>
    </body>
    </html>';

?> 
  • 写回答

1条回答 默认 最新

  • douque9982 2016-01-26 18:18
    关注

    Its a bit long to explain in detail about MVC (Model View Controllers), but you can Google and find out a bunch of info on it. In a nutshell, its separation of layers. Model(handles data, your database queries), Controller(logic-building the data needed for your views), Views(html,css,js).. Your code above is very hard to follow and I believe you would benefit from the MVC pattern.

    Anyway, to start separating your code, you want to start organizing a bit. I would place your initial SQL query on top (mimicking the data layer), then if any logic is needed underneath that, and lastly your html.

    I will show you how I would redo your code. All this code would be in one file, just for demonstration purposes. Eventually you want to separate this in different files.

    Here's the top of your page, simulating the data you would get from your database into PHP. I will assign this data to your variable $resultado:

    <?php
    $resultado = array(
        array(
            "id" => 1,
            "firstname" => "John",
            "lastname" => "Doe",
            "email" => "j@d.com"
        ),
        array(
            "id" => 2,
            "firstname" => "Jane",
            "lastname" => "Johnson",
            "email" => "ja@d.com"
        ),
        array(
            "id" => 3,
            "firstname" => "Tom",
            "lastname" => "Brady",
            "email" => "b@d.com"
        )
    );
    ?>
    

    Then, since theres not much logic happening, I will output the "view" or the HTML. Here, you will notice that I created a different function to "lock" all your inputs, and another that will pass the current radio and "unlock" those inputs. Notice, that any embedded PHP is surrounded with those PHP tags inside HTML. :

    <html>
        <head>
            <script type="text/javascript">
    
                window.onload = function () {
                    lock_inputs();
                };
    
                function lock_inputs() {
                    var inputs = document.getElementsByTagName('input');
                    for (var i = 0; i < inputs.length; i++) {
                        if (inputs[i].type === "text") {
                            inputs[i].readOnly = true;
                        }
                    }
                }
    
                function escritura(radio, i) {
                    lock_inputs();
                    if (radio.checked) {
                        document.getElementById("n".concat(i)).readOnly = false;
                        document.getElementById("a".concat(i)).readOnly = false;
                        document.getElementById("e".concat(i)).readOnly = false;
                    }
                }
            </script>
        </head>
        <body>
            <form action="" method="post">
                Registros a modificar:<br/>
                <table>
                    <?php
                    $i = 0;
                    foreach ($resultado as $fila) {
                        ?>
                        <tr>
                            <td><?php echo $fila["id"] ?></td>
                            <td>
                                <input type="text" id="n<?php echo $i ?>" name="nombre" value="<?php echo $fila["firstname"] ?>"/>
                            </td>
                            <td>
                                <input type="text" id="a<?php echo $i ?>" name="apellidos" value="<?php echo $fila["lastname"] ?>"/>
                            </td>
                            <td>
                                <input type="text" id="e<?php echo $i ?>" name="email" value="<?php echo $fila["email"] ?>"/>
                            </td>
                            <td>
                                <input type="radio" id="r<?php echo $i ?>" name="radio" value="<?php echo $fila["firstname"] . ':' . $fila["lastname"] . ':' . $fila["email"] . ':' . $fila["id"] ?>" onchange="escritura(this,<?php echo $i ?>);"/>
                            </td>
                        </tr>
                        <?php
                        $i++;
                    }
                    ?>
                </table>
            </form>
        </body>
    </html>
    

    I hope you can understand this code better now. I did delete a lot of your other code so that you can follow and understand the importance of separation.

    Hope this helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?