i have a page template assigned to a page, that displays the images of all the posttype=suspense...but how do i get voting button on each of the image so that ppl can vote on each image and restrict it to voting per ip.

i have a custom field called count that i want to store the votes to and updatenext to image immediately...just cant seem to get it to work

here's my code

 <?php
    /**
     * Template Name:  suspense Gallery
     *
     * Description: Creates a gallery of featured images from a custom post type
     *
     * @package WordPress
     * @subpackage 
     * @since 2014
     */
    ?>
    <script>
function myvote($pid,$tempcount) {
    $sql = "UPDATE `count` SET count = '$tempcount' WHERE post_id = $pid";
$query = mysql_query($sql);
}
</script>


    <?php 
    // Query the custom post type to display
        $args = array('post_type' => 'suspense');
        $query = new WP_Query( $args );
        while ( $query->have_posts() ) : 
                $query->the_post();
                    if ( has_post_thumbnail() ): 
    ?>
        <div><?php the_post_thumbnail('thumbnail'); ?><button onclick="myvote($post->ID,$newcount)">Vote</button><?php echo get_field('count');?></div>

    <?php endif; endwhile; ?>
Member Avatar for diafol

I'm not familiar with the package, so bear with me.

If you want to log the IP Address, then you need to store that in a table, e.g.

votes

image_id
ip_address

Where the two fields make a composite primary key (no duplicates allowed)

So to count votes on an image you'd need to make a COUNT query on image_id. However, this may get ridiculous if you've got millions of votes, so you could "cheat" with a non-normalized field for each image:

images

id
....
votes

So when you vote, you log an entry into the votes table and increment votes against the votes field in the images table. Non-normalized fields are usually a no-no, but can save substantial retrieval time. My 2p.

You can probably use an ajax to call for another php to store the data instead of using the code $query = mysql_query($sql); in the <script> tag as this code will not having anything to do with the php function mysql_query();

@lps...how do i use ajax? i have no idea ...can u plz help

Create an ajax.php with codes similar

<?php
//connect to your db
    $sql = "UPDATE `count` SET count = $_POST['tempcount'] WHERE post_id = $_POST['pid']";
    $query = mysql_query($sql);
    echo "success";
?>

remember to cater the not success scenario in ajax.php

and then modify the script into

function myvote($pid,$tempcount) {
    $.ajax({
        type: "POST",
        url: "ajax.php",
        data: {pid:$pid,tempcount:$tempcount},
        cache: false,
        success: function(html){
            $("body").append(html);
        }
    });
};

do i put the ajax.php inside the theme folder of wordpress? i created the ajax.php as u said and put it in the theme folder of wordpress but on clicking the btn nothing happens

if put inside the theme folder then the url you need to change to <?php bloginfo('template_directory'); ?>/ajax.php

nope not working...its not updating in the database...neither is the updated count immediately displayed next to buttn...posted the code below

this is my code now

page template :-

<?php
/**
 * Template Name:  suspense Gallery
 *
 * Description: Creates a gallery of featured images from a custom post type
 *
 * @package WordPress
 * @subpackage 
 * @since 2014
 */
?>
<script language="Java Script" type="text/javascript">
function myvote($pid,$tempcount) {
    $.ajax({
        type: "POST",
        url: "<?php bloginfo('template_directory'); ?>/vajax.php",
        data: {pid:$pid,tempcount:$tempcount},
        cache: false,
        success: function(html){
            $("body").append(html);
        }
    });
};
</script>

<?php 
// Query the custom post type to display
    $args = array('post_type' => 'suspense');
    $query = new WP_Query( $args );
    while ( $query->have_posts() ) : 
            $query->the_post();
                if ( has_post_thumbnail() ): 
            $oldcount=get_field('count');
            $newcount=$oldcount++;
?>
    <div><?php the_post_thumbnail('thumbnail'); ?><button onclick="myvote($postid,$newcount)">Vote</button><?php echo get_field('count');?></div>

<?php endif; endwhile; ?>

and my vajax.php is

<?php
//connect to your db
    $sql = "UPDATE `count` SET count = $_POST['tempcount'] WHERE post_id = $_POST['pid']";
    $query = mysql_query($sql);
    echo "success";
?>

please do not simply copy, understand the ajax.php and connect your own database....

how to do that? sorry i m newbie

i updated the code to

<?php
//connect to your db
$servername = "localhost";
$username = "admin";
$password = "admin";
$dbname = "mydb";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

    $sql = "UPDATE `count` SET count = $_POST['tempcount'] WHERE post_id = $_POST['pid']";
    if (mysqli_query($conn, $sql)){
    echo "success";
    }

$conn->close();
?>

still not working

Member Avatar for diafol

Erk! Don't do that! You've just opened yourself up to SQL injection by placing the raw input into your sql. Always sanitize your inoput or better still use prepared statements and bind your values/params.

I know the following is not exactly as you have it, but I'll spell it out simply. This is assuming a non-normalized field 'votes' (or 'count' in your case).

When you receive a vote on an image (or a post):

voting.php

$ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);
$image_id = filter_var($_POST['image_id'], FILTER_VALIDATION_INT);

if($ip && $image_id)
{
    //Do rest of code in here
}else{
    //Naughty! image_id not an integer or messed up IP address
}

Note I've used POST here as we're going to manipulate the data in the DB (insert and/or update). I'm using PDO here to manipulate the DB - assume that connection already made and new PDO object is $db.

So in the body of the conditional statement (if) above...

$q = "INSERT INTO votes (`ip_address`, `image_id`) VALUES (?, ?)";
$stmt = $db->prepare($q);
$stmt->execute(array($ip, $image_id));
if($stmt->rowCount())
{
   $q = "UPDATE `images` SET `votes` = `votes` + 1 WHERE image_id = ?";
   $stmt = $db->prepare($q);
   $stmt->execute(array($image_id));
   if($stmt->rowCount())
   {
       //successful update - maybe return vote count to Ajax?
       echo 1;
   }else{
       //couldn't update for some reason
   }
}else{
    //already voted
}

If you're ajaxing (recommended), then the return value (1) will sereve to increment the number of votes in the page. Also it will serve to hide the upvote button/link whatever from further attemnpts to upvote. If the return value is anything other than 1, then do not increment on the page nor should you hide the button/link. Just a few quick ideas.

so this is what my code should be...plz check

plz note count is a custom field created via ACF

pagetemplate.php

<?php
/**
 * Template Name:  suspense Gallery
 *
 * Description: Creates a gallery of featured images from a custom post type
 *
 * @package WordPress
 * @subpackage 
 * @since 2014
 */
?>


<?php 
// Query the custom post type to display
    $args = array('post_type' => 'suspense');
    $query = new WP_Query( $args );
    while ( $query->have_posts() ) : 
            $query->the_post();
                if ( has_post_thumbnail() ): 
            $oldcount=get_field('count');
            $newcount=$oldcount+1;
?>


  <div><?php the_post_thumbnail('thumbnail'); ?><button onclick="myvote($post_id,$newcount)">Vote</button><?php echo get_field('count');?></div>

<?php endif; endwhile; ?>

<script language="Java Script" type="text/javascript">
function myvote($pid,$tempcount) {
    $.ajax({
        type: "POST",
        url: "<?php bloginfo('template_directory'); ?>/voting.php",
        data: {pid:$pid,tempcount:$tempcount},
        cache: false,
        success: function(html){
            $("body").append(html);
        }
    });
};
</script>

voting.php

<?php
$ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);
$post_id = filter_var($_POST['post_id'], FILTER_VALIDATION_INT);
if($ip && $post_id)
{
    $q = "INSERT INTO count (`ip_address`, `post_id`) VALUES ($ip, $post_id)";
$stmt = $db->prepare($q);
$stmt->execute(array($ip, $post_id));
if($stmt->rowCount())
{
   $q = "UPDATE `wp_posts` SET `count` = `count` + 1 WHERE post_id = ?";
   $stmt = $db->prepare($q);
   $stmt->execute(array($post_id));
   if($stmt->rowCount())
   {
       //successful update - maybe return vote count to Ajax?
       echo 1;
   }else{
       echo "couldn't update";
   }
}else{
    echo "already voted";
}
}else{
    //Naughty! post_id not an integer or messed up IP address
}
?>
Member Avatar for diafol

so this is what my code should be...plz check

That's up to you to check. Use it, see if it works, if not, try to fix it, if you can't, come back.

with the modifications i made code still doesn't work...the custom field doesn't update

ok i cchanged the voting.php to work without ip thing simple increase count and update on page

<?php
$tempcount = filter_var($_POST['tempcount'], FILTER_VALIDATION_INT);
$post_id = filter_var($_POST['pid'], FILTER_VALIDATION_INT);

   $q = "UPDATE `wp_posts` SET `count` = $tempcount WHERE post_id = $pid";
   $stmt = $db->prepare($q);
   $stmt->execute(array($pid));
   if($stmt->rowCount())
   {
       //successful update - maybe return vote count to Ajax?
       echo 1;
   }else{
       echo "couldn't update";
   }

?>

still doesn't work

Member Avatar for diafol

WHy are you using this $tempcount? Surely you just want to increment the count field? It won't work because you're not binding your parameters properly:

$q = "UPDATE `wp_posts` SET `count` = ? WHERE post_id = ?";
$stmt = $db->prepare($q);
$stmt->execute(array($tempcount, $pid));

Is $db being created properly before this code? E.g.

$db = new PDO(....);

its with wordpress ...the db is already there. i m trying to update the custom field that was created via advanced custom field plugin for the posttype.

i passing the newcount to the function myvote hence tempcount is actually the incremented count.

Member Avatar for diafol

Seems like a lot of unnecessary messinf about to me. Ok so what isn.t working? Use mysql errors to tell uou what.s wrong

ok i did it in simple php i got the buttnons working but for some reason i click on vote btn for image 3 first time then count for image 4 increments , but second time count for image 3 increases. like wise if i click for btn for image 2 then on first time click ,count of image3 increases on 2nd click count of image 2 increase

how do i get it increase the correct count the first time itself

u can see it live at http://myproject.byethost7.com/?page_id=5

my code is

<?php
 $args = array('post_type' => 'suspense');
 $query = new WP_Query( $args );
 while ( $query->have_posts() ) {
     $query->the_post();
     if ( has_post_thumbnail() ) {
         $postid = get_the_ID();
         $votecount = get_field('count');
 ?>
         <form action="" method="POST">
             <div>
         <?php echo the_title()."<br>"; ?>    
             <?php the_post_thumbnail('thumbnail'); ?>
             <input type="hidden" value="<?php echo $postid; ?>" name="id" />
             <input type="submit" name="submit" value="Vote" />
             <?php echo $votecount; ?>
             </div>
         </form>
<?php
    } //close endif
} // close while

 if (isset($_POST['submit'])) { 
     $id = $_POST['id'];     
     $votecount = get_field('count',$id);   
     $newcount = $votecount+1;
     update_field('field_5504',$newcount,$id); 
 }

?>
Member Avatar for diafol

ok i did it in simple php i got the buttnons working but for some reason i click on vote btn for image 3 first time then count for image 4 increments , but second time count for image 3 increases. like wise if i click for btn for image 2 then on first time click ,count of image3 increases on 2nd click count of image 2 increase

I'm sorry - very sorry - but that makes no sense to me at all.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.