Hi,

Looking for a way to update multiple rows of a db I stumble accross this little article as it came up on the first page of google...

http://www.phpeasystep.com/mysql/10.html

Looked quite simple so I modified it to suit, but then couldn't get it to work... (you could click the submit button, but nothing would happen)

So I then followed the tutorial to letter rather than a modified version, but I can't get that version to work either. (although this time when you clicked the button the page refreshed, but it just reloaded over the top of any changes you had made to data rather than updating the table.

Can anyone spot any obvious problems with this tutorial.

Does anyone know of a better way of doing the same thing?

many thanks

    That tutorial looks like an old tutorial in that it assumes that PHP is configured such that register_globals is set to on. These days, by default, register_globals is now off, so you would use say, $_POST['Submit'] instead of $Submit.

    Other problems include the lack of proper escaping of incoming data, which means that the script is vulnerable to SQL injection. These days, you should be using the PDO extension or the MySQLi extension instead of the MySQL extension, upon which you can use prepared statements as an escaping mechanism. The use of prepared statements also mean that you can bind new values on each iteration and execute the prepared statement instead of having the statement be re-compiled on each iteration (but then again, there may be a query cache or something).

      ohhhh, I see. 🙂

      So I'd also need to change the line...

      $sql1="UPDATE $tbl_name SET name='$name[$i]', lastname='$lastname[$i]', email='$email[$i]' WHERE id='$id[$i]'";
      

      so each of the set use $_POST

      hmm now I have a problem with the brackets I think as this gives an error...

      $sql1="UPDATE $tbl_name SET name=$_POST['$name[$i]'], lastname=$_POST['$lastname[$i]'], email=$_POST['$email[$i]'] WHERE id=$_POST['$id[$i]']";
      

      err, and do I need to use $_POST for each of the $i that numbers each part.
      hmmm is this even workable?

      Thanks

        You would need to use:

        $sql1 = "UPDATE $tbl_name SET name='{$_POST['name'][$i]}', lastname='{$_POST['lastname'][$i]}', email='{$_POST['email'][$i]}' WHERE id='{$_POST['id'][$i]}'";

        However, the weakness here is that the input is assumed to be valid. Besides assuming that the user will not attempt SQL injection (or that the input from a non-malicious user will not contain single quotes), what happens if I submit a form crafted by myself with only some of the data? The script will end up accessing arrays out of bounds since it assumes that the number of elements in the incoming arrays is the same as the number of rows in the database table.

        I might be reading the client side source wrongly, but it also appears that the id is not even passed in the form, so accessing $_POST['id'] will not work anyway.

          I don't have to worry about malicious users but point taken about entry using quotes.

          looks like this is goig to be a bad starting point.

          thanks for your help, I think I might start again

            I don't have to worry about malicious users but point taken about entry using quotes.

            You may not have to worry about them now, but worrying about them now means that you will not forget to worry about them later when it matters.

            looks like this is goig to be a bad starting point.

            We could still use it though. I would simplify the example such that the database table becomes:

            CREATE TABLE `test_people` (
                `id` INT NOT NULL AUTO_INCREMENT,
                `name` VARCHAR(65) NOT NULL DEFAULT '',
                PRIMARY KEY(`id`)
            );

            Then to insert the test data:

            INSERT INTO `test_people` (`name`) VALUES ('Billly'), ('Jame'), ('Mark'), ('Linda'), ('Joey'), ('Sidney');

            A simple PHP form to process and display the names of the people:

            <?php
            $host = "localhost";       // Host name
            $username = "";            // Mysql username
            $password = "";            // Mysql password
            $db_name = "test";         // Database name
            $tbl_name = "test_people"; // Table name
            
            // Connect to server and select databse.
            $db = new PDO('mysql:host=' . $host . ';dbname=' . $db_name, $username, $password);
            
            // If there is an update, process it.
            if (isset($_POST['submit'], $_POST['name']) && is_array($_POST['name'])) {
                $stmt = $db->prepare("UPDATE `$tbl_name` SET `name`=:name WHERE id=:id");
                $stmt->bindParam(':id', $id, PDO::PARAM_INT);
                $stmt->bindParam(':name', $name, PDO::PARAM_STR);
                foreach ($_POST['name'] as $id => $name) {
                    $stmt->execute();
                }
                echo '<h1>Updated the records.</h1>';
            }
            
            // Print the form.
            echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF']) . '" method="post">';
            foreach ($db->query("SELECT `id`, `name` FROM `$tbl_name` ORDER BY `name`") as $row) {
                echo '<input type="text" name="name[' . (int)$row['id'] . ']" value="'
                    . htmlspecialchars($row['name']) . '" /><br />';
            }
            echo '<input type="submit" name="submit" value="Update" /></form>';
            ?>

            I have chosen to use the PDO extension in my example instead of the MySQL extension.

              a year later

              I know this is a bit old, but its still very useful. I'm trying to understand how to add a couple more fields in the PDO extension example.

              A snippet of code showing how to add another field/variable to the updating script would be super helpful to me.

              And greatly appreciated. Thanks in advance.

                2 years later

                I have made it to work. I was following the same tutorial "http://www.phpeasystep.com/mysql/10.html". But i couldn't get it to work by using arrays with brackets "[]". I just changed the whole thing and now it does the job. Here is how you do it. First follow the "Step 1" of the tutorial "http://www.phpeasystep.com/mysql/10.html". You should now have created the database, table and filled the table with some data. Then don't follow the tutorial any further. Create a blank .php page. name it "update_multiple.php". Go to code view of this page and delete everything, and i mean everything. Now copy and paste the following code into the file. Please note that "selected_row" is just the name of the recordset i created in Dreamweaver. I can't explain it further.

                <?php
                $hostname_test = "localhost";
                $database_test = "test";
                $username_test = "root";
                $password_test = "";
                $test = mysql_pconnect($hostname_test, $username_test, $password_test) or trigger_error(mysql_error(),E_USER_ERROR); 
                ?>
                <?php
                if (!function_exists("GetSQLValueString")) {
                function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
                {
                  if (PHP_VERSION < 6) {
                    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
                  }
                
                  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
                
                  switch ($theType) {
                    case "text":
                      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
                      break;    
                case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } mysql_select_db($database_test, $test); $query_selected_row = "SELECT * FROM test_mysql"; $selected_row = mysql_query($query_selected_row, $test) or die(mysql_error()); $row_selected_row = mysql_fetch_assoc($selected_row); $totalRows_selected_row = mysql_num_rows($selected_row); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body> <form action="" id="update" name="update" method="POST"> <table border="0" width="500px"> <tr> <td><strong>id</strong></td> <td><strong>name</strong></td> <td><strong>lastname</strong></td> <td><strong>email</strong></td> </tr> <?php $counter=1; ?> <?php do { $name='name'; $id='id'; $lastname='lastname'; $email='email'; $name.=$counter; $id.=$counter; $lastname.=$counter; $email.=$counter; ?> <tr> <td><input name="<?php echo $id ?>" type="text" id="id2" value="<?php echo $row_selected_row['id']; ?>" size="1" readonly="readonly" /></td> <td><input name="<?php echo $name ?>" type="text" id="name" value="<?php echo $row_selected_row['name']; ?>" /></td> <td><input name="<?php echo $lastname ?>" type="text" id="lastname" value="<?php echo $row_selected_row['lastname']; ?>" /></td> <td><input name="<?php echo $email ?>" type="text" id="email" value="<?php echo $row_selected_row['email']; ?>" /></td> </tr> <?php $counter++; ?> <?php } while ($row_selected_row = mysql_fetch_assoc($selected_row)); ?> </table> <p> <input type="submit" name="Update" id="Update" value="Update" /> </p> </form> <?php if (isset ($_POST['Update'])) { $id2=1; for($i=1;$i<$totalRows_selected_row+1;$i++){ $name2='name'; $name2.=$i; if (isset ($_POST[$name2])) {$name2=$_POST[$name2]; } $lastname2='lastname'; $lastname2.=$i; if (isset ($_POST[$lastname2])) {$lastname2=$_POST[$lastname2]; } $email2='email'; $email2.=$i; if (isset ($_POST[$email2])) {$email2=$_POST[$email2]; } $sql1="UPDATE test_mysql SET name='$name2', lastname='$lastname2', email='$email2' WHERE id='$id2'"; $result1=mysql_query($sql1); $id2++; } if($result1){ header("location:update_multiple5.php"); } } ?> </body> </html> <?php mysql_free_result($selected_row); ?>
                  Write a Reply...