【发布时间】:2017-08-04 18:41:15
【问题描述】:
基本上我有一个调用外部 XML 文件的 php 脚本
然后它将某些数据从 xml 文件插入到 foreach 循环内的 mysql 数据库中
但是当我检查数据库时它是空的
我做错了什么
xml包含以下结构
<jobs>
<job>
<jobref>987654321</jobref>
<title>TITLE HERE</title>
<url>
URL HERE
</url>
<salary>£85 - £105/day benifits</salary>
<location>LOCATION</location>
<description>desc</description>
<category>CAT HERE</category>
</job>
<job>
<jobref>123456789</jobref>
<titleTITLE HERE</title>
<url>
URL HERE
</url>
<salary>£85 - £105/day benifits</salary>
<location>LOCATION</location>
<description>desc</description>
<category>CAT</category>
</job>
</jobs>
下面是PHP代码
<?php
$dbu = 'user';
$dbp = 'pass';
$dbh = 'localhost';
$dbn = 'dbname';
$dbc = mysql_pconnect($dbh,$dbu,$dbp);
// Get XML Feed
$startPage = $_GET['page'];
$perPage = 3000;
$currentRecord = 0;
$xml = simplexml_load_file("urlhere");
$jobs = $xml->xpath("/jobs/job");
foreach ($jobs as $job)
{
mysql_select_db($dbn,$dbc);
$query = mysql_query("INSERT INTO `listings` (`jobref`,`title`,`url`,`salary`,`location`,`description`,`category`) VALUES ('$job->jobref','$job->title','$job->salary','$job->location','$job->description','$job->category')",$dbc);
echo "$job->jobref Added <br>";
}
?>
它显示:
120239811 Added
201909016 Added
202482907 Added
当我运行脚本时,它会解析 xml 文件,但实际上并没有插入数据
任何帮助都会很棒,因为我的时间非常紧迫 在此先感谢
** 在下面编辑 ** 下面的新代码
<?php
$startPage = 1;
$perPage = 3000;
$currentRecord = 0;
$xml = simplexml_load_file("urlhere");
$jobs = $xml->xpath("/jobs/job");
mysql_select_db($dbn,$dbc);
foreach ($jobs as $job)
{
$currentRecord += 1;
if($currentRecord > ($startPage * $perPage) && $currentRecord < ($startPage * $perPage + $perPage)){
$query = mysql_query("INSERT IGNORE INTO `listings` (jobref,title,url,salary,location,description,category) VALUES ('$job->jobref','$job->title','$job->url','$job->salary','$job->location','$job->description','$job->category')",$dbc);
if($query){
echo "$job->jobref Added <br>";
} else {
echo mysql_error();
}
}
}
?>
现在只是在 XML 文件中添加第一个条目
从查询中删除 IGNORE 并添加 在重复键更新 jobref =$job->jobref+1 还是一样的问题
【问题讨论】:
-
每次在新代码中使用the
mysql_数据库扩展a Kitten is strangled somewhere in the world 时,它都已被弃用,并且已经存在多年,并且在 PHP7 中永远消失了。如果您只是学习 PHP,请花精力学习PDO或mysqli数据库扩展和预处理语句。 Start here -
尝试像
if (! $query) { echo mysql_error(); }一样测试$query然后你可能会看到一些有用的东西 -
还将
mysql_select_db($dbn,$dbc);移到foreach循环之外,只需执行一次 -
upper cmets 是很好的陈述,您应该执行这些建议,还将这两件事放在您的脚本之上
error_reporting(E_ALL);和ini_set('display_errors', 1);这将为您提供有关脚本中发生的错误的更多详细信息 -
我刚刚修改了脚本并检查了 db & script 中的列数并且都匹配