单击按钮即可从数据库中获取行的id



我想这对这里的专家来说应该很容易。。。我正在使用wordpress,并从mysql数据库中获取图像,代码如下。我显示图像,每个图像都有一个按钮,我想要的是,当按下该按钮时,提取的数据库行的id就会打印在屏幕上。但下面的代码只显示最后一个id。

下面是我的代码。。。我希望在每次点击按钮时,我都能从数据库中获得特定的行id,并用回声在屏幕上打印

代码

$sql = "SELECT * FROM 1user";
$results = $wpdb->get_results($sql) or die(mysql_error());
foreach( $results as $result ) {
echo '<form action="" method="post">';
echo "<img src='$result->path' width='150' height='150' >" . '<br><br>'.'<input type="submit" name="show" id="show" value="Upvote"></form>';    
}
if(isset($_POST['show'])){
echo "<br>".$result->path;
}

WORKFLOW:我向图像添加了一个类和一个atribute。atribute是图像的id。当用户单击图像时,jquery使用attr()函数获取id,并找到与类id-img最接近的p,并显示idphp:替换此echo

echo "<img class="spimg" src='$result->path' width='150' data-id='$result->id' height='150' >" . '<br><br>'.'<input type="submit" name="show" id="show" value="Upvote"><p class='id-img'></p></form>'; 

jquery:

$('.spimg').on('click',function(){
   $id = $(this).attr('data-id');
  $(this).next('id-img').text($id);
});

或者,如果你想在表单中使用id,你可以使用隐藏输入:

$sql = "SELECT * FROM 1user";
$results = $wpdb->get_results($sql) or die(mysql_error());
foreach( $results as $result ) {
echo '<form action="" method="post">';
echo "<img src='$result->path' width='150' height='150' >" . '<br><br>'.'<input type="submit" name="show" id="show" value="Upvote"><input name='id' type='hidden' value='$result->path'/><input type='submit'/></form>";    
}

你可以像这样用$_POST['id'];获取id:

if(isset($_POST['id'])){
echo 'id of image = '.$_POST['id'];
}

最新更新