简体   繁体   中英

PHP: MySQL Query with fieldname in a var

Little question: With the following code...

<?php
$statement = "SELECT * FROM TABLE";
$query_unfetched = mysql_query($statement);
$query_num = mysql_num_rows($query_unfetched);
if ($query_num !== 1) {
    exit;
}
$query_fetched = mysql_fetch_object($query_unfetched);

$fielname = "ID";
echo $query_fetched->$fiedname;
?>

With this code, there is no output, because PHP somehow does not check that in $fieldname is an existing name of a field in the selected Table.

Why doesn't it work, have I made a mistake? Or are there any other ways to select a field whose name is saved in a var?

Thanks for the help!

Instead of using mysql_fetch_object, you could use mysql_fetch_assoc . It will return the result as an array, after which you can simply use your variable as a key.

I'd suggest using var_dump on the $query_fetched . Some OS's and DB's will return different capitalizations. Oracle, for one, will always return the column names as capital. I've seen MySQL only return lower in one circumstance.

You can also use the fetch_assoc as suggested by Cpt. eMco and that will give you warnings if the array key is not set. (Remember to turn warnings off in production though).

(I do need to put in an obligatory plug for the PDO classes. I find them far more intuitive and clearer.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM