我正在写我自己的简单博客。到目前为止,我只剩下一个非常恼人的bug了。如果我的数据库中有4行数据,前2行(ID最低)将不会显示。因此,如果我添加一个新的第三行,只有第一行将弹出我的屏幕,它将采取2个新的帖子之前,第三行将显示。如果我转过ID的顺序,如果我的数据库中有2个无用的帖子,它就会起作用。当然,我希望更高的id显示在顶部。
下面是将数据库信息显示在屏幕上的代码:
<?php
require('config.inc.php');
require('template.inc.php');
require('functions.inc.php');
include_once('insert.php');
$query="SELECT * FROM blog ORDER BY ID DESC";
$result=mysql_query($query);
$db_field = mysql_fetch_assoc( $result );
mysql_fetch_assoc( $result );
mysql_close();
htmlOpenen('ServerSideBlog');
while ($db_field = mysql_fetch_assoc($result) ) {
echo'
<span class="post">
<h1>'.$db_field['title'].'</h1>
<h2>'.$db_field['date'].'</h2>
<p>'.$db_field['contents'].'</p>
<h3>Hoogachtend, Sincerely, Aufrichtig, sinceramente,</h3>
<h4>'.$db_field['author'].'</h4>
';
}
htmlSluiten();
?>下面是在数据库中添加帖子的代码:
<?php
$db_host = "db.jxxxxx.com";
$db_username = "md2xxxx230";
$db_pass = "J9xxxx58";
$db_name = "md2xxxxx230";
@mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
@mysql_select_db("$db_name") or die ("no database");
if ($_POST['parse_var'] == "new"){
$title=$_POST['title'];
$contents=$_POST['contents'];
$author=$_POST['author'];
$date=$_POST['date'];
$date = strftime("%b %d, %y", strtotime($date));
$sqlcreate = mysql_query("INSERT INTO blog (date, title, contents, author)
VALUES(now(),'$title','$contents','$author')");
}
?>我找不到任何解决这个问题的办法。希望我能在这里得到一些awnsers :)
发布于 2013-01-31 19:55:59
为什么你要把这个放在while循环之前?
$db_field = mysql_fetch_assoc( $result );
mysql_fetch_assoc( $result );
mysql_close(); 其次,您在关闭mysql连接之前-
while ($db_field = mysql_fetch_assoc($result)发布于 2013-01-31 19:57:19
您在三个地方调用mysql_fetch_assoc。在进入while循环之前执行两次。这两次返回前两行。因此,当您进入while循环时,您从第3行开始。因为显示帖子的代码在while循环中,所以很明显,它不会显示前两个帖子。
删除行
$db_field = mysql_fetch_assoc( $result );和
mysql_fetch_assoc( $result );然后移动
mysql_close();在你的while循环之后,它很可能会做你想做的事情。
Sidenote:
将数据添加到数据库的方式是非常不安全的。这行
$sqlcreate = mysql_query("INSERT INTO blog (date, title, contents, author)
VALUES(now(),'$title','$contents','$author')");加上没有过滤插入的数据,这表明它非常容易受到注入攻击。可以执行任意SQL代码和Javascript。
给你的一些信息:
https://stackoverflow.com/questions/14625094
复制相似问题