skip to Main Content

I have data in my PHPMYADMIN in a few columns and rows.

Via PHP I read the Data out of my SQL Table and print it into a table.

The last of my table is a action button. So the whole table is a echo and within the table there’s a html form in the last , but only with a submit button (input type=”hidden”) but the value should be the “id” out of my SQL table.

Here’s the problem. How can I get the id of one row into the value of an input field? . $row[“id”]. doesn’t work. How can I fix this problem?

This is for a Website where the user can vote a table row up and then with the html form it is sending via http post to another page where it overrides the current number in the database with +1

$sql = "SELECT * FROM votingpoll ORDER BY votecount DESC";
$result = $conn->query($sql);

echo "$id";

echo "<table>";
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<tr>
                <td> 
                    <form action='vote.php' method='post'>
                        <input type='text' name='id' value='$id'> 
                        <input type='submit' value='VOTE'> 
                    </form>
                </td>
            </tr>";
    }
} else {
    echo "0 results";
}

Thank you!!!

2

Answers


  1. You can do $row[id] i.e. leave the quotes off when the array reference is used inside a double quoted string.

    $sql = "SELECT * FROM votingpoll ORDER BY votecount DESC";
    $result = $conn->query($sql);
    
    // remove this it does not appear to do anything useful here
    //echo "$id";
    
    echo "<table>";
    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            echo "<tr>
                    <td> 
                        <form action='vote.php' method='post'>
                            <input type='text' name='id' value='$row[id]'> 
                            <input type='submit' value='VOTE'> 
                        </form>
                    </td>
                </tr>";
        }
    } else {
        echo "0 results";
    }
    

    Or if you prefer you could use

    <input type='text' name='id' value='{$row['id']}'> 
    
    Login or Signup to reply.
  2. It looks like you aren’t setting $id anywhere. Try setting it from the results like $id = $row["id"];

    Full example:

    while($row = $result->fetch_assoc()) {
        $id = $row["id"];
        echo "<tr>
                <td> 
                    <form action='vote.php' method='post'>
                        <input type='text' name='id' value='$id'> 
                        <input type='submit' value='VOTE'> 
                    </form>
                </td>
            </tr>";
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search