Jump to content

Insert Looping using a Single String of text of names seperated by Commas


Recommended Posts

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.

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

 

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.