Updating one column in all rows in a table

Mohammad_Hosseini picture Mohammad_Hosseini · Apr 17, 2013 · Viewed 69.7k times · Source

I want to update one same column in all rows in one table can some one give me a hand how to update the table ? there is just one input field that should update all rows value . this code is not working and I know there is something wrong in index and array .

<?php
    <form method="post" dir="rtl" name="maxcharfield" >                     
        <textarea onKeyDown="textCounter(this,'progressbar1',300)" 
          onKeyUp="textCounter(this,'progressbar1',300)" 
          onFocus="textCounter(this,'progressbar1',300)"  
            style="font-family:'B_yekan';" id="text" name="text" rows="0" cols="0" class="required"></textarea>
        <div class="cleaner h10"></div> 

        <div style="font-family:'B_yekan';" dir="rtl" id="progressbar1" class="progress" ></div>
        <script>textCounter(document.getElementById("maxcharfield"),"progressbar1",100)</script>    

        <input class="styled-button-8" style="margin-top:10px; float:right; margin-right:50px; font-size: 14px;  padding: 5px 14px;" type="submit" value="save" name="Submit"   />
        <input style="font-family:'B_yekan';" type="reset" value="reset" id="reset" name="reset" class="submit_btn float_l" />

    </form>

<?php
// for updating Check if button name "Submit" is active, do this 
if(isset($_POST['Submit']) && $_POST['Submit'] == 'save')
    {
        $sql1="UPDATE `".$tbl_name."` SET `board`='".$_REQUEST['text']."'  ";
                            $result1=mysql_query($sql1);
     }

    }   
?>

Answer

David picture David · Apr 17, 2013

You're over-complicating the solution. In order to update every record, the approach you're trying to take is:

  1. Select all records.
  2. Get the ID for each record.
  3. Loop through the IDs.
  4. Update each record by that ID.

The UPDATE syntax has a much easier way to do this. You don't need to supply a WHERE clause to an UPDATE statement. Without that clause, it will by default update every record in the table:

UPDATE TableName SET `board`='value'

Also, please be aware that you have a SQL injection vulnerability in your code. By using $_REQUEST['text'] directly in your SQL query, you allow any user to send SQL code to your query. Your code then executes whatever they send you. This could allow them to corrupt or delete your data, even gain administrative access to your server.

For starters, please stop using mysql_* functions. PHP has deprecated those and they should no longer be used. There is a mysqli_ replacement for them. In addition to that, use the mysqli_real_escape_string() function to sanitize your inputs before using them in a SQL query. And finally, use prepared statements instead of directly concatenating values into your SQL string.