除非我刷新页面,否则数据不会插入数据库?

时间:2013-07-18 08:00:49

标签: php mysql ajax database

我有以下文件,这就是他们所做的:

input.php:从XML Feed中获取数据,连接并将其输入数据库。
output.php:连接数据库并创建要输出的变量。
index.php:包含output.php并使用变量输出数据。
refresh.js: Ajax刷新div以更新数据。


Input.php

$xml = simplexml_load_file( "http://domain.com/feed" );
$json = json_encode( $xml );
$array = json_decode( $json,TRUE );
$items = $array['channel']['item'];

$DB = new mysqli( 'localhost','USERNAME','PASSWORD','DATABASE' );
if( $DB->connect_errno ){
  print "failed to connect to DB: {$DB->connect_error}";
  exit( 1 );
}

$match = "#^(?:[^\?]*\?url=)(https?://)(?:m(?:obile)?\.)?(.*)$#ui";
$replace = '$1$2';

foreach( $items as $item ){
  $title = $item['title'];
  $url = preg_replace( $match,$replace,$item['link'] );
  $title_url[] = array( $title,$url );
  $sql_values[] = "('{$DB->real_escape_string( $title )}','{$DB->real_escape_string( $url )}')";
}
$SQL = "INSERT IGNORE INTO `read`(`title`,`url`) VALUES\n ".implode( "\n,",array_reverse( $sql_values ) );
if( $DB->query( $SQL ) ){
} else {
  print "failed to INSERT: [{$DB->errno}] {$DB->error}";
}
$DB->set_charset( 'utf8' );

Output.php

$DB = new mysqli( 'localhost','USERNAME','PASSWORD','DATABASE' );
if( $DB->connect_errno ){
  print "failed to connect to DB: {$DB->connect_error}";
  exit( 1 );
}

$query = "SELECT `title`,`url` FROM `read` ORDER BY `order` DESC";
$result = $DB->query( $query );
// error-handling: make sure query returned a result
if( $result ){
  while( $row = $result->fetch_array() ){
      // list gets values from a numeric array
      list( $title,$url ) = $row;
      // using [] (append) is much faster than using array_push()
      $data[] = array( 'title'=>$title,'url'=>$url );
}
$title = $data[0]['title'];
$url = $data[0]['url'];
}else{
  //do something
}

的index.php

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Recently</title>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  <script src="js/refresh.js"></script>
</head>

<body>
  <?php include_once "includes/output.php"; ?>

  <p class="title"><span>Read </span>
    <a  id="read" href="<?php echo $url; ?>" target="_blank"><?php echo $title; ?></a>  
  </p>

</body>
</html>

Refresh.js

var auto_refresh = setInterval(
 function() {
   $('#read').load('index.php #read');
 }, 2000);

问题在于,除非我刷新input.php(这会增加递增计数),否则数据不会插入到数据库中。我不知道为什么会这样。有什么想法吗?

注意:因为我刚刚开始了解有关PHP和数据库的更多信息,所以如果我的input.phpoutput.php代码最少,我希望需要

4 个答案:

答案 0 :(得分:2)

基本上您当前的工作流程是:执行input.php一次=&gt;使用JS在一个间隔中执行output.php以获得输出。所以你可以看到问题是输入是有点静态的,输出是动态的。

您可以单独修改您的刷新脚本:执行input.php =&gt;执行output.php =&gt;在第二次执行input.php之后再次=&gt;再次执行output.php,依此类推:

var auto_refresh = setInterval(function() {
    $.get('input.php', function () { // call input here
        $('#read').load('index.php #read'); // call output here
    });    
}, 2000); // run again after 2 seconds, you might wanna make this number higher to offload i/o

希望这有帮助。

答案 1 :(得分:1)

好吧,这是因为你曾经input.php 致电

您的index.php中没有任何地方再次调用它,因此调用了output.php,它会获取最新的行ORDER BY order DESC,然后$url = $data[0]['url']

必须再次致电input.php 才能获得新数据。

您可以将refresh.js更改为以下内容:

(function refresh() {
  $.get('input.php', function() {
    $("#read").load("index.php", function() {
      refresh();
    });
  });
})(); // self-executing anonymous functions are better than setInterval() to handle ajax

答案 2 :(得分:0)

也许您的请求正在缓存中。试着改变:

   $('#read').load('index.php?r='+ Math.floor((Math.random()*100)+1) +' #read');

答案 3 :(得分:0)

将input.php和output.php合并到一个文件中(例如io.php)。

// input.php content
// output.php content
// And instead of creating $title and $url variables use this

header('Content-type: application/json');
echo json_encode($data[0]);

不再需要在index.php中包含任何文件,只需编辑 refresh.js ,如下所示

setInterval(function(){ $.ajax({
  url: 'io.php',
  type: 'GET',
  dataType: 'json',
  cache: false,
  success: function(m){
    $('#read').text(m.title).attr('href',m.url);
  }
}); }, 2000);

也无需重新加载index.php。我认为这是更有效的方式

编辑:这是完整的代码。

可能有另外的代码块需要在index.php中包含output.php或者与我的方法冲突的东西。我不知道有关您系统的这种其他信息。这只是一个建议。

io.php

(input.php + output.php)我不知道在组合这些文件时仍需要保存数据库,但您可以在另一页中使用这些保存的数据。 < / p>

$xml = simplexml_load_file( "http://domain.com/feed" );
$json = json_encode( $xml );
$array = json_decode( $json,TRUE );
$items = $array['channel']['item'];

$DB = new mysqli( 'localhost','USERNAME','PASSWORD','DATABASE' );
if( $DB->connect_errno ){
  print "failed to connect to DB: {$DB->connect_error}";
  exit( 1 );
}

$match = "#^(?:[^\?]*\?url=)(https?://)(?:m(?:obile)?\.)?(.*)$#ui";
$replace = '$1$2';

foreach( $items as $item ){
  $title = $item['title'];
  $url = preg_replace( $match,$replace,$item['link'] );
  $title_url[] = array( $title,$url );
  $sql_values[] = "('{$DB->real_escape_string( $title )}','{$DB->real_escape_string( $url )}')";
}
$SQL = "INSERT IGNORE INTO `read`(`title`,`url`) VALUES\n ".implode( "\n,",array_reverse( $sql_values ) );
if( $DB->query( $SQL ) ){
} else {
  print "failed to INSERT: [{$DB->errno}] {$DB->error}";
}
$DB->set_charset( 'utf8' );

$query = "SELECT `title`,`url` FROM `read` ORDER BY `order` DESC";
$result = $DB->query( $query );
// error-handling: make sure query returned a result
if( $result ){
  while( $row = $result->fetch_array() ){
      // list gets values from a numeric array
      list( $title,$url ) = $row;
      // using [] (append) is much faster than using array_push()
      $data[] = array( 'title'=>$title,'url'=>$url );
}

header('Content-type: application/json');
echo json_encode($data[0]);

}else{
  //do something
}

的index.php

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Recently</title>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  <script src="js/refresh.js"></script>
</head>

<body>

  <p class="title"><span>Read </span>
    <a  id="read" href="" target="_blank"></a>  
  </p>

</body>
</html>

refresh.js

setInterval(function(){ $.ajax({
  url: 'io.php',
  type: 'GET',
  dataType: 'json',
  cache: false,
  success: function(m){
    $('#read').text(m.title).attr('href',m.url);
  }
}); }, 2000);