I’m just wondering if there’s any way to select a row using the primary key in the WHERE clause without necessarily knowing the name of the key’s column.
My suggested PHP function is as follows:
function getData($table,$key,$asarray=false) {
$sql = mysql_query("select * from `".$table."` where primary='".$key."'");
if( !$asarray) return mysql_fetch_assoc($sql);
$ret = [];
while($row = mysql_fetch_assoc($sql)) $ret[] = $row;
return $ret;
}
A few notes:
$tableonly ever comes from literal strings inside the code, never from an outside source.- For the purposes of this question, assume that
$keyis already properly escaped. - I don’t care that
mysqlis deprecated in PHP 5.5, because I’m using PHP 5.4 - For that same reason
$ret = []is a perfectly valid way to define an array – I say this because in my last question people were telling me my code wasn’t working because of this syntax.
Now, my current, actual, working code has an associative array mapping table names to their corresponding primary key field names. I’m just wondering if there’s an automated way to do this, preferably one that doesn’t involve querying INFORMATION_SCHEMA, SHOW CREATE TABLE or SHOW INDEXES.
No, there is no automated way of doing it without knowing or querying the primary key column(s).
Note that the primary key may be more than one column!
I implemented this sort of generic find-by-primary-key method in the Zend Framework 1.0. We had to write code for the table gateway class to discover the table’s primary key and all other columns.
Use
DESCas a faster alternative toSHOW CREATE TABLEor querying theINFORMATION_SCHEMA. TheSHOWcommands just map to queries againstINFORMATION_SCHEMA, and that can have a high cost because it triggers InnoDB tables to re-read a portion of the tables to refresh in-memory statistics (unless you set innodb_stats_on_metadata=0).