FantanSquad
FantanSquad

Reputation: 31

How to make echo results in table hyperlinks

I have retrieved data from DB and inserted into a html table however I want to make each value in the table a hyperlink to another page. Below I have tried making the pupil_id and link to a profile.php but all pupil_id values have now vanished!

(if (!isset($_POST['search'])) {
                    $pupils = mysql_query("SELECT * FROM pupil") or die("Cant find         Pupils");
                    $count = mysql_num_rows($pupils);
                    if ($count == 0) {
                        $totalpupil = "There are currently no Pupils in the system.";
                    } else {
                        while ($row = mysql_fetch_array($pupils)) {
                            ?>
                            <tr>
                                <td><?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?></td>
                                <td><?php echo $row['pupil_name'] ?></td>
                                <td><?php echo $row['class_id'] ?></td>                        
                            </tr>
                            <?php
                        }
                    }
                })

The finishing table should display every hyperlink as a hyperlink to another page. Any help?

Upvotes: 1

Views: 5173

Answers (4)

user1037355
user1037355

Reputation:

https://www.php.net/mysql_query

Watch out, which ever resource you are learning from may well be quite old. mysql_query is now deprecated.

https://www.php.net/manual/en/ref.pdo-mysql.php is a replacement.

Here is a kick starter to using PDO (this is much much safer) i write a while ago.

Include this file in which ever php script needs to access your db. An example file name would be 'database.php' but that is your call. Set the namespace from 'yourproject' to whatever your project is called. Correct the database credentials to suit your database

This will save you a lot of headaches hopefully!

I have given some example uses at the bottom for you. I remember when i started out getting clear advice was sometimes hard to come by.

//***** in a database class file*****/
namespace yourproject;
class Database {
    
    private $db_con = '';
    
    /*** Function to login to the database ***/
    public function db_login()
        {
            // Try to connect
            try{
                    // YOUR LOGIN DETAILS:
                    $db_hostname = 'localhost';
                               $db_database = 'yourdatabasename';
                                $db_username = 'yourdatabaseusername';
                                $db_password = 'yourdatabasepassword';
                    
                    // Connect to the server and select database
                    $this->db_con = new \PDO("mysql:host=$db_hostname;dbname=$db_database",
                                                "$db_username",
                                                "$db_password",
                                                array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
                    
                    // Prevent emulation of prepared statements for security
                    $this->db_con->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
                    $this->db_con->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
                    
                    return true;
                }
            // If it fails, send user to maintenance page
            catch(PDOException $e)
                {
                    header("location:http://yourwebsiteurl.com/maintenance.php");
                    exit();
                }
        }
        
    /*** Function for database control ***/
    public function db_control($query , $parameters, $returnID = false)
        {
            if(!is_array($query) && is_array($parameters))
                {
                    try{
                            //prepare the statement
                            $statement = $this->db_con->prepare($query);
                            
                            //execute the statement
                            $statement->execute($parameters);
                            
                            //check whether this is a select, if it is then we need to retrieve the selected data
                            if(strpos($query, 'SELECT') !== false)
                                {
                                    //fetch the results
                                    $result = array();
                                    while( $row = $statement->fetch(\PDO::FETCH_ASSOC) )
                                        {
                                            $result[] = $row;
                                        }
                                    
                                    //count the results
                                    $count = count($result);
                                    
                                    //return the array
                                    return array( 'results' => $result, 'result_count' => $count );
                                }
                            //else return the number of affected rows
                            else{
                                    //count the affected rows and place into a returnable array
                                    $affected_rows = $statement->rowCount();
                                    $returnArray = array('result_count' => $affected_rows);
                                
                                    //check to see if we are to return a newly inserted autoincrement ID from an INSERT
                                    if($returnID)
                                        {
                                            //find the newly created ID and add this data to the return array
                                            $insertID = $this->db_con->lastInsertId();
                                            $returnArray['ID'] = $insertID;
                                        }
                                    
                                    return $returnArray;
                                }
                        }
                    catch(PDOException $e)
                        {
                            return false;
                        }
                }
            else{
                    return false;
                }
        }
}

// Start the database class and connect to the database then create a globally accessible function for ease of reference
$db = new \yourproject\Database();
$db->db_login();
function _db( $sql , $params , $returnID = false ){
    return $GLOBALS['db']->db_control( $sql , $params , $returnID );
}

When you include this file you now have a new function: _db(). As the function is global it can be called from within any class or std file. When called into a variable as demonstrated below will result in an array like this:

array(
   'result_count' => 3,
   'results' => array(
     array(/*row 1*/),
     array(/*row 2*/),
     array(/*row 3*/),
     .. etc etc
   )
)

Now include your database file in your php script:

//call in the database file
require_once 'database.php';

//your query as in the op
$sql = 'SELECT * FROM pupil';
//your params for the query
$params = array();
//running the query and getting the results returned into a variable called $query
$query = _db($sql,$params);

//if no results
if( $query['result_count'] == 0 )
{
    echo 'sorry no pupils in the system';
}
else
{
    //looping through each result and printing into a html table row
    for( $i = 0 ; $i < $query['result_count'] ; ++$i )
    {
        echo '<tr><td><a href="profile.php?id=' . $query['results'][$i]['pupil_id'] . '"</a></td>';
        echo '<td>'. $query['results'][$i]['pupil_name'] . '</td>';
        echo '<td>'. $query['results'][$i]['class_id'] . '</td></tr>';
    }
}

Your original query but with some parameters passed through

//Passing parameters to the query
//your query
$sql = 'SELECT * FROM pupil WHERE pupil_id = :pupil_id AND class_id = :class_id';
//your params for the query
$params = array(
            ':pupil_id' => 12,
            ':class_id' => 17,
        );
//running the query and getting the results returned into a variable called $query
$query = _db($sql,$params);

//deal with the results as normal...

If you set the 3rd param as true you can return the automatic id of the row just entered eg:

//where $sql is a query that will INSERT a row
$query = _db($sql,$params, true);

Upvotes: 0

user2801966
user2801966

Reputation: 468

You don't put any text between your link tags, <a href="">text here</a>

Maybe this will help you:

 <td><?php echo '<a href="profile.php?id=' .$row['pupil_id']  . '">'.$row['pupil_name'].'</a>' ?></td>

Upvotes: 0

OfirH
OfirH

Reputation: 657

Try replace this:

<?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?>

with this:

<?php echo "<a href='profile.php?id=".$row['pupil_id']."'>link</a>"; ?>

Also, you dont have <table> tags at all.

Upvotes: 1

Hanky Panky
Hanky Panky

Reputation: 46900

Because your HTML is invalid, you are missing a closing > and you have no text defined for the hyperlink

<?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?>   //Wrong

Correct would be

<?php echo '<a href="profile.php?id='.$row['pupil_id'].'">'.$row['pupil_id'].'</a>'; ?>

Upvotes: 3

Related Questions