0

I would like to into a string into mysql and understand I have to explode the string into an array before it can be inserted.

How would I write the PHP object oriented code to insert the string?

I have two variables:

$id = "Apple"    and    $product = "Pie, Candy"

This is what I would like the database to look like:

ID          Product
---         -------
Apple       Pie
Apple       Candy

This is what I have written so far in my code:

$id = "Apple";
$product = "Pie, Candy";
$product_arr = explode(", ",$product);

if (is_array($product_arr)) {
    $sql = "INSERT INTO table1 (id, product) VALUES ";
    $value_arr = array();

    foreach($product_arr as $row) {
        $prdct = mysql_real_escape_string($row[0]);
        $value_arr[] = "('$id','$prdct')";
    }
    mysqli_query($conn,$sql);
}
Dan T 4591
  • 11
  • 2
  • 1
    Possible duplicate of [How to include a PHP variable inside a MySQL insert statement](http://stackoverflow.com/questions/7537377/how-to-include-a-php-variable-inside-a-mysql-insert-statement) – Sagar Bhut Apr 11 '17 at 04:41
  • Be careful. **DO NOT** mix different APIs, especially not the garbage, old `mysql_query` one. `mysql_real_escape_string` has been removed from PHP 7. – tadman Apr 11 '17 at 05:07
  • **WARNING**: When using `mysqli` you should be using [parameterized queries](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add user data to your query. **DO NOT** use manual escaping and string interpolation or concatenation to accomplish this because you will create severe [SQL injection bugs](http://bobby-tables.com/). Accidentally unescaped data is a serious risk. – tadman Apr 11 '17 at 05:07
  • If you create a singular prepared statement of the form `INSERT INTO x (a,b) VALUES (?,?)` then you can bind values to it each time through the loop and execute it over and over. For small amounts of data this is acceptably fast. – tadman Apr 11 '17 at 05:08

1 Answers1

0

You can try this

$id = "Apple";
$product = "Pie, Candy";
$product_arr = explode(", ",$product);
$len = count($product_arr);

for($i=0;$i< $len;$i++){
    $product = $product_arr[$i];
    $abc = "INSERT INTO table1 (id, product) VALUES "."('$id','$product')";
    if ($con->query($abc) === TRUE) {
    }
    else
    {
        //echo "Error: " . $abc . "<br>" . $con->error;
    }
}

Output

A.A Noman
  • 5,244
  • 9
  • 24
  • 46