PHP MYSQL在行中插入(如果不存在)或显示数据库中的内容
我正在开发一个脚本,它使用Curl从youtube获取标题和id,并将它们保存到具有以下结构的数据库:id | title | id | youtube | date 问题是我需要一个代码,这样,如果db中已经存在显示db中内容的标题,那么就可以卷曲以处理它并将其存储在db中PHP MYSQL在行中插入(如果不存在)或显示数据库中的内容,php,mysql,Php,Mysql,我正在开发一个脚本,它使用Curl从youtube获取标题和id,并将它们保存到具有以下结构的数据库:id | title | id | youtube | date 问题是我需要一个代码,这样,如果db中已经存在显示db中内容的标题,那么就可以卷曲以处理它并将其存储在db中 id_youtube($q); // this function get the id_youtube title_youtube($q); // this function get the youtube title
id_youtube($q); // this function get the id_youtube
title_youtube($q); // this function get the youtube title
$id = id_youtube($q);
$q = title_youtube($q);
This is my code to insert values to DB
mysql_connect('localhost', 'db_user', 'pw_name') or die($connect_error);
mysql_select_db('db_name') or die($connect_error);
mysql_query("INSERT IGNORE INTO posts (id, title, id_youtube,date) VALUES (null,'$q', '$id',now())");
现在,只需保存到DB,如果存在,请再次插入新行(重复行),我需要如下方法:
if $q already exist {
//query to show content from DB
}else{
// Code tu get titles and ids WHIT Curl
//mysql_query("INSERT IGNORE INTO posts (id, title, id_youtube,date) VALUES (null,'$q', '$id',now())");
}
有什么帮助吗?您可能可以执行一个查询,尝试查找具有您正在分析的id的行。如果查询返回至少一行(实际上只有一行),您将使用第二个查询获取信息,否则将执行插入查询 类似于以下伪代码:
$query = "SELECT * FROM posts WHERE id_youtube = '$id' LIMIT 1";
$result = mysql_query($query);
if(mysql_num_rows($result) == 1)
$query = "SELECT yourColumns FROM posts WHERE id_youtube = '$id'";
display_the_info();
else
mysql_query("INSERT IGNORE INTO posts (id, title, id_youtube,date) VALUES (null,'$q', '$id',now())");
您还应该使用myslqi函数,而不是mysql函数 PSA:mysql的函数是。不建议编写新代码,因为这样会阻止您将来升级。我考虑了这一点,但现在我使用另一个php版本