PHP, MySQL, Drupal, .htaccess, Robots.txt, Phponwebsites: mysql_fetch_assoc in php and mysql

24 Mar 2014

mysql_fetch_assoc in php and mysql

                       Mysql_fetch_assoc() return row as an associative array. Here, we can use numeric indices to get values from mysql data using php.

Consider following example:

                     mysql_fetch_assoc in php and mysql at phponwebsites

Retrieve data from table using mysql_fetch_assoc() in php:

                       You can retrieve data from mysql table using mysql_fetch_assoc() in php. The following php script is used for retrieve data.

<html>
<body>
<table>
<th>Game_ID</th><th>Category</th><th>Title</th>
<?
        php mysql_connect('localhost','root','') or die(mysql_error());
        mysql_select_db('new') or die(mysql_error());
        $query=mysql_query('select * from table1') or die(mysql_error());
        while($res=mysql_fetch_assoc($query))
         {
             echo'<tr><td>'.$res['game_ID'].'</td><td>'.$res['category_Name'].'</td><td>'.$res['game_Title'].'</td></tr>';
         }
        echo'<table>';
 ?>
 </body>
</html>


           Now you'll get output like this:

mysql_fetch_assoc in php


Where,
            the result of array should be like this:
     Array(
                  [game_ID] => 1
                  [category_Name] => Adventures
                  [game_Title] => Achilles
               )

 Suppose you'll use
echo'<tr><td>'.$res[0].'</td><td>'.$res['category_Name'].'</td><td>'.$res['game_Title'].'</td></tr>';

That means you use numeric index instead associative, then you will get undefined offset error like as follows as:

mysql_fetch_assoc at phponwebsites

Where,
              $res[0] represents the first column of mysql table. But you can't use this to retrieve data from table. Because you used mysql_fetch_assoc() mysql function to retrieve data.

Related Post:

No comments:

Post a Comment