1

I have two results/outputs from a couple of scripts.

Script 1 result:

    print_r($unit);

OUTPUT =  

Array ( [0] => http://one.com, [1] => http://two.com, [2] => http://three.com/, )

Script 2 result:

    echo $item."<br>"; 

OUTPUT = 

http://one.com,
http://two.com,
http://three.com,

I'm embarrassingly failing to failing to import either one into a MySQL table which has just two fields: ID and URL.

//Connect to MySQL...

// Attempt insert query execution

    $list=implode($unit);

    $sql = "INSERT INTO urls (url) VALUES ('$list')";
    if(mysqli_query($conn, $sql)){
        echo "Records added successfully.";
    } else{
        echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
    }

    // Close connection
    mysqli_close($conn);

The insert works but the code is inserting all 3 urls into a single field:

id  url
1   http://one.com,http://two.com,http://three.com,

DESIRED MySQL table result for both script 1 and 2:

id  url
1   http://one.com
2   http://two.com
3   http://three.com

THANKS for your thoughts!

7
  • $list=implode(",", $unit); try that out. Commented Nov 3, 2015 at 21:15
  • @Fred-ii- : I think he wants one row for each record. Commented Nov 3, 2015 at 21:17
  • @MateoBarahona 10-4. grazie Commented Nov 3, 2015 at 21:17
  • 1
    @MateoBarahona 10-4 = "acknowledged". grazie = "thank you". ;-) Commented Nov 3, 2015 at 21:19
  • 1
    @MateoBarahona prego (welcome) and there you have it, your Italian lesson for the day! (I'll bet you already knew that) (10-4, is widely used in the services area of the world, police, army, navy, etc.) ;-) Commented Nov 3, 2015 at 21:20

1 Answer 1

4

you are doing a bit wrong here, you need to explode the $unit on the basis of ',' instead of implode

here it is

if (is_array($unit)) {
    $unit = implode(',', $unit);
} // check if array, convert to string
$list = explode(',', $unit);
$stmt = mysqli_prepare($conn, "INSERT INTO urls(url)  VALUES (?)");
mysqli_stmt_bind_param($stmt, 's', $url);
foreach ($list as $url) {
    if (empty($url)) {
        continue;
    }

    mysqli_stmt_execute($stmt);
    echo "Records added successfully.";
}
Sign up to request clarification or add additional context in comments.

10 Comments

$list=implode(",", $unit); I guess I meant "explode"; my bad.
You're not sanitizing your values. That's EXTREMELY dangerous.
yes, but OP only wants to insert at the moment(this could also be a local project) @Terry
Local project is no excuse for using sloppy code.
The explode results in "Warning: explode() expects parameter 2 to be string, array given..." and the foreach line results in "Warning: Invalid argument supplied for foreach()..."
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.