0

I have an array that looks like:

Array ( [0]  => 'overview' 
        [53] => 'PUBLIC' 
        [54] => '-friendsD' 
        [55] => 'XHTML' 
        [56] => '1.0' 
        [57] => 'Transitional' 
        [77] => 'People' );

How can I take those values and put them into MySQL with an INSERT? For example INSERT INTO array_value VALUES ('$arrayvalues'). For each array value is a new post into MySQL.

I tried this:

  <?php
$homepage = file_get_contents('http://www.mysiteexample.com/');
$array = explode(" ",$homepage);
foreach($array as $val) {
$servername = "localhost";
$username = "111";
$password = "111";
$dbname = "111";
    // Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} else {
if ($val != " "){
$val = $val. " ";
    $query = "INSERT INTO `111` (word) VALUES ('$val')";

       $executeQuery = $conn->query($query) === TRUE;

    }

    if ($executeQuery === TRUE) {
        //echo "New record created successfully";
echo $val;
    } else {
        //echo "Error: " . $query . "<br>" . $conn->error;
echo $val. " ";
    }}
    $conn->close();
}
?>

This works to some extent. It produces many empty results how could it be filtered to have no empty posts. I tried the $val != " " but this didnt work.

2
  • Have you tried something? Show it! Commented Aug 6, 2015 at 22:47
  • Did you try the answer I provided? Commented Aug 6, 2015 at 22:58

1 Answer 1

2

You can loop through the array and build the query. Then execute it.

<?php
$homepage = file_get_contents('http://www.mywebsite.com/');
$array = explode(" ",$homepage);

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

    // Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} else {
    $executeQuery;

    for ($i = 0; $i < count($array); $i++) {
        if (!empty($array[$i])) {
            $executeQuery = $conn->query("INSERT INTO `yourTable` (yourField) VALUES ('" . $array[$i]  . "')");
        }
    }

    if ($executeQuery === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $query . "<br>" . $conn->error;
    }
    $conn->close();
}
?>
Sign up to request clarification or add additional context in comments.

Comments

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.