Gotham Gotham - 6 months ago 14
SQL Question

select data from mysql and display it in order of expiry date

I want to be able to display document name and expiry date in order of expiry date in my browser. Mysql table name is employee_doc and the database name is employee_info. Here is my code

<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'employee_info';

$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

if(! $conn ) {
die('Could not connect: ' . $mysqli->connect_error());
}

$mysqli = 'SELECT * FROM `employee_doc` ORDER BY `employee_doc`.`PPExp` ASC';
mysqli_connect($conn,"employee_info");
$retval = mysqli_query($conn,$mysqli);

if(! $retval ) {
die('Could not get data: ' . $mysqli->connect_error());
}

while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
echo $row['PPNO'];
echo "<br>";
echo $row['PPExp'];
echo "<br>";
}
mysqli_close($conn);
?>


PPExp and PPNO are the column headings for expiry date and document name respectively. I am using Xampp. When I open the file from localhost die('Could not get data: ' . mysql_error()); is executed. What am I doing wrong?

Answer

mysqli_connect: Open a new connection to the MySQL server.

mysqli_select_db: Selects the default database to be used when performing queries against the database connection. This function should only be used to change the default database for the connection.

This explains the basic concepts of both the functions. Check mysqli_connect and mysqli_select_db for detailed explanation.

Change your code as follows:

<?php
    $dbhost = 'localhost';
    $dbuser = 'root';
    $dbpass = '';
    $dbname = 'employee_info';

    $conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

    if(! $conn ) 
    {
        die('Could not connect: ' . mysqli_connect_error());
    } 

    $sql = 'SELECT * FROM `employee_doc` ORDER BY `employee_doc`.`PPExp` ASC';

    $retval = mysqli_query($conn,$sql);

    if(! $retval ) 
    {
        die('Could not get data: ' . mysqli_error($conn));
    }

    while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC))  
    {
        echo $row['PPNO'];
        echo "<br>";
        echo $row['PPExp'];
        echo "<br>";
    }  

    mysqli_close($conn); 
?>

Also you are mixing mysql and mysqli