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!
Edited by Strahan
Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.