Strahan Posted January 23, 2015 Share Posted January 23, 2015 (edited) 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 January 23, 2015 by Strahan Quote Link to comment Share on other sites More sharing options...
ginerjm Posted January 23, 2015 Share Posted January 23, 2015 array_keya(), array_values() and implode() Quote Link to comment Share on other sites More sharing options...
Strahan Posted January 23, 2015 Author Share Posted January 23, 2015 Thanks! Quote Link to comment Share on other sites More sharing options...
ginerjm Posted January 23, 2015 Share Posted January 23, 2015 oops - I see a typo. That s/b 'array_keys' Quote Link to comment Share on other sites More sharing options...
mac_gyver Posted January 23, 2015 Share Posted January 23, 2015 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.