S
S
sergey19892016-01-30 20:17:33
PHP
sergey1989, 2016-01-30 20:17:33

How to add data in MySQL from two loops?

Good day. I wrote a parser, but when adding data to the database, a problem arose that first the data from the first cycle is written, and then from the second, as a result, a shift by ID is obtained. How can data from two cycles be written in one go?

function mysql_insert($table, $field, $insert) {
  $send_data = mysql_query("INSERT INTO $table ($field) VALUES ('$insert')");
  // return $send_data;
  if ($send_data) {
    echo "OK";
  } else {
    echo "NOT";
  }
}


foreach ($domResultmore as $valuesec) {
  foreach ($valuesec->find('.entry-header h1') as $value_title) {

    echo $p++;
    echo $value_title->innertext . '<br>';
    mysql_insert(wp_posts, post_title, $value_title->innertext);

  }
  foreach ($valuesec->find('.entry-meta') as $meta) {
    echo $s++;
    echo $meta->innertext . '<br>';

    mysql_insert(wp_posts, post_content, $meta->innertext);
  }
  foreach ($valuesec->find('.entry-content a img') as $valuemeta) {
    $src = $valuemeta->src;
    $arr = explode("/", $src);
    $name = end($arr);
    file_put_contents("data/$name", file_get_contents($valuemeta->src));

    
  
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
entermix, 2016-01-30
@entermix

And can you clarify what the shift by ID means?
UPD: In the loops, we create a new array, where we collect the results, after which we go through it and add it to the database, or we add it in the first loop, and in the rest we update the already created rows (but that would be stupid)

$i = 0;
$results = [];

foreach ($domResultmore as $valuesec) {
    
    foreach ($valuesec->find('.entry-header h1') as $value_title) {
        $results[$i]['post_title'] = $value_title->innertext;
    }
    foreach ($valuesec->find('.entry-meta') as $meta) {
        $results[$i]['post_content'] = $meta->innertext;
    }
    foreach ($valuesec->find('.entry-content a img') as $valuemeta) {
        $name = end(explode("/", $valuemeta->src));

        $results[$i]['src']['name'] = $meta->innertext;
        $results[$i]['src']['data'] = file_get_contents($valuemeta->src);
    }
}

foreach ($results as $result) {
    echo '<pre>';
    print_r($result);
    echo '</pre>';
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question