1

I have a PHP/MYsql question.

I am trying to insert a new row after each comma.

Basically, I want this function:

Let's say we have a textbox with the following text:

Basketball, Tennis, Futbol, Volleyball --> Submit Button

After the submit button is clicked, I want to Insert a new row in one table after each word.

Basically, I want the outcome in the DB like this

id      category
1       Basketball
2       Tennis
3       Futbol
4       Volleyball

Anyone can help me with this ?

thanks :)

roberttdev
  • 42,762
  • 2
  • 20
  • 23
denis
  • 351
  • 1
  • 7
  • 16

5 Answers5

6

You could just loop through each, and add them individually.

$input = "Basketball, Tennis, Futbol, Volleyball";
foreach (explode(',',$input) as $piece)
{
    $piece = mysql_real_escape_string(trim ($piece));
    $sql = "INSERT INTO table VALUES($piece)";
    //Run sql
}
Jess
  • 8,628
  • 6
  • 49
  • 67
  • 1
    It's imperative not to forget `mysql_real_escape_string($piece)` when using it with the real input variable. – mario Apr 16 '11 at 23:13
  • @mario your right, I didn't because I used a variable, but if he is getting it from a form (which he is) then it is imperative. @halfdan He didn't give a table, columns, etc. Am I suppose to read his mind to format my sql? – Jess Apr 16 '11 at 23:21
  • Superb.. Exact answer what i researched. – Abijith Ajayan Jul 28 '19 at 12:52
  • 1
    @AbijithAjayan If I were doing this today, and you're running PHP 5.6+, look at this instead - https://stackoverflow.com/questions/15094048/prepared-multiple-insert-mysqli – Jess Jul 29 '19 at 22:33
1

You can do it in one query like so:

$Input = explode(',', 'a, b, c, d, e, f, g');
$Query = 'INSERT INTO Table(TableColumn) VALUES';

foreach ($Input as $Entry)
{
    $Query .= '("' . $Entry . '"), ';
}

$Query = substr_replace($Query, '', -2);

mysql_query($Query);

The outputted query will look like this:

INSERT INTO Table(TableColumn) VALUES("a"), ("b"), ("c"), ("d"), ("e"), ("f"), ("g")
Zach Rattner
  • 20,745
  • 9
  • 59
  • 82
0

Is this what you are looking for ??

http://php.net/manual/en/function.fgetcsv.php

ankur.singh
  • 658
  • 5
  • 11
0

Just grab the values from the super global GET/POST/REQUEST array:

$categories = $_REQUEST['categories'];

Make them seperate values:

$categories = explode(",", $categories);

For each value in the array create a SQL statement and execute it.

foreach($categories as $category) {
    $category = trim($category); // Remove possible whitespace
    $sql = "INSERT INTO table (category) VALUES ('%s')";
    $sql = sprintf($sql, mysql_real_escape_string($category));
    mysql_query($sql);
}
halfdan
  • 33,545
  • 8
  • 78
  • 87
0

Shortest code:

$Input = explode(',', 'a, b, c, d, e, f, g');
if($Input){
    echo('INSERT INTO Table(TableColumn) VALUES ("'.
      implode('"),("',$Input).'")');
} 

However you would need to have your $Input escaped.

romaninsh
  • 10,606
  • 4
  • 50
  • 70