TripleS Academy
TripleS Academy

Reputation: 31

index of fetch array

i want to get the index of td that the user clicked , i have an html table fill from database using php ...

this is my index.php :

<html>
<head>
    <title>Last 10 Results</title>
</head>
<body>
    <table>
    <thead>

    </thead>
    <tbody>
    <tr>
    <?php
        session_start();
        $connect = mysqli_connect("localhost","root","","test");
        if (!$connect) {
            die(mysql_error());
        }
        $results = mysqli_query($connect,"SELECT * FROM family where parent_id = 0");
        while($row = mysqli_fetch_assoc($results)) {    
        ?>
            <td onclick="window.location='index2.php'"
            <?php  $id = $row['id'];
            $_SESSION['varname'] = $id;?>>
            <?php echo $row['name']?> <br/>
            <?php echo $row['description']?> <br/>
            <?php echo $row['parent_id']?> <br/>
            </td>
        <?php
        }
        ?>
        </tr>
        </tbody>
        </table>
</body>
</html>

this is my index2.php :

<html>
<head>
    <title>Last 10 Results</title>
</head>
<body>
    <table>
    <thead>

    </thead>
    <tbody>
    <tr>
    <?php
        session_start();
        $gg = $_SESSION['varname'];
        echo $gg;
        $connect = mysqli_connect("localhost","root", "","test");
        if (!$connect) {
            die(mysql_error());
        }
        $results = mysqli_query($connect,"SELECT * FROM family where parent_id = '$gg' ");
        while($row = mysqli_fetch_array($results)) {
        ?>
                <td>
                <?php echo $row['id']?> <br/>
                <?php echo $row['name']?> <br/>
                <?php echo $row['description']?> <br/>
                <?php echo $row['parent_id']?> <br/>
                </td>
        <?php
        }
        ?>
        </tr>
        </tbody>
        </table>
</body>
</html>

now i want to take the "id" of the td that the user click on,, but this code always give me the last id in my database ...

what can i do ?

Upvotes: 1

Views: 37

Answers (1)

webservices
webservices

Reputation: 465

Replace in Index.php:

<td onclick="window.location='index2.php'"

With:

<td onclick="window.location='index2.php?parent_id=<?php echo $row['id']; ?>'"

And in Index2.php:

$gg = $_SESSION['varname'];

With:

$gg = (int)$_GET['parent_id'];

It's better to use $_GET variable for this than $_session (urls are search engine friendly)

Upvotes: 1

Related Questions