-1

my problem is that i am trying update a table database using php with the values of selected options saved in an array and i am not able to make it works. In the case i will explain now, i am trying update a row which has certain value with one of the values from the array.

This is the php that shows the information of the table database inside a table enter image description here

This is the table database which content want update enter image description here

And this is part of the code that create the table with the selected options

<div class="centro">
        <table class="tabla" style="width:100%">
            <thead>
                <tr>
                    <th>Numero</th>
                    <th>Coste</th>
                    <th>Usuario</th>
                    <th>Estado</th>
                    <th>Confirmar</th>
                </tr>
            </thead>

            <tbody>
                <tr>
                    <?php

                        //Variable para el nombre de usuario
                        $x = $user_data['usuar_nom'];
                        $conexion = mysqli_connect("localhost", "root", "", "llanoponte");
                        $sql = "SELECT * FROM carro";
                        $resultado = $conexion->query($sql);
                        $id = 0;

                        if($resultado->num_rows > 0){
                            while($row = $resultado-> fetch_assoc()) {   
                                echo"
                                <tr>
                                    <td>",$row['numero'],"</td>
                                    <td>",$row['coste'],"</td>
                                    <td>",$row['usuario'],"</td>
                                    <td>",$row["estado"],"</td>
                                    <td>
                                        <select id='$id' name='estados'>
                                            <option value='Por confirmar'>Selecciona estado</option>
                                            <option value='Cancelada'>Cancelada</option>
                                            <option value='En entrega'>En entrega</option>
                                        </select>
                                    </td>
                                </tr>
                                ";
                               $id++;
                            }
                        }
                        else {
                            echo "Sin resultados";
                        }
                        $conexion-> close();
                    ?>
                </tr>
            </tbody>
        </table>
    </div>

Then this is the code with an input when clicked that creates the array with the selected options and send it to the php which updates.

<input type="submit" id="cambios" name="cambios" class="cambios" onclick="cambios()" value="Cambiar">

    <script type="text/javascript">
        function cambios()
        {

            //array para ver length de select lists
            let lista = [];

            //Pasar variable del php para hacer bucle for
            var veces = '<?php echo $id?>';
            
            //Bucle que pasa por los select
            for(var i=0; i< veces; i++)
            {
                var e = document.getElementById(i);
                var value  = e.value;
                lista.push(value);
            }

            $.ajax({
                url:'modificando.php',
                type:'post',
                data:{lista:lista},
                success:function(respuesta)
                {
                    alert("Se han realizado los cambios");
                }
            });

        }
    </script>

And finally this is the php where i want update the database with value of the array

<?php

    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "llanoponte";

    $lista = $_POST['lista'];

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
    }

    $sql = "UPDATE carro SET estado='.$lista[1].' WHERE id=2";

    mysqli_query($conn, $sql);

    $conn->close();

?>

Thank you by reading all this, and sorry if it was difficult to understand

Paul
  • 1
  • 2
  • 1
    When you debug, where specifically does an operation first fail or produce an unexpected result? There are multiple steps and operations taking place here, now is the time for you to start observing the behavior and results of each one to narrow down the specific problem. – David May 12 '23 at 10:10
  • 1
    `SET estaso='.$lista[1].'` - based on what are you picking the second element out of that array here, how do you know that of all the values send, this is the one you want to use for your update? And if you always want to use that one specific element - then why are you sending an array in the first place? – CBroe May 12 '23 at 10:22
  • As an aside... Your code is wide open to **SQL injection**, which is not only a security vulnerability but also a very common source of bugs. (Potentially even the bug you're trying to solve right now.) Now would be a great time to [correct that](https://stackoverflow.com/q/60174/328193). – David May 12 '23 at 10:23
  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Community May 12 '23 at 10:53

1 Answers1

-1

You need to add string quotes in SQL Queries when inserting/updating a string
I have modified the query to single quotes so we can use double quotes inside the Query

<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "llanoponte";

$lista = $_POST['lista'];

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = 'UPDATE carro SET estaso="'.$lista[1].'" WHERE id=2';

mysqli_query($conn, $sql);

$conn->close();
?>

In addition, it will be helpful to see what is inside the lista array to make sure there's data in it and you are passing it correctly

print_r($lista); // Print whole array 
echo $lista[1];  // Print the variable you want
hareth py
  • 112
  • 6
  • **Warning for future readers:** This code is wide open to [SQL injection](https://stackoverflow.com/q/60174/328193) and should *never* be used in any production system. It shouldn't even be used in testing, debugging, or academic exercises as it builds bad habits which have a tendency to find their way into production systems. – David May 12 '23 at 10:27
  • I am totally aware of this but the whole code doesn't even look prodution-ready – hareth py May 12 '23 at 10:40