Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>1) some flaws in your concept</p> <ul> <li><p><strong>every</strong> 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. </p></li> <li><p><strong>never</strong> use a table name passed from the client side. there can be malicious code instead of mere table name as well.</p></li> <li><p>same for the field names. <strong>every</strong> <em>identifier</em> should be hardcoded in your script. </p></li> </ul> <p>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.</p> <p>Luckily, Mysql let us use similar syntax for both insert and update. So, a very simple function like this one can help:</p> <pre><code>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); } </code></pre> <p>So, you can make your code shorter:</p> <pre><code>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; </code></pre> <p>if all your actions are such alike, you can make more high leveled functions:</p> <pre><code>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; </code></pre> <p>and even more high level</p> <pre><code>case 'speaker': $table = "speakers"; $fields = explode(" ","speaker_name speaker_content speaker_status"); $id = dbMagic(); header('Location: speakers?speaker_id='.$id); exit; break; </code></pre> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload