Jump to content

Knowing where you are in a non-numeric index loop


Strahan

Recommended Posts

Hi.  I want to build a SQL string based on my form fields so when I have a new field in the db, I can just add a new form field and the sql update will automatically work.  For example I have:

<input type=text name=t_something>
<input type=text name=d_something>
<input type=text name=n_something>

(post submission)

$data = array();
foreach ($_REQUEST AS $key=>$val) {
  if (substr($key, 0, 2) == "t_") $data[substr($key, 2, strlen($key)-2)] = $val;
  if (substr($key, 0, 2) == "n_") $data[substr($key, 2, strlen($key)-2)] = (trim($val)==""?"0":$val);
  if (substr($key, 0, 2) == "d_") $data[substr($key, 2, strlen($key)-2)] = (trim($val)==""?"NULL":date("Y-m-d", strtotime($val));
}
$data["posted"] = "NOW()";
 
$sql = "INSERT INTO table ("; $cnt = 0;
foreach ($data AS $key=>$val) {
  $cnt++;
  $sql .= $key . (($cnt < count($data))?", ":"");
}
 
But that's klunky.  The part that annoys me most is the $cnt.  I want to know if the element I'm on is the last one or not, if it isn't I put a comma.  If it was a number based index, I could just do a for x=0 to count, but since it's not I just did the array as key/val.  I inc a counter each loop through so I know where I am in the array vs the count.  That can't be a good way to do this.  
 
What would be a more efficient way to tell when I get to the end, or rather, what would be a more efficient way to build the query based on a form?  Security isn't a concern as this form is just for my use on an internal LAN.  Thanks!
if (substr($key, 0, 2) == "t_") $data[substr($key, 2, strlen($key)-2)]

 

 

there's no need to ever extract/manipulate form field names this way. just use an array name for each different meaning form field and you will directly received arrays of data in your php code when you add more of the same meaning form fields.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.