Search code examples
phpjquerymysql-num-rows

Using mysqli_num_rows with while loop and onclick event


I want to echo number of rows(suppose numer of rows= 3).if the user clicks on the number(I am passing 1 parrameter from while loop),then data is alerted But the problem is that

  1. if I echo numrows inside while loop then all rows(related 3 rows data ) are alerted on onclick event,but numrows are shown 3 times like 333.
  2. If I echo outside of while loop,then num rows are show one time but Only one result is passed to the function.

I also used count(col),but this way only one result is retrieved.

Any solution to show the number of rows one time but passing all the results of $uid(which is in while loop) to onclick function?.Plz help.

  $sql=mysqli_query($this->db->connection,"SELECT * from user_data where  scid='$scid'");
            $num=mysqli_num_rows($sql);

            while($row=mysqli_fetch_array($sql)){
                $uid=$row['uid'];



                ?>


            <span onclick=o4_sameby_scid(<?php echo $uid;  ?>)><?php echo  $num  ?></span>



            <script type="text/javascript">

                function o4_sameby_scid(o4_id) {
                    alert(o4_id);
                }


            </script>



            <?php
            }

Solution

  • I think your problem is that you are nesting the wrong parts of your code inside of your while loop. What about this approach?:

    <?php
    $sql=mysqli_query($this->db->connection,"SELECT * from user_data where  scid='$scid'");
    $num=mysqli_num_rows($sql);
    
    $allvalues = array();
    
    //  Do all looping before any echoing
    while($row=mysqli_fetch_array($sql)){
        // add this row's value to an array of all values
        $allvalues[] = $uid=$row['uid'];
    }
    
    // implode this array
    $valuesascsv = implode(', ', $allvalues);
    
    
    //  This is echo'd outside of the loop, because we only need to see it one time
    echo '<span onclick=o4_sameby_scid("'. $valuesascsv .'")>'. $num .' results found! </span>';
    ?>
    
    <script type="text/javascript">
        function o4_sameby_scid(o4_id) {
            alert(o4_id);
        }
    </script>
    

    This should output:

    <span onclick=o4_sameby_scid("uid#1, uid#2, uid#3")>3 results found!</span>
    
    <script type="text/javascript">
        function o4_sameby_scid(o4_id) {
            alert(o4_id);
        }
    </script>
    

    Clicking on any of the row count should alert all of the UIDs.

    Is this the behavior you were looking for?