1

I have a MySQL-database with x rows. Now I want to interpret a link, fetch the right row and print this values.

E.g. Link: .html?row=3 -> Opens site which fetch row 3 and print them.

.html?row=1000 -> Opens site which fetch row 1000 and print them

I don't know how to connect this dynamic link and the database. I only can print the database when I chose the row manually.

<?php
require_once ('../mysql/config.php');
$db_link = mysqli_connect (
                 MYSQL_HOST, 
                 MYSQL_BENUTZER, 
                 MYSQL_KENNWORT, 
                 MYSQL_DATENBANK
                );
mysqli_set_charset($db_link, 'utf8');
if (!$db_link) {
die('keine Verbindung möglich: ' . mysql_error());
} 

$sql = "SELECT * FROM Tabelle1";
$db_erg = mysqli_query( $db_link, $sql );
?>
if ( ! $db_erg )
      {
        die('Ungültige Abfrage: ' . mysqli_error());
      }
      while ($row = mysqli_fetch_array( $db_erg, MYSQL_ASSOC))
      {
        echo $row['B'];
        echo $row['E'];
      }
      mysqli_free_result( $db_erg );
      ?>
elkloso
  • 27
  • 1
  • 7
  • You should be using a unique key in the table to specify a row, that way it will always return the correct row. Just add a where clause to your query. If there isn't a unique key (bad design, BTW), you can use the limit clause. – Sloan Thrasher Jun 16 '17 at 17:02
  • I second Sloan's advice. And what's the html? How do you generate that link? – George M Reinstate Monica Jun 16 '17 at 17:04
  • Thank you for your advice. I am a MySQL Beginner. I don't generate the link. They are static with a parameter "?row=... " at the end. My fault. – elkloso Jun 16 '17 at 17:08

2 Answers2

1

If it really has to be by row number (which can change depending upon the where or order by clauses), you can use the limit clause:

SELECT * 
FROM Tabelle1
LIMIT 1000,1;

A much better design is to have a unique key, and select a row based on that:

SELECT * 
FROM Tabelle1
WHERE `id` = 1000;

Since you didn't include the schema of the table, I just made up a column name as an example.

To get the value passed to your php script, you can use:

$row_num = $_REQUEST['row'];
Sloan Thrasher
  • 4,953
  • 3
  • 22
  • 40
  • Thank you. I think my problem is that I don't know how to fetch the html link. In your example you define the "id" as "1000". But I need to say "id" = "parameter from the called html link". – elkloso Jun 16 '17 at 17:12
  • I've added a simple example on retrieving a value passed to the script in the answer above. – Sloan Thrasher Jun 16 '17 at 17:15
  • The table is included from a excel file so the schema is like the excel schema "A to Z" and "1 to 100". Every row should show with another link. If I click on .hmtl?row=A" it should show row "A" and so on. – elkloso Jun 16 '17 at 17:15
  • If it's Excel, row would be a number. row=A would reference a column. You say "included from an excel file". Do you mean the table was _imported_ from an excel file? – Sloan Thrasher Jun 16 '17 at 17:18
  • Sorry I mean imported. I know but he shows me "A" or "C" or whatever as a row but that's right in my case. I think it's really confusing and I should come back with an example on a server. – elkloso Jun 16 '17 at 17:21
  • Show the schema of your table (column names and types) and a few rows of sample data. – Sloan Thrasher Jun 16 '17 at 17:23
1

mysql/data_access.php

<?php

/*
 * ---------------------
 * Data access functions
 * ---------------------
 */

/**
 * Create a new db connection.
 * 
 * @param string $host Host.
 * @param string $dbname Database name.
 * @param string $username Username.
 * @param string $password Password.
 * @param string $port [optional] Port.
 * @param array $charset [optional] Character set.
 * @param array $options [optional] Driver options.
 * @return PDO Db connection.
 */
function createConnection($host, $dbname, $username, $password, $port = '3306', $charset = 'utf8', $options = array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_EMULATE_PREPARES => false,
    PDO::ATTR_PERSISTENT => true,
)) {
    $dsn = getDsn($host, $dbname, $port, $charset);
    $connection = new PDO($dsn, $username, $password);
    foreach ($options as $key => $value) {
        $connection->setAttribute($key, $value);
    }
    return $connection;
}

/**
 * Create a mysql DSN string.
 * 
 * @param string $host Host.
 * @param string $dbname Database name.
 * @param string $port [optional] Port.
 * @param array $charset [optional] Character set.
 * @return string DSN string.
 */
function getDsn($host, $dbname, $port = '3306', $charset = 'utf8') {
    $dsn = sprintf('mysql:host=%s;port=%s;dbname=%s;charset=%s'
            , $host
            , $port
            , $dbname
            , $charset
    );
    return $dsn;
}

/**
 * Close a db connection.
 * 
 * @param PDO $connection Db connection.
 * @return void
 */
function closeConnection($connection) {
    $connection = NULL;
}

/**
 * Get the data type of a binding value.
 * 
 * @param mixed $value Binding value.
 * @return mixed Data type of the binding value.
 */
function getInputParameterDataType($value) {
    $dataType = PDO::PARAM_STR;
    if (is_int($value)) {
        $dataType = PDO::PARAM_INT;
    } elseif (is_bool($value)) {
        $dataType = PDO::PARAM_BOOL;
    }
    return $dataType;
}

error_reporting.php

<?php

/*
 * -------------------------
 * Error reporting functions
 * -------------------------
 */

/**
 * Toggle error reporting.
 * 
 * @param integer $level Error level.
 * @param bool $display_errors Display errors if TRUE, hide them otherwise.
 * @return void
 */
function acivateErrorReporting($level = E_ALL, $display_errors = 1) {
    error_reporting($level);
    ini_set('display_errors', $display_errors);
}

print.php

<?php

/**
 * Print data on screen.
 * 
 * @param mixed $data Data to print.
 * @param bool $preformatted Print preformatted if TRUE, print normal otherwise.
 * @return void
 */
function printData($data, $preformatted = FALSE) {
    if ($preformatted) {
        echo '<pre>' . print_r($data, true) . '</pre>';
    } else {
        echo $data;
    }
}

deli_list.php

<?php
require_once ('../mysql/config.php');
require_once ('../mysql/data_access.php');
require_once ('../mysql/print.php');

// Validate the 'id' value from the query string
if (!isset($_GET['id']) || empty($_GET['id']) || $_GET['id'] == 0) {
    echo 'Please provide a valid "id" value!';
} else {
    try {
        // Read the 'id' value from the query string.
        $id = $_GET['id'];

        // Create db connection.
        $connection = createConnection(
                MYSQL_HOST, MYSQL_DATENBANK, MYSQL_BENUTZER
                , MYSQL_KENNWORT, MYSQL_PORT, MYSQL_CHARSET
        );

        // Define sql statement.
        $sql = 'SELECT * FROM Tabelle1 WHERE id = :id';

        // Prepare and check sql statement (returns PDO statement).
        $statement = $connection->prepare($sql);
        if (!$statement) {
            throw new Exception('The SQL statement can not be prepared!');
        }

        // Bind values to sql statement parameters.
        $statement->bindValue(':id', $id, getInputParameterDataType($id));

        // Execute and check PDO statement.
        if (!$statement->execute()) {
            throw new Exception('The PDO statement can not be executed!');
        }

        // Fetch person details.
        $fetchedData = $statement->fetchAll(PDO::FETCH_ASSOC);

        closeConnection($connection);
    } catch (PDOException $pdoException) {
        printData($pdoException->getMessage());
        exit();
    } catch (Exception $exception) {
        printData($exception->getMessage());
        exit();
    }
}
?>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>App title</title>
    </head>
    <body>

        <!-- Accordion example -->
        <ul class="accordion">
            <?php
            foreach ($fetchedData as $record) {
                ?>
                <li>
                    <?php echo $record['A'] ?> - <?php echo $record['B'] ?> - <?php echo $record['C'] ?>
                </li>
                <?php
            }
            ?>
        </ul>

        <!-- Table example -->
        <table>
            <?php
            foreach ($fetchedData as $record) {
                ?>
                <tr>
                    <td>
                        <?php echo $record['A'] ?>
                    </td>
                    <td>
                        <?php echo $record['B'] ?>
                    </td>
                    <td>
                        <?php echo $record['C'] ?>
                    </td>
                </tr>
                <?php
            }
            ?>
        </table>

    </body>
</html>
  • Thank you! I'll try it tomorrow. – elkloso Jun 16 '17 at 17:55
  • @elkloso You are welcome. Feel free to ask anything if you need. –  Jun 16 '17 at 18:04
  • I tried your code but it says: "The sql statement can not be prepared!". I think it's because of the "$sql = "SELECT * FROM Tabelle1 WHERE id = ?";". I tried "A"; " 'A' ", "['A']" but it didn't work. – elkloso Jun 16 '17 at 19:54
  • Same issue as before. phpadmin says the identity column is type "int(3)". – elkloso Jun 16 '17 at 20:28
  • Now I get a blank page – elkloso Jun 16 '17 at 20:56
  • "Fatal error: Wrong parameters for Exception([string $exception [, long $code [, Exception $previous = NULL]]]) in .../test.php on line 49". Line 49 is "throw new Exception(mysqli_error_list($db_link));" – elkloso Jun 16 '17 at 21:06
  • `"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '['A']' at line 1"` If I try A instead of ['A']: `Unknown column 'id' in 'where clause'` – elkloso Jun 16 '17 at 21:14
  • Thank you. I guess I found the error. In phpmyadmin the columns and rows are inverted because of the imported table. I'll try another table tomorrow. – elkloso Jun 16 '17 at 21:29
  • If I say `SHOW COLUMNS FROM table` it shows all columns. In column 'A' is the id located but it doesn't work. How can I mark this column as the "row identify column"? – elkloso Jun 16 '17 at 22:03
  • I haven't enough reputation to chat. This is the output: https://www.pic-upload.de/view-33350340/Unbenannt.jpg.html – elkloso Jun 17 '17 at 06:30
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/146926/discussion-between-aendeerei-and-elkloso). –  Jun 17 '17 at 06:32
  • @elkloso Thanks, I appreciate. –  Jun 17 '17 at 13:25