Записи в таблицы базы данных
-
Всем привет..
Помогите пожалуйста решить проблему. Есть сайт киношный: http://institut8.ru/
Обновление идет через пп.Там стоит плагин, добавляющий новые записи. Проблема в том, что как только появляется новый сериал или фильм с обновленной датой, имеющий одинаковый post_url, например сериал: Кухня Сезон 2 Серия 1, потом выходит Кухня Сезон 2 Серия 2 и так далее все новые серии .. или это может быть любой другой фильм с одинаковым post_url, то получается в одном данном посте два или бывает больше дублированных записей прямо в одном посте. То есть полностью в одной записи, как бы добавляется под ней вторая с другим тайтлом, а весь остальной контент такой же.. и так может быть 3-4 одинаковых записи с разными тайтлами в одном посте, они как пирамидка наклыдываются. Вот к примеру:
http://institut8.ru/vikings_-_season_1/
http://institut8.ru/jack_reacher/
http://institut8.ru/kuhnya_-_sezon_2/
http://institut8.ru/realnie_pacany_-_sezon_5/
http://institut8.ru/autoreiji/
http://institut8.ru/safe_haven/
http://institut8.ru/pawn/
http://institut8.ru/a_laveugle/
http://institut8.ru/the_incredible_burt_wonderstone/Точно есть информация, что ответ кроется в файле плагина партнерки functions.php, в строках
mysql_query(«INSERT INTO
".$table_prefix."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 (NULL, 1, ‘».$post_date.»‘, ‘».$post_date_gmt.»‘, ‘».$post_text.»‘, ‘».$post_title.»‘, », ‘publish’, ‘open’, ‘open’, », ‘».$post_url.»‘, », », ‘».$post_date.»‘, ‘».$post_date_gmt.»‘, », 0, », 0, ‘post’, », 0)», $db);Которые добавляют запись в базу. Как то нужно перед ней добавить условие, IF что если запись с таким post_url уже есть, то не ДОБАВЛЯТЬ все строки таблицы по новой там, но ОБНОВИТЬ только title.
Что бы он не обновлял все, так как имеет большое значение сохранить написанный ранее контент, а обновлял только тайтл. И если post_url разные, то как обычно, пусть публикуется новый пост.Это требует навыков php и mysql, которыми я не обладаю… может посоветуете, как и какое условие необходимо прописать, что бы он в случае содинаковым post_url , обновлял только title?
А вот дальше если поможет весь код файла плагина functions.php:
<?php
$ch = curl_init();/* get data from MovieShop update server */
function movieshop_get_data($action, $from = null, $how_much = null) {
global $ch;
$url = MOVIESHOP_UPDATE_SERVER;
if (strpos($url, «?») === false) {
$url .= «?»;
}$url .= «&lang=».MOVIESHOP_LANGUAGE;
$url .= «&shop=».MOVIESHOP_PARENT_SHOP_URL;
$url .= «&aid=».MOVIESHOP_DISTRIBUTOR_ID;
$url .= «&genres=».MOVIESHOP_DATA_GENRES;
$url .= «&years=».MOVIESHOP_DATA_YEARS;
$url .= «&last_update=».MOVIESHOP_LAST_UPDATE;
$url .= «&action=».$action;if (!is_null($from)) {
$url .= «&from=».$from;
}
if (!is_null($how_much)) {
$url .= «&how_much=».$how_much;
}curl_setopt($ch, CURLOPT_URL,$url);
//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
curl_setopt($ch, CURLOPT_TIMEOUT, 180);
$result = curl_exec($ch);if (!curl_errno($ch)) {
$decoded = «»;
for ($i=0; $i < ceil(strlen($result)/256); $i++)
$decoded = $decoded . base64_decode(substr($result,$i*256,256));
return unserialize($decoded);
}
else {
movieshop_log(«ERROR: «.curl_error($ch));
exit();
}
}/* update MovieShop config */
function movieshop_update_config($PARENT_SHOP_URL, $DISTRIBUTOR_ID, $LANGUAGE, $UPDATE_SERVER, $USE_GENRES, $USE_YEARS, $USE_COUNTRIES, $DATA_GENRES, $DATA_YEARS, $ACTORS_TAGS, $LAST_UPDATE = MOVIESHOP_LAST_UPDATE) {
$config = «<«.»?».»phpn».
$config .= «define(‘MOVIESHOP_PATH’, ABSPATH . ‘wp-content/plugins/movieshop/’);n»;
$config .= «define(‘MOVIESHOP_PARENT_SHOP_URL’, ‘».$PARENT_SHOP_URL.»‘);n»;
$config .= «define(‘MOVIESHOP_DISTRIBUTOR_ID’, ‘».$DISTRIBUTOR_ID.»‘);n»;
$config .= «define(‘MOVIESHOP_LANGUAGE’, ‘».$LANGUAGE.»‘);n»;
$config .= «define(‘MOVIESHOP_UPDATE_SERVER’, ‘».$UPDATE_SERVER.»‘);n»;
$config .= «define(‘MOVIESHOP_LAST_UPDATE’, ‘».$LAST_UPDATE.»‘);n»;
$config .= «define(‘MOVIESHOP_USE_GENRES’, «.$USE_GENRES.»);n»;
$config .= «define(‘MOVIESHOP_USE_YEARS’, «.$USE_YEARS.»);n»;
$config .= «define(‘MOVIESHOP_USE_COUNTRIES’, «.$USE_COUNTRIES.»);n»;
$config .= «define(‘MOVIESHOP_DATA_GENRES’, ‘».$DATA_GENRES.»‘);n»;
$config .= «define(‘MOVIESHOP_DATA_YEARS’, ‘».$DATA_YEARS.»‘);n»;
$config .= «define(‘MOVIESHOP_ACTORS_TAGS’, «.$ACTORS_TAGS.»);n»;
$config .= «?».»>»;@chmod(MOVIESHOP_PATH.’config.php’, 0777);
$fp = fopen(MOVIESHOP_PATH.’config.php’, «w»);
fwrite($fp, $config);
fclose($fp);
}/* outputs log message */
function movieshop_log($str = «») {
print $str;
if ($str != «») {
print «.»;
}
print «
«;for ($i = 0; $i<1024; $i++) {
print » «;
}
print «n»;flush();
}function movieshop_update() {
global $table_prefix;/* no time limit */
set_time_limit(0);
@ini_set(‘memory_limit’, ‘150M’);/* database connection */
$db = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_select_db(DB_NAME, $db);
mysql_query(«SET NAMES ‘».DB_CHARSET.»‘», $db);/* categories and tags from WordPress */
$wp_terms = array();
$sql = mysql_query(«SELECT * FROM «.$table_prefix.»terms w;», $db);
$counter=0;
while ($term = mysql_fetch_assoc($sql)) {
$wp_terms[] = $term[‘slug’];
$counter++;
}/* creating super categories */
$super_terms[‘genre’] = wp_create_category(«Films by genre»);
$super_terms[‘year’] = wp_create_category(«Films by year»);
$super_terms[‘country’] = wp_create_category(«Films by country»);/* updating categories */
movieshop_log(«Updating categories..»);
$data = movieshop_get_data(«categories»);
movieshop_log(«Received «.count($data).» categories from server»);
movieshop_log(«Updating database..»);if ($data) {
foreach($data as $category) {
if (!in_array($category[‘slug’], $wp_terms)) {
if ((MOVIESHOP_USE_GENRES && $category[‘type’] == ‘genre’) ||
(MOVIESHOP_USE_YEARS && $category[‘type’] == ‘year’) ||
(MOVIESHOP_USE_COUNTRIES && $category[‘type’] == ‘country’)) {
wp_insert_category(array(‘cat_name’ => $category[‘name’], ‘category_description’ => $category[‘name’], ‘category_nicename’ => $category[‘slug’], ‘category_parent’ => $super_terms[$category[‘type’]]));
}
}
}
}/* deleting useless categories */
if (!MOVIESHOP_USE_GENRES) {
$categories = get_categories(array(‘child_of’ => $super_terms[‘genre’], ‘hide_empty’ => false));
foreach ($categories as $cat) {
wp_delete_category($cat->cat_ID);
}
wp_delete_category($super_terms[‘genre’]);
}
if (!MOVIESHOP_USE_YEARS) {
$categories = get_categories(array(‘child_of’ => $super_terms[‘year’], ‘hide_empty’ => false));
foreach ($categories as $cat) {
wp_delete_category($cat->cat_ID);
}
wp_delete_category($super_terms[‘year’]);
}
if (!MOVIESHOP_USE_COUNTRIES) {
$categories = get_categories(array(‘child_of’ => $super_terms[‘country’], ‘hide_empty’ => false));
foreach ($categories as $cat) {
wp_delete_category($cat->cat_ID);
}
wp_delete_category($super_terms[‘country’]);
}/* categories and tags from WordPress, once again */
$wp_terms = array();
$sql = mysql_query(«SELECT w1.*, w2.term_taxonomy_id FROM «.$table_prefix.»terms w1 LEFT JOIN «.$table_prefix.»term_taxonomy w2 ON w1.term_id = w2.term_id», $db);
$counter=0;
while ($term = mysql_fetch_assoc($sql)) {
$wp_terms[$term[‘name’]] = $term[‘term_taxonomy_id’];
$counter++;
}/* updating posts */
movieshop_log();
movieshop_log(«Updating posts..»);
$counter=0;$steps = 0;
$from = 0;
$how_much = 500;
$posts_count = $how_much;while($posts_count == $how_much) {
movieshop_log(«Fetching data from server..»);
$data = movieshop_get_data(«posts», $from, $how_much);$steps += 1;
$from += $how_much;
$posts_count = count($data);movieshop_log(«Step «.$steps.». Received «.$posts_count.» new posts from server»);
movieshop_log(«Updating database..»);if ($data) {
foreach($data as $post) {
$post_date = date(«Y-m-d H:i:s», $post[‘date’]);
$post_date_gmt = date(«Y-m-d H:i:s», $post[‘date’]);
$post_url = $post[‘url’];
$post_title = $post[‘title’].» («.$post[‘year’].»)»;
$post_text = $post[‘text’];
$post_text = mysql_real_escape_string($post_text);
$post_title = mysql_real_escape_string($post_title);mysql_query(«INSERT INTO
".$table_prefix."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 (NULL, 1, ‘».$post_date.»‘, ‘».$post_date_gmt.»‘, ‘».$post_text.»‘, ‘».$post_title.»‘, », ‘publish’, ‘open’, ‘open’, », ‘».$post_url.»‘, », », ‘».$post_date.»‘, ‘».$post_date_gmt.»‘, », 0, », 0, ‘post’, », 0)», $db);if (mysql_errno() == 0) {
$post_id = mysql_insert_id();
if ($post_id > 0) {
/* adding meta-tags */
add_post_meta($post_id, «movieshop_title», $post[‘title’], true);
add_post_meta($post_id, «movieshop_title_ru», $post[‘title_ru’], true);
add_post_meta($post_id, «movieshop_title_en», $post[‘title_en’], true);
add_post_meta($post_id, «movieshop_genres», implode(«, «, explode(«|», $post[‘genres’])), true);
add_post_meta($post_id, «movieshop_countries», implode(«, «, explode(«|», $post[‘countries’])), true);
add_post_meta($post_id, «movieshop_year», $post[‘year’], true);
if ($post[‘cover_small’] != «») add_post_meta($post_id, «movieshop_cover_small», $post[‘cover_small’], true);
if ($post[‘cover_big’] != «») add_post_meta($post_id, «movieshop_cover_big», $post[‘cover_big’], true);
add_post_meta($post_id, «movieshop_url», $post[‘url_part’], true);
$actors = explode(«|», $post[‘actors’]);
$actors_str = array();
$actors_cnt = 0;
foreach($actors as $actor) {
$actors_cnt ++;
if ($actors_cnt <= 10) {
$tmp = explode(«:», $actor);
if (count($tmp) > 1) {
$actors_str[] = $tmp[1];
}
}
}
add_post_meta($post_id, «movieshop_actors», implode(«, «, $actors_str), true);
$directors = explode(«|», $post[‘directors’]);
$directors_str = array();
foreach($directors as $director) {
$tmp = explode(«:», $director);
if (count($tmp) > 1) {
$directors_str[] = $tmp[1];
}
}
add_post_meta($post_id, «movieshop_directors», implode(«, «, $directors_str), true);
if (($post[‘film_trailers’] != «») && ($post[‘film_trailers’] != null)) add_post_meta($post_id, «movieshop_trailer», stripslashes($post[‘film_trailers’]), true);/* updating tags and categories for that post */
$post_terms = explode(«|», $post[‘terms’]);
foreach($post_terms as $term) {
if (array_key_exists($term, $wp_terms)) {
$term_tax_id = $wp_terms[$term];
mysql_query(«INSERT INTO «.$table_prefix.»term_relationships VALUES («.$post_id.», «.$term_tax_id.», 0);»);
mysql_query(«UPDATE «.$table_prefix.»term_taxonomy SETcount=count+ 1 WHERE term_taxonomy_id = «.$term_tax_id.»;»);
}
}/* adding actors as tags */
if (MOVIESHOP_ACTORS_TAGS) {
wp_set_post_tags($post_id, implode(«, «, $actors_str));
wp_set_post_tags($post_id, implode(«, «, $directors_str), true);
}$counter++;
}
} else {
print mysql_error();
exit();
}
}
}
unset($data);
}
movieshop_log(«Done. Posts added: «.$counter);/* updating last_update time in MovieShop config */
if ($counter > 0) {
movieshop_update_config(MOVIESHOP_PARENT_SHOP_URL, MOVIESHOP_DISTRIBUTOR_ID, MOVIESHOP_LANGUAGE, MOVIESHOP_UPDATE_SERVER, MOVIESHOP_USE_GENRES, MOVIESHOP_USE_YEARS, MOVIESHOP_USE_COUNTRIES, MOVIESHOP_DATA_GENRES, MOVIESHOP_DATA_YEARS, MOVIESHOP_ACTORS_TAGS, time());
movieshop_log();
movieshop_log(«WordPress database is updated successfully»);
} else {
movieshop_log();
movieshop_log(«Completed.»);
}
}
?>Вопрос касается блога (видны только вошедшим пользователям).
- Форум «Записи в таблицы базы данных» закрыт для новых ответов.