Php Sql Update

Discussion in 'PHP' started by Omzy, Mar 12, 2009.

  1. #1
    I'm just creating a basic interface for a MySQL database - the form brings up the customer details from $_GET (for example: customer.php?id=12). All the customer details are populated into INPUT fields.

    Ideally what I want is for the update query to be run upon form submission and only the fields that have been edited get updated in the database. Is this possible?
     
    Omzy, Mar 12, 2009 IP
  2. exodus

    exodus Well-Known Member

    Messages:
    1,900
    Likes Received:
    35
    Best Answers:
    0
    Trophy Points:
    165
    #2
    run a query to get all the sql data into php var's. Then compare those var's with the $_post vars. Create your sql then update statement if it has been changed.

    if($var != $_post['blah'] { $var = clean($_post['blah']); $sqlquery = "`blah` = '$var',"; }
    //need to remove the left most comma
    mysql_query("update `table` SET $sqlquery where `id` = $id");

    Something like the top portion, except with all the var's. Plus you have to not have the last var with a comma. So, before doing the update statement then remove the most left comma. There might be a better way of doing it, but this is the quick and simple way of doing what you asked about.
     
    exodus, Mar 12, 2009 IP
  3. MenOnWeb

    MenOnWeb Peon

    Messages:
    5
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I would make an array with the fields, and loop trough to create the sql-query. Possibly even put the query pieces in an array and use implode() to create the , between the fields.
     
    MenOnWeb, Mar 12, 2009 IP
  4. wesd

    wesd Peon

    Messages:
    4
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Don't compare the variables to the current database fields, it's a wasted call to the DB and makes things more complicated than they need to be. Use a hidden field called "Action" or something similar in the form that your script can check to see if the request is to read the data or to update the data.

    
    <form method="post" action="customer.php?ID=<?php echo $ID; ?>">
    <input type="hidden" name="Action" value="Update"/>
    <!-- Your Form Here -->
    </form>
    
    HTML:
    
    if ($_POST['Action'] == 'Update') {
    // Database UPDATE Code Here
    }
    else {
    // Database SELECT code here
    }
    
    PHP:
     
    wesd, Mar 12, 2009 IP