Pereiti prie turinio

Php PDO foreach cikle insertina du kart ta pačia užklausą


Rekomenduojami pranešimai

Pereinu iš senos dle prie wp ir rašau skriptą kad perkelti visas naujienas su nuotraukomis. Susidūriau su problema kad ta pati INSERT daro du kartus nors pabandymui ciklo gale naudoju break;

 

Failas stovi localhost tarp wp failų www direktorijoje.

 

<?php
header("Content-Type: text/html; charset=utf-8");
//Prijungiu DB
$dbh = new PDO('mysql:host=localhost;dbname=sklukas', 'root', '');
//
//Mysql koduote 
$dbh->exec("set names utf8");
$dbh->exec("SET CHARACTER SET 'utf8");
//
//Kategorijos id 3 = Naujienos
$categoryID = 3;

//Suzinau MAX id kad butu galima nurodyti kituose lenteles laukuose
$stmt = $dbh->query("SELECT MAX(ID) FROM wp_posts");
$maxID = $stmt->fetchColumn();
$maxID++;
$firstInsertID = $maxID;
//
echo $maxID;
//
//Paiimtu duomenis is senos lenteles
   foreach($dbh->query('SELECT id, date, short_story, full_story,title, alt_name FROM dle_post WHERE category = "1" ORDER BY id ASC ') as $row) {

       $maxID = "";
       $date = $row['date'];
       $dleNewsID = $row['id'];
       $title = $row['title'];
       $altTitle = $row['alt_name'];

       if($row['full_story'] == ''){
           $fullStory = $row['short_story'];
       } else {
           $fullStory = $row['full_story'];
       }


       // Ištrinu html brieda pridėta 
       $fullStory = preg_replace("/<br.*/", '', $fullStory);

       //Ištraukiu paveikslėlį pagal senos naujienos id
       $stmt = $dbh->prepare('SELECT images FROM dle_images WHERE news_id = :dleNewsID');
       $stmt->execute(array(':dleNewsID'=> $dleNewsID));
       $result = $stmt->fetch(PDO::FETCH_ASSOC);
       //var_dump($result);
       //Tikrinu as yra paveikslėlis, jei taip darau vėjus 
       if($result != false){
           $result['images'] = preg_replace("/\d{4}-\d{2}/", '2017/05', $result['images']);
           //var_dump($result);

           $photoNameWithDate = $result['images'];
           $photoNameWithOutDate = preg_replace("/\d{4}-\d{2}/", '', $result['images']);

           $stmt = $dbh->prepare('SELECT `post_id` FROM `wp_postmeta` WHERE `meta_value` = :imageName');
           $stmt->execute(array(':imageName'=> $result['images']));
           $result = $stmt->fetch(PDO::FETCH_ASSOC);


           $oldPostID = $result['post_id'];
           $stmt = $dbh->prepare('UPDATE `wp_postmeta` SET `post_id` = :firstInsertID WHERE `post_id` = :oldPostID');
           $stmt->execute(array(':oldPostID'=> $oldPostID, ':firstInsertID' => $firstInsertID));
           $result = $stmt->fetch(PDO::FETCH_ASSOC);
       }
       //Insertinu pirma naujien
       $sth = $dbh->prepare('INSERT INTO wp_posts (`ID`,`post_author`, `post_date`, `post_date_gmt`, `post_content`, `post_title`, `post_excerpt`, `post_status`, `comment_status`, `ping_status`, `post_password`, `post_name`, `to_ping`, `pinged`, `post_modified`, `post_modified_gmt`, `post_content_filtered`, `post_parent`, `guid`, `menu_order`, `post_type`, `post_mime_type`, `comment_count`)
                           VALUES
                                                           (:ID, :post_author, :post_date, :post_date_gmt, :post_content, :post_title, :post_excerpt, :post_status, :comment_status, :ping_status, :post_password, :post_name, :to_ping, :pinged, :post_modified, :post_modified_gmt, :post_content_filtered, :post_parent, :guid, :menu_order, :post_type, :post_mime_type, :comment_count)');
       $firstInsert = array(
                   'ID'                    => $firstInsertID,
                   'post_author'           => 1,
                   'post_date'             => $date,
                   'post_date_gmt'         => $date,
                   'post_content'          => $fullStory,
                   'post_title'            => $title,
                   'post_excerpt'          => '',
                   'post_status'           => 'publish',
                   'comment_status'        => 'open',
                   'ping_status'           => 'open',
                   'post_password'         => '',
                   'post_name'             => $altTitle,
                   'to_ping'               => '',
                   'pinged'                => '',
                   'post_modified'         => $date,
                   'post_modified_gmt'     => $date,
                   'post_content_filtered' => '',
                   'post_parent'           => 0,
                   'guid'                  => "http://localhost/?p=$firstInsertID",
                   'menu_order'            => 0,
                   'post_type'             => 'post',
                   'post_mime_type'        => '',
                   'comment_count'         => 0
                   );

       $sth->execute($firstInsert);
       //Tikrinu ar yra sutvarkytas paveikselis
       if(!empty($photoNameWithDate)){
           $sth = $dbh->prepare('INSERT INTO wp_posts (`post_author`, `post_date`, `post_date_gmt`, `post_content`, `post_title`, `post_excerpt`, `post_status`, `comment_status`, `ping_status`, `post_password`, `post_name`, `to_ping`, `pinged`, `post_modified`, `post_modified_gmt`, `post_content_filtered`, `post_parent`, `guid`, `menu_order`, `post_type`, `post_mime_type`, `comment_count`)
                               VALUES
                                                               (:post_author, :post_date, :post_date_gmt, :post_content, :post_title, :post_excerpt, :post_status, :comment_status, :ping_status, :post_password, :post_name, :to_ping, :pinged, :post_modified, :post_modified_gmt, :post_content_filtered, :post_parent, :guid, :menu_order, :post_type, :post_mime_type, :comment_count)');
           $SecondInsert = array(
                       //'ID'                    => $id,
                       'post_author'           => 1,
                       'post_date'             => $date,
                       'post_date_gmt'         => $date,
                       'post_content'          => '',
                       'post_title'            => $photoNameWithOutDate,
                       'post_excerpt'          => '',
                       'post_status'           => 'inherit',
                       'comment_status'        => 'open',
                       'ping_status'           => 'closed',
                       'post_password'         => '',
                       'post_name'             => $photoNameWithOutDate,
                       'to_ping'               => '',
                       'pinged'                => '',
                       'post_modified'         => $date,
                       'post_modified_gmt'     => $date,
                       'post_content_filtered' => '',
                       'post_parent'           => $firstInsertID,
                       'guid'                  => "http://localhost/wp-content/uploads/$photoNameWithDate",
                       'menu_order'            => 0,
                       'post_type'             => 'attachment',
                       'post_mime_type'        => 'image/jpeg',
                       'comment_count'         => 0
                       );

           $sth->execute($SecondInsert);
       }
}

Redagavo Gemalas
Nuoroda į pranešimą
Dalintis kituose puslapiuose

Kaip matau tau $firstInsert betkokiu atvėju insertins į duombazę, o po $sth->execute($firstInsert) tu dar sukuri naują įrašą tik su paveikslėlio duomenim? Tai jei tau $result == true, abudu insertai ivyksta. Galėtum daugiau aprašyt patį algoritmą kaip įsivaizduoji tas insertinimas turėtu vykti.

Nuoroda į pranešimą
Dalintis kituose puslapiuose

Zodziu sutvarkiau kazka tik nezinau ka... tiek kad veikia bet speju labai trapus skriptas :D atsiprasau uz //komentarus gal kam kadaa prireiks.. bet abejoju.

 


<!DOCTYPE html>
<html lang="en"> 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<?php
header("Content-Type: text/html; charset=utf-8");
//Prijungiu DB
$dbh = new PDO('mysql:host=localhost;dbname=sklukas', 'root', '');
//
//Mysql koduote 
$dbh->exec("set names utf8");
$dbh->exec("SET CHARACTER SET 'utf8");
//
//Kategorijos id 3 = Naujienos
$categoryID = 3;


//
//Paiimtu duomenis is senos lenteles
   foreach($dbh->query('SELECT id, date, short_story, full_story,title, alt_name FROM dle_post WHERE category = "1" ORDER BY id ASC ') as $row) {
   	//Suzinau MAX id kad butu galima nurodyti kituose lenteles laukuose
	$stmt = $dbh->query("SELECT MAX(ID) FROM wp_posts");
	$maxID = $stmt->fetchColumn();
	$maxID++;
	$firstInsertID = $maxID;
	//
       //$maxID = "";
       $date = $row['date'];
       $dleNewsID = $row['id'];
       $title = $row['title'];
       $altTitle = $row['alt_name'];

       if($row['full_story'] == ''){
           $fullStory = $row['short_story'];
       } else {
           $fullStory = $row['full_story'];
       }

       $fullStory = preg_replace("/<br.*/", '', $fullStory);
       //@@Insertinu pagrindine naujiena.
	$sth = $dbh->prepare('INSERT INTO wp_posts (`ID`,`post_author`, `post_date`, `post_date_gmt`, `post_content`, `post_title`, `post_excerpt`, `post_status`, `comment_status`, `ping_status`, `post_password`, `post_name`, `to_ping`, `pinged`, `post_modified`, `post_modified_gmt`, `post_content_filtered`, `post_parent`, `guid`, `menu_order`, `post_type`, `post_mime_type`, `comment_count`)
                           VALUES
                                                           (:ID, :post_author, :post_date, :post_date_gmt, :post_content, :post_title, :post_excerpt, :post_status, :comment_status, :ping_status, :post_password, :post_name, :to_ping, :pinged, :post_modified, :post_modified_gmt, :post_content_filtered, :post_parent, :guid, :menu_order, :post_type, :post_mime_type, :comment_count)');
       $firstInsert = array(
                   'ID'                    => $firstInsertID,
                   'post_author'           => 1,
                   'post_date'             => $date,
                   'post_date_gmt'         => $date,
                   'post_content'          => $fullStory,
                   'post_title'            => $title,
                   'post_excerpt'          => '',
                   'post_status'           => 'publish',
                   'comment_status'        => 'open',
                   'ping_status'           => 'open',
                   'post_password'         => '',
                   'post_name'             => $altTitle,
                   'to_ping'               => '',
                   'pinged'                => '',
                   'post_modified'         => $date,
                   'post_modified_gmt'     => $date,
                   'post_content_filtered' => '',
                   'post_parent'           => 0,
                   'guid'                  => "http://localhost/?p=$firstInsertID",
                   'menu_order'            => 0,
                   'post_type'             => 'post',
                   'post_mime_type'        => '',
                   'comment_count'         => 0
                   );
       $sth->execute($firstInsert);
       unset($sth);
       //@@

       echo $maxID." <br>";


       //@@ Istraukiu senus paveikslius is senos DLE bazes pagal senos naujienos id is senos DLE
       $stmt = $dbh->prepare('SELECT images FROM dle_images WHERE news_id = :dleNewsID');
       $stmt->execute(array(':dleNewsID'=> $dleNewsID));
       $result = $stmt->fetch(PDO::FETCH_ASSOC);
       //@@
       //
       //@@Jei paveikselis yra einu i vidu.
       if($result != false){
       	//Paakeiciu sena data i nauja
           $result['images'] = preg_replace("/^\d+-\d\d/", '2017/05', $result['images']);
           //Kur buvo priskirti du paveiksleliai vienai naujienai buvo atskirti |||. Pasilikaau tik viena nes tyngejau atskirineti ir pridejineti dar viena
           $result['images'] = preg_replace("/\|\|\|.*/", '', $result['images']);
           //
           //Paveikslelis su data
           $photoNameWithDate = $result['images'];
           //Paveikslelis be datos
           $photoNameWithOutDate = preg_replace("/^\d+\/\d\d+\//", '', $result['images']);
           //Paveikslelis be pletinio
           $photoNameWithExtenction = preg_replace("/.jpg/", '', $photoNameWithOutDate);
           //Be kito pletinio
           $photoNameWithExtenction = preg_replace("/.gif/", '', $photoNameWithExtenction);
           unset($result);

           //@@ Pasirenku nuotraukos naujiena kad gauti id
           $stmt = $dbh->prepare('SELECT `ID` FROM `wp_posts` WHERE `post_title` = :photoNameWithExtenction');
           $stmt->execute(array(':photoNameWithExtenction'=> $photoNameWithExtenction));
           $result = $stmt->fetch(PDO::FETCH_ASSOC);
           $photoPostID = $result['ID'];
           //@@
           //
           //@@Updatinu nuotraukos naujienos parent ID i naujai idetos pagrindines naujienos priskirta pagal nuotrauka
           $stmt = $dbh->prepare('UPDATE `wp_posts` SET `post_parent` = :firstInsertID WHERE `post_id` = :photoPostID');
           $stmt->execute(array(':photoPostID'=> $photoPostID, ':firstInsertID' => $firstInsertID));
           //@@
           //
           //@@Insertindaamaas sita priskiriu nuotrauka naujienai
           $sth = $dbh->prepare(	'INSERT INTO wp_postmeta (`post_id`, `meta_key`, `meta_value`)
                           		VALUES
                                  (:firstInsertID, :meta_key, :meta_value)');
       	$postMetaInsert = array(
       						':firstInsertID'         => $firstInsertID,
                               ':meta_key'  => '_thumbnail_id',
                               ':meta_value'        => $photoPostID);
       	$sth->execute($postMetaInsert);
       	unset($sth);
           //@@
       }

       //@@ Surisu naujienas su kategorijom
       $sth = $dbh->prepare('INSERT INTO wp_term_relationships (`object_id`, `term_taxonomy_id`, `term_order`)
                           VALUES
                                                           (:object_id, :term_taxonomy_id, :term_order)');
       $categoryInsert = array(':object_id'         => $firstInsertID,
                               ':term_taxonomy_id'  => $categoryID,
                               ':term_order'        => 0);
       $sth->execute($categoryInsert);
       unset($sth);

   }

?>

Redagavo Gemalas
Nuoroda į pranešimą
Dalintis kituose puslapiuose

Prisijunkite prie diskusijos

Jūs galite rašyti dabar, o registruotis vėliau. Jeigu turite paskyrą, prisijunkite dabar, kad rašytumėte iš savo paskyros.

Svečias
Parašykite atsakymą...

×   Įdėta kaip raiškusis tekstas.   Atkurti formatavimą

  Only 75 emoji are allowed.

×   Nuorodos turinys įdėtas automatiškai.   Rodyti kaip įprastą nuorodą

×   Jūsų anksčiau įrašytas turinys buvo atkurtas.   Išvalyti redaktorių

×   You cannot paste images directly. Upload or insert images from URL.

Įkraunama...
  • Dabar naršo   0 narių

    Nei vienas registruotas narys šiuo metu nežiūri šio puslapio.

×
×
  • Pasirinkite naujai kuriamo turinio tipą...