0

I'm trying to take an array and insert it into seperate rows in a MYSQL database.

Basically, there's an HTML form for a top 5 list that I want to input in one field, but with each value seperated by commas. So, for example (Artist 1, Artist 2, Artist 3, etc.)

These 5 values then have to be seperated into 5 values that are then inserted into 5 rows in a MYSQL database.

So the HTML form looks like this:

 <tr>
 <td>Loud Rock</td>
 <td><label for="lr_topfive"><input type="text" placeholder="" name="lr_topfive" size="75"
 maxlength="100" autofucus required /></label></td>
 </tr>

and the form value is sent to another php file with this code in it:

$val = $_POST['lr_topfive'];
$data = str_getcsv($val);

??????


$lr_one = mysql_prep($_POST['lr_one']);
$lr_two = mysql_prep($_POST['lr_two']);
$lr_three = mysql_prep($_POST['lr_three']);
$lr_four = mysql_prep($_POST['lr_four']);
$lr_five = mysql_prep($_POST['lr_five']);

$query = "INSERT INTO xyz_wb (lr_one, lr_two, lr_three, lr_four, lr_five) VALUES ('{$lr_one}','{$lr_two}', '{$lr_three}', '{$lr_four}', '{$lr_five}')";
$result = mysql_query($query, $connection);
    if ($result) {
        redirect_to("email-ready.php");
    } else {
    //display error message
    echo "<p>Yikes!</p>";
    echo "<p>" . mysql_error() . "</p>";
    }

I get that the 'lr_topfive' value is parsed and seperated into distinct values by the first two lines, but I dont know what to do before inserting these values into the MYSQL DB.

3

1 Answer 1

1

I think you are just looking for:

$top_five_array = explode(',', $_POST['lr_topfive']);

and then:

$lr_one = mysql_prep($top_five_array[0]);
$lr_two = mysql_prep($top_five_array[1]);
....

However, this will break if there are not exactly 4 comma's in your input field.

Apart from that you need to switch to prepared statements using PDO or mysqli, see the comments below your question.

Sign up to request clarification or add additional context in comments.

2 Comments

How would I insert the ($top_five_array[0]) variables into the DB? Wouldn't I need to turn it back into a string first?
@user1478878 That's what I was doing in the second part, assigning it to $lr_one, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.