W3docs

How to get primary key of table?

To get the primary key of a table in PHP, you can use the SHOW KEYS SQL statement to retrieve information about the keys (including the primary key) of a table.

To get the primary key of a table in PHP, you can use the SHOW KEYS SQL statement to retrieve information about the keys (including the primary key) of a table.

You can use the mysqli_query() function to execute the SHOW KEYS statement and retrieve the result set.

Then you can use the mysqli_fetch_array() function to iterate through the result set and check the Key_name field for the primary key. Note that tables with composite primary keys will return multiple rows where Key_name equals 'PRIMARY'.

Example:

Example of getting primary key of a table in PHP

<?php
$host = 'your_host';
$user = 'your_username';
$pass = 'your_password';
$db   = 'your_database';

$con = mysqli_connect($host, $user, $pass, $db);
if (!$con) {
    die('Connection failed: ' . mysqli_connect_error());
}

$result = mysqli_query($con, "SHOW KEYS FROM table_name");
if (!$result) {
    die('Query failed: ' . mysqli_error($con));
}

$primaryKeys = [];
while ($row = mysqli_fetch_array($result)) {
    if ($row['Key_name'] === 'PRIMARY') {
        $primaryKeys[] = $row['Column_name'];
    }
}

echo implode(', ', $primaryKeys);

mysqli_close($con);
?>

This will return the primary key column name(s) of table_name. For modern PHP applications, consider using PDO, which is the current standard for database interactions and provides improved error handling and security features.