Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 967749
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T02:22:09+00:00 2026-05-16T02:22:09+00:00

I’ve been learning about DRY code and my code isn’t DRY… For example, I

  • 0

I’ve been learning about DRY code and my code isn’t DRY…

For example, I have a custom CMS and I save basically a name, content and a publish status for a few things… like an article, a user, a event. To submit a form, I submit to a file (process.php) which has a switch in it like so:

switch($_POST['process']) {


case 'speaker':

    if($_POST['speaker_id']) {

        $sql = '
            UPDATE speakers 
            SET speaker_name="' . mysql_escape_string($_POST['speaker_name']) . '",
            speaker_content="' . mysql_escape_string($_POST['speaker_content']) . '",
            speaker_status="' . $_POST['speaker_status'] . '"
            WHERE speaker_id="' . $_POST['speaker_id'] . '"
            LIMIT 1
        ';

    } else {

        $sql = '
            INSERT INTO speakers 
            SET speaker_name="' . mysql_escape_string($_POST['speaker_name']) . '",
            speaker_content="' . mysql_escape_string($_POST['speaker_content']) . '",
            speaker_status="' . $_POST['speaker_status'] . '"
        ';

    }


    mysql_query($sql);  

    if($_POST['speaker_id']) {

        header('Location: speakers?speaker_id=' . $_POST['speaker_id']);        

    } else {

        header('Location: speakers?speaker_id=' . mysql_insert_id);

    }

break;





case 'event':

    if($_POST['event_id']) {

        $sql = '
            UPDATE events 
            SET event_name="' . mysql_escape_string($_POST['event_name']) . '",
            event_content="' . mysql_escape_string($_POST['event_content']) . '",
            event_status="' . $_POST['event_status'] . '"
            WHERE event_id="' . $_POST['event_id'] . '"
            LIMIT 1
        ';

    } else {

        $sql = '
            INSERT INTO events 
            SET event_name="' . mysql_escape_string($_POST['event_name']) . '",
            event_content="' . mysql_escape_string($_POST['event_content']) . '",
            event_status="' . $_POST['event_status'] . '"
        ';

    }


    mysql_query($sql);  

    if($_POST['event_id']) {

        header('Location: events?event_id=' . $_POST['event_id']);      

    } else {

        header('Location: events?event_id=' . mysql_insert_id);

    }

break;


case 'article':

    if($_POST['article_id']) {

        $sql = '
            UPDATE articles 
            SET article_name="' . mysql_escape_string($_POST['article_name']) . '",
            article_content="' . mysql_escape_string($_POST['article_content']) . '",
            article_status="' . $_POST['article_status'] . '",
            article_modified="' . $_POST['article_modified'] . '"
            WHERE article_id="' . $_POST['article_id'] . '"
            LIMIT 1
        ';

    } else {

        $sql = '
            INSERT INTO articles 
            SET article_name="' . mysql_escape_string($_POST['article_name']) . '",
            article_content="' . mysql_escape_string($_POST['article_content']) . '",
            article_status="' . $_POST['article_status'] . '"
        ';

    }


    mysql_query($sql);  

    if($_POST['article_id']) {

        header('Location: articles?article_id=' . $_POST['article_id']);        

    } else {

        header('Location: articles?article_id=' . mysql_insert_id);

    }

break;




}

Despite some basic variations, like different table names and column names, and perhaps there sometimes being a couple more or less columns to populate, the code is literally the same and programming like this feels more like data entry than creativity.

I imagine there’s a way to create a class for this so that all the below code could be achieved in 1/3 the amount. Is there some sort of streamlined mysql insert / update method/strategy?

In my head, I’m thinking if I name all my inputs the same as they are in the table, ie if the column is called ‘speaker_name’ and the input is..

<input type="text" name="speaker_name" />

…I wonder if I could have a function which went through the $_POST array and simply updated the appropriate fields. Is this sound logic?

Perhaps I would have a hidden input in the form which was the ‘table’ variable which let the function know which table to update and it takes care of the rest.

Excuse me while I just thought out-loud. Any ideas would be really cool!

My newbie solution
Here’s what I have i got working

if($_POST['id']) {

  $sql = 'UPDATE ';

} else {

  $sql = 'INSERT INTO ';

}

// number of rows in array
$total = count($_POST);
// number of commas = total of values minus 1
$commas = $total - 1;
// starting number
$count = 1;

foreach ($_POST as $key => $value) {

  if($count == 1)
{

  $sql .= mysql_real_escape_string($value) . ' SET ';

}
else
{

if(    $count < $total    )
{

 $sql .= $key . '="' . mysql_real_escape_string($value) . '"';

if($count != $commas)
{

  $sql .= ', ';

}

    }
    elseif(    $_POST['id']    ) 
    {

    $sql .= ' WHERE ' . $key . '="' . mysql_real_escape_string($value) . '"';

    }


  }

$count = $count + 1;


}

mysql_query($sql);

if($_POST['id']) {

  header('Location: ' . $_POST['process'] . '?id=' . $_POST['id'] . '');


} else {

header('Location: ' . $_POST['process'] . '?id=' . mysql_insert_id());

}

To do this means my form designs need to have a pretty strict setup ie the first hidden input holds the table name, the last input is the id number of the row in the table being edited (if it exists).

I know its far from good… but a lot better than the hundreds of lines it previously took.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T02:22:10+00:00Added an answer on May 16, 2026 at 2:22 am

    1) some flaws in your concept

    • every piece of data you’re going to put into quotes in your query, should be processed with
      mysql_real_escape_string, as you cannot know what can be inside.

    • never use a table name passed from the client side. there can be malicious code instead of mere table name as well.

    • same for the field names. every identifier should be hardcoded in your script.

    2) as for the DRY – it’s simple. just note similar parts in your code and put them into function. only fields differ? okay, make a function that take fields list and produce an SQL statement of them.

    Luckily, Mysql let us use similar syntax for both insert and update. So, a very simple function like this one can help:

    function dbSet($fields) {
      $set='';
      foreach ($fields as $field) {
        if (isset($_POST[$field])) {
          $set.="`$field`='".mysql_real_escape_string($_POST[$field])."', ";
        }
      }
      return substr($set, 0, -2); 
    }
    

    So, you can make your code shorter:

    case 'speaker':
    
      $table = "speakers";
      $fields = explode(" ","speaker_name speaker_content speaker_status");
    
      if(isset($_POST['speaker_id'])) {
        $id = intval($_POST['speaker_id']);
        $query  = "UPDATE $table SET ".dbSet($fields)." WHERE id=$id";
      } else {
        $query  = "INSERT INTO $table SET ".dbSet($fields);
      }
      mysql_query($sql) or trigger_error(mysql_error().$query);  
      if($_POST['speaker_id']) $id = mysql_insert_id();
      header('Location: speakers?speaker_id='.$id);        
    
    break;
    

    if all your actions are such alike, you can make more high leveled functions:

    case 'speaker':
    
      $table = "speakers";
      $fields = explode(" ","speaker_name speaker_content speaker_status");
    
      if(isset($_POST['speaker_id'])) {
        $id = intval($_POST['speaker_id']);
        dbUpdate($table,$fields,$id);
      } else {
        $id = dbInsert($table,$fields);
      }
      header('Location: speakers?speaker_id='.$id);        
      exit;
    
    break;
    

    and even more high level

    case 'speaker':
    
      $table = "speakers";
      $fields = explode(" ","speaker_name speaker_content speaker_status");
      $id = dbMagic();
      header('Location: speakers?speaker_id='.$id);        
      exit;
    
    break;
    

    But I won’t go into that. I’d stop at 1st option, because it’s pretty straightforward and there are always some little things not fit into such a broad concept.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 502k
  • Answers 502k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer You are using styles incorrectly here. A style should be… May 16, 2026 at 2:40 pm
  • Editorial Team
    Editorial Team added an answer Not sure what you mean when you say send json… May 16, 2026 at 2:40 pm
  • Editorial Team
    Editorial Team added an answer 1. Why is this so? HashMap is newer than Hashtable… May 16, 2026 at 2:40 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Related Questions

I have a jquery bug and I've been looking for hours now, I can't
I have just tried to save a simple *.rtf file with some websites and
link Im having trouble converting the html entites into html characters, (&# 8217;) i
this is what i have right now Drawing an RSS feed into the php,
I'm looking for suggestions for debugging... If you view this site in Firefox or
Seemingly simple, but I cannot find anything relevant on the web. What is the
Does anyone know how can I replace this 2 symbol below from the string
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I want to count how many characters a certain string has in PHP, but

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.