Question

I want to update multiple mysql rows with one submit button. But there seems to be a problem in my php code.

    <?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'webtest');
define('DB_PASSWORD', '******');
define('DB_DATABASE', 'webtest');

$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE) or die(mysql_error());
mysql_set_charset("utf8", $connection);
?>

    <form action='' method='post'>
    <table border='1'>
        <?php
            $result = mysql_query("SELECT * FROM users ");

                    echo "<tr>";
                        echo "<td colspan='3'>CLASS 1</td>";
                    echo "</tr>";

                    while($row = mysql_fetch_array($result)){

                    echo "<tr>";
                        echo "<td><input type='text' name='id' value='".$row['id']."' /></td>";
                        echo "<td>Email  :<input type='text' name='email' value='".$row['email']."' /></td>";
                        echo "<td>Username  :<input type='text' name='username' value='".$row['username']."' /></td>";
                        echo "<td>Password  :<input type='text' name='password' value='".$row['password']."' /></td>";
                    echo "</tr>";

            }

            echo "<input type='submit' name='update' value='UPDATE' />";
        ?>
    <table>
</form>

<?php
    $id = $_POST['id'];
    $update = $_POST['update'];
    $email = $_POST['email'];
    $username = $_POST['username'];
    $password = $_POST['password'];

if(isset($_POST['update'])){

foreach($_POST['email'] as $email){


    mysql_query("   UPDATE users
                       SET email= '$email', username='$username', password='$password'
                     WHERE id = '$id' ");   

}
    header("location: updateusers.php");
    exit;
}   

?>
Was it helpful?

Solution

$_POST['email'] is not an array. You cannot loop it. You must declare input tag of email as an array to use it in foreach.

replace this

echo "<td>Email  :<input type='text' name='email' value='".$row['email']."' /></td>";

with

echo "<td>Email  :<input type='text' name='email[]' value='".$row['email']."' /></td>";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top