oneshotflinch Posted December 27, 2011 Share Posted December 27, 2011 I need a php function that will take an undertermined very long list of names as a single text string that are seperated by commas, e.g. "john,mary,ken,mark,..." loop through and insert each of the names as a new table row. When all the names have been inserted the loop ends. I am familiar with c/c++ but new to php. Any assistance to the best way to do this much appreciated. Quote Link to comment https://forums.phpfreaks.com/topic/253890-insert-looping-using-a-single-string-of-text-of-names-seperated-by-commas/ Share on other sites More sharing options...
QuickOldCar Posted December 27, 2011 Share Posted December 27, 2011 something similar to this, you must change to your values I included the reference links for you to read It would be best to auto_increment the values http://dev.mysql.com/doc/refman/5.6/en/example-auto-increment.html here's a sample auto_increment create CREATE TABLE users ( id INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, fname VARCHAR(255) ) if needed additional can modify the create or alter it later ALTER TABLE users ADD lname VARCHAR(250) <?php //a comma separated list $text_list = "john,mary,ken,mark"; //explode() http://php.net/manual/en/function.explode.php $text_array = explode(",", $text_list); //can also make the list as an array, will not need to explode it //$text_array = array("john","mary","ken","mark"); //create a mysql connection http://php.net/manual/en/function.mysql-connect.php $con = mysql_connect("localhost","mysql admin name","mysql password");//change to your admin credentials if (!$con) { die('Could not connect: ' . mysql_error()); } /*connect to database*/ mysql_select_db("database name", $con);//change your database name //foreach loop http://php.net/manual/en/control-structures.foreach.php //within the foreach an insert or create statement http://dev.mysql.com/doc/refman/5.6/en/insert.html foreach($text_array as $text){ mysql_query("INSERT INTO users (fname) VALUES ('$text')"); echo $text . " added <br />"; } //close the mysql connection mysql_close($con); ?> If it's really large lists, you can also use load data infile Quote Link to comment https://forums.phpfreaks.com/topic/253890-insert-looping-using-a-single-string-of-text-of-names-seperated-by-commas/#findComment-1301581 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.