-5

I have this string as my input string:

12345-45678-543245

So in my database table I want to insert these dash separated strings as followed:

   part_id  |  Part numbers
------------------------------
   1        |     12345
   2        |     45678
   3        |    543245

I have no idea how to do this? Maybe some hints and advices would help me.

Rizier123
  • 58,877
  • 16
  • 101
  • 156

3 Answers3

3

This should work for you:

Just PDO::prepare() your INSERT statement and then loop through your explode()'d input and insert the values into your db.

<?php

    $input = "12345-45678-543245";
    $arr = explode("-", $input);

    $host = "localhost";
    $dbname = "myDBName";
    $user = "root";
    $password = "";

    try {

        $dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = $dbh->prepare("INSERT INTO myTable (`part_id`, `Part numbers`) VALUES(?, ?)");
        foreach($arr as $k => $v)
            $stmt->execute([($k+1), $v]);

    } catch(PDOException $e) {
        echo $e->getMessage();
    }

?>
Rizier123
  • 58,877
  • 16
  • 101
  • 156
1
$string  = '12345-45678-543245';
$array = explode('-',$string);
Foreach($array as $arr){
    //Here add to database...
}

But that is very simple PHP... Please visit php.net for more info ¬.¬'

Kyto
  • 181
  • 3
  • 12
1

You can explode your string to separate it into sections.

<?php
$string = "12345-45678-543245"

$parts = explode("-", $string);

$p0 = $parts[0];  //12345
$p1 = $parts[1];  //45678
$p2 = $parts[2];  //543245
?>
jakecfc1992
  • 196
  • 11