Reputation: 321
I guess this should be easy for the experts here ... I am using wordpress and I am fetching images from the mysql database with below code. And I display the image and there is a button just with every image and what I want is that when that button is pressed the id of that row of database that is fetched is printed on the screen. But below code only shows the last id.
Below is my code ... I want that on each button click I get that particular row id from database and print on screen with echo
Code
$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;
}
Upvotes: 2
Views: 4663
Reputation: 32354
WORKFLOW: I add a class and a atribute to the image the atribute is the id of the image when the user clicks the image the jquery takes the id using the attr()
function and finds the closest p
with the class id-img
and displays the id
php: replace this 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);
});
or if you want to use the id in a form you can use a hidden input:
$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>";
}
you can fetch id with $_POST['id'];
like this:
if(isset($_POST['id'])){
echo 'id of image = '.$_POST['id'];
}
Upvotes: 1