是否为PHP生成的div创建唯一标识符?
不确定实现这一点的最佳方法,但本质上我使用PHP从一个SQL POST数据库中提取,在for循环中执行。这是我目前的代码:是否为PHP生成的div创建唯一标识符?,php,jquery,html,mysql,Php,Jquery,Html,Mysql,不确定实现这一点的最佳方法,但本质上我使用PHP从一个SQL POST数据库中提取,在for循环中执行。这是我目前的代码: $sql = "SELECT *FROM $tbl_name"; $lastPostID = mysql_num_rows(mysql_query($sql))-1; //CREATE BLOG POSTS for ($currPostID = $lastPostID; $currPostID >= 0; $currPostID--){ $sqlQue
$sql = "SELECT *FROM $tbl_name";
$lastPostID = mysql_num_rows(mysql_query($sql))-1;
//CREATE BLOG POSTS
for ($currPostID = $lastPostID; $currPostID >= 0; $currPostID--){
$sqlQuery = "SELECT title, content FROM $tbl_name WHERE postID = '$currPostID'";
$title = mysql_fetch_array(mysql_query($sqlQuery))['title'];
$content = mysql_fetch_array(mysql_query($sqlQuery))['content'];
echo '<div class = "row">';
echo '<div class = "col-md-12">';
echo '<h4 class = "widget-title">' .$title. '</h4>';
echo '<p>' .nl2br($content). '</p>';
echo '<hr class = "blogborder">';
echo '</div>';
echo '</div>';
}
$sql=“从$tbl\u name中选择*;
$lastPostID=mysql\u num\u行(mysql\u查询($sql))-1;
//创建博客帖子
对于($currPostID=$lastPostID;$currPostID>=0;$currPostID--){
$sqlQuery=“从$tbl\u name中选择标题、内容,其中postID='$currPostID';
$title=mysql_fetch_数组(mysql_query($sqlQuery))['title'];
$content=mysql_fetch_数组(mysql_query($sqlQuery))['content'];
回声';
回声';
回显“.$title.”;
回音“”.nl2br($content)。“”;
echo'
;
回声';
回声';
}
如您所见,我将SQL数据库中的每个条目放入页面上自己的div容器中。然而,我也在想,将来我会为这些帖子创建一个“编辑”功能,这要求我能够在我的SQL数据库中唯一地标识帖子
现在,我正在考虑添加一个额外的div容器来单独存储每个post的postID(它是SQL中的主键)。因此,在for循环中,将有一个额外的行:
echo '<div class = "idNum">' .$postID. '</div>';
echo'.$posted';
然后使用jQuery使用this.val()获取ID值,这将允许我运行AJAX查询编辑文章
然而,我觉得有一种更好、更干净的方法可以做到这一点,我想知道你们是否都有任何意见?不需要额外的元素。在每个重复模块上使用
data-
属性
使用jQuery data()方法可以轻松读取这些数据
您可以使用一个随机字符串作为
id
的名称。顺便说一句,停止使用不推荐的mysql.*
函数;改用PDO/MySQLi。
echo '<div class = "row" data-id="' .$postID. '">';
$('.widget-title').click(function(){
alert( $(this).closest('.row').data('id') );
});