antfuentes87 Posted July 21, 2012 Share Posted July 21, 2012 I was trying to have the below function insert the data just into one row, but instead it is doing (see image below). No idea why it is doing that, if anyone knows and could tell me how to fix it. It would be much appreciated. function set($table){ $result = mysql_query("SELECT * FROM $table"); $i = 0; while ($i < mysql_num_fields($result)) { $meta = mysql_fetch_field($result, $i); $name = $meta->name; $nameB = $_POST[$name]; if($name <> 'id'){ $q = "INSERT INTO $table($name) VALUES ('".$nameB."')"; mysql_query($q); } $i++; } } Quote Link to comment https://forums.phpfreaks.com/topic/266056-insert-into-question/ Share on other sites More sharing options...
xyph Posted July 21, 2012 Share Posted July 21, 2012 Perhaps if you echo'd $q, you might realize what your script is doing. The results you're getting are exactly what you've programmed it to do. This little article might help further http://www.ntchosting.com/mysql/insert-data-into-table.html Quote Link to comment https://forums.phpfreaks.com/topic/266056-insert-into-question/#findComment-1363339 Share on other sites More sharing options...
jcbones Posted July 21, 2012 Share Posted July 21, 2012 Try this: UN-TESTED! <?php //syntax highlighting. function set($table) { $result = mysql_query("SHOW COLUMNS FROM $table"); //no need to select all data, just get the column info. while ($row = mysql_fetch_assoc($result)) { //loop through the data resource. $name = $row['Field']; //pull out the field name. $nameB = $_POST[$name]; //get the form data that matches the field name. if(strtolower($name) <> 'id'){ //if the field is not 'id', case sensitive here. might want to do a strtolower() on the field name. $columns[] = $name; //store the columns in an array. $values[] = $nameB; //store the values in an array. Indexes will match the column name. } //close if. } //close while; $q = "INSERT INTO $table(" . implode(',',$columns) . ") VALUES ('" . implode('\',\'',$values) . "')"; //implode the data into your query string. mysql_query($q) or trigger_error('(' . $q . ') has encountered the error: <br />' . mysql_error()); //run the query, trigger an error if it fails. } //close function. Quote Link to comment https://forums.phpfreaks.com/topic/266056-insert-into-question/#findComment-1363346 Share on other sites More sharing options...
antfuentes87 Posted July 21, 2012 Author Share Posted July 21, 2012 Thank you jcbones, with the comments I was able to understand exactly what you did. Quote Link to comment https://forums.phpfreaks.com/topic/266056-insert-into-question/#findComment-1363347 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.