Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8332901
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T02:51:14+00:00 2026-06-09T02:51:14+00:00

I am using a PHP array to gather user input that has been added

  • 0

I am using a PHP array to gather user input that has been added to my MySQL database. As this is information from user input I am using a variable created by the num_rows in my database to determine the number of times a for loop runs through displaying my array values. The for loop contains a form that displays one value of the array, and a “like” button (type=submit), and repeats this form until all values have been displayed (from newest to oldest), with a “like” button following each.

I want users to be able to click the “like” button, to add a “like” to that post. The problem I’ve run into is that the code I have is adding a “like” to every post (because the code checks to see if the “like” button has been pressed, and since the “like” button was created by the for loop, every “like” button has the same name). I’ve tried to rectify this by giving the “like” button a name based on an incremented variable, but the button does not seem to work if the name is a variable or an array.

Here is my code:

<?php
error_reporting (E_ALL ^ E_NOTICE);

session_start();
$userid = $_SESSION['userid'];
$username = $_SESSION['username'];
$userside = $_SESSION['side'];

echo "<b>Organized posts:</br><hr /></b>";

require("./postconnect.php");

$query = mysql_query("SELECT * FROM original ORDER BY postid ASC");
$numrows = mysql_num_rows($query);

$numrows = $numrows-1;

$sql = "SELECT postername FROM original ORDER BY postid ASC"; // select only the postername field from the table "original"
$result = mysql_query($sql); // process the query

$name_array = array(); // start an array

while($row = mysql_fetch_array($result)){ // cycle through each record returned
  $name_array[] = "".$row['postername'].""; // get the postername field and add to the array above
}

$sql = "SELECT post FROM original ORDER BY postid ASC"; // select only the post field from the table "original"
$result = mysql_query($sql); // process the query

$post_array = array(); // start an array

while($row = mysql_fetch_array($result)){ // cycle through each record returned
  $post_array[] = "".$row['post'].""; // get the post field and add to the array above
}

$sql = "SELECT posterside FROM original ORDER BY postid ASC"; // select only the posterside field from the table "original"
$result = mysql_query($sql); // process the query

$side_array = array(); // start an array

while($row = mysql_fetch_array($result)){ // cycle through each record returned
  $side_array[] = "".$row['posterside'].""; // get the posterside field and add to the array above
}

$sql = "SELECT likes FROM original ORDER BY postid ASC"; // select only the likes field from the table "original"
$result = mysql_query($sql); // process the query

$likes_array = array(); // start an array

while($row = mysql_fetch_array($result)){ // cycle through each record returned
  $likes_array[] = "".$row['likes'].""; // get the likes field and add to the array above
}

$i=$numrows;

for($i;$i>=0;$i--) {

    if ($side_array[$i]==1) {
        $color="red";
    }
    elseif ($side_array[$i]==2) {
        $color="blue";  
    }
    elseif ($side_array[$i]==3) {
        $color="green"; 
    }

    echo "<form action='./memberhag.php' method='post'>
            <table>
            <tr>
              <td><font color='$color'>$name_array[$i]</font> - $post_array[$i]</td>
        </tr>
        <tr>
          <td><input type='submit' name='likebtn' value='Like' /> <font color=$color>$name_array[$i]</font> has $likes_array[$i] likes!</td>
        </tr>
        </table>
        </form>";

    if ($_POST['likebtn']) {

            $numlikes = $likes_array[$i];
        $numlikes = $numlikes + 1;      
        mysql_query("UPDATE original SET likes = '$numlikes' WHERE postername = '$name_array[$i]'");


    }
}

?>

This has had me stumped for quite a while… I’ve even tried using a while loop instead of a for loop.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T02:51:16+00:00Added an answer on June 9, 2026 at 2:51 am

    Having lots of forms to do this is one possible solution, but I’d be inclined to have just one form, and several buttons. The primary problem seems to be that, as you say, you’ve called the buttons the same thing, which means you have no way to determine which one has been pressed.

    A very basic fix is to do this:

    <input type='submit' name='likebtn_{$i}' value='Like' />
    

    That will at least give you an ordinal number you can use to differentiate between buttons. However it is probably better for you to loop through your posts in this loop, so you can do this (assuming you have a primary key called id in this table:

    <input type='submit' name='likebtn_{$post['id']}' value='Like' />
    

    Ah yes, and when you fix your POST section (i.e. the bit when someone pushes a ‘like’ button) you’ll need to read what’s in $_POST and parse out what’s been pushed. To help debug this, temporarily add this into your post handler:

    print_r($_POST); exit();
    

    That will give you the output you need to decode (check that it is different for each post like). You’ll also need to change your if statement to detect posts; change this:

    if ($_POST['likebtn']) {
    

    to:

    if ($_POST) {
    

    This is necessary as you now don’t have a single name to detect, so we just now detect whether the array $_POST contains anything (if it does, we know this is a post operation). Inside this, put the print_r() above, to see what’s inside it.

    Now, here are some things you can do to improve your code:

    • It isn’t clear what the table original does, so I’d probably rename that.
    • You seem to have several queries from this table, when you’ve already done SELECT * FROM original – so there are too many queries here
    • Bear in mind that in a system like this, you’ll probably need other tables, such as who has done the “like” (maybe called user)
    • Rather than the for loop, switch that to a while loop over your posts table.
    • Try not to put large blocks of HTML in echo "x" statements, as it gets difficult to debug after a while. It is probably better to break out of PHP mode, and use simple loops and variable outputs in HTML mode.

    Edit, in response to your comment:

    Ok, I did the if ($_POST) { print_r } and got Array ( [likebtn_4] => Like ) for one of the posts. 🙂 – Jeremy

    Great! OK, try something like this:

    if ($_POST) {
        $find = 'likebtn_';
        foreach ($_POST as $key => $value) {
            $likeKey = (int) str_replace($key, $find, '');
            if ($likeKey) {
                // If this runs, do your update against row $likeKey
                // Note that I've forced it to be an int, to avoid security issues
            }
        }
    }
    

    Above all, try to understand why this works. Do some reading around it if necessary. I’ve essentially looped through the associative array of the post operation, and tested each key (i.e. element name) to see if it contains the string “likebtn_”. If it does, I convert the remainder to an integer, which you can then use in an UPDATE statement.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

using PHP and MySQL i have grabbed an array of facebook user ids from
I am using PHP and I have an array of user images that I
I want to create an array using PHP that can be used in MySQL.
How do I convert SOAP response like this to php array using SimpleXML? <?xml
So we all know that when iterating through a PHP array using foreach, the
how to insert inner array in mongodb using php I run this command in
PROBLEM I have a nested PHP array that I need to populate from flat
I'm trying to search through this Json array using PHP: {count:2,items:{milestone:[{id:3107,username:TomSmith1,userid:1620602,date:2012-01-12 16:49:26,projectid:804,projectname:TEST PROJECT,reason:Partial payment
This tutorial here is a good source of generating kml from the database using
I created a array using PHP $userarray = array('UserName'=>$username,'UserId'=>$userId,'UserPicURL'=>$userPicURL); How can I convert this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.