note 58155 deleted from function.mysql-query by philip

From: Date: Fri, 04 Sep 2015 19:22:59 +0000
Subject: note 58155 deleted from function.mysql-query by philip
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-203658@lists.php.net to get a copy of this message
Note Submitter: congaz at yahoo dot dk ---- Here's a little trick to help you keep track of MySQL table/column names, and the values you want to insert/select. I always use constants instead of variables for my table/column names. The script that define the constants can then dynamically be set to initialize different table/column names if needed. However, here comes the trick. Say you have an Insert statement like this: <?= // define(TABLE_DOCUMENT, 'table_name'); // define(COL_DOC_PUBLIC, 'column_name'); // etc.... $sql = "INSERT INTO ".TABLE_DOCUMENT." (".COL_DOC_PUBLIC.", ".COL_DOC_UPLOAD_TSTAMP.", ".COL_DOC_CREATOR_NAME.") VALUES (".$doc_public.", ".$doc_upload_tstamp.", ".$doc_name.")"; ?> Now, with long insert statements, I find it easy to loose track of which values goes with which column names. If I somehow could use the constants as variable names, keeping track of all that sql mishmash would be quite a lot easier. As it turns out, constants names can be used as variable variables (not quite the correct definition when we're actually dealing with constants, but what the heck). So,the sql above could instead be like this: <?= ${COL_DOC_PUBLIC} = $doc_public; ${COL_DOC_UPLOAD_TSTAMP} = $doc_upload_tstamp; ${COL_DOC_CREATOR_NAME} = $doc_name; $sql = "INSERT INTO ".TABLE_DOCUMENT." (".COL_DOC_PUBLIC.", ".COL_DOC_UPLOAD_TSTAMP.", ".COL_DOC_CREATOR_NAME.") VALUES (".${COL_DOC_PUBLIC}.", ".${COL_DOC_UPLOAD_TSTAMP}.", ".${COL_DOC_CREATOR_NAME}.")"; ?> This little trick made things alot easier for me - especially when dealing with extended querys, where you might have to use the same values in severel insert/select statements. Another thing is, that you can wait to use addslashes()/my_sql_real_escape_string until you create the "variable constants" - thus the task of remebering which values have been prepared to be used in an sql-statement has become fool-proof. Hope somebody finds this usefull...

« previous php.notes (#203658) next »