Mysql_field_name to array

I am trying to compare the field names in the table with the $ _GET field names, and if they exist in the table, create a Query row, and I find it difficult to load mysql_field_name into an array, if I do them individually, how $t1 = mysql_field_name($result,1);

does it work, but load them all like a dose $vars = mysql_field_name($result);

. doesn't seem to work.

This dose doesn't work

$query = array();
$result = mysql_query("SELECT * FROM search_prof");
$vars = mysql_field_name($result);

foreach ($vars as $v)
{
    if (isset($_GET[$v]))
    {
        $query[] = $v.' = "'.addslashes($_GET[$v]).'"';
    }
}
$query = implode(' AND ', $query); 

      

It works

$t1 = mysql_field_name($result,1);
$t2 = mysql_field_name($result,2);
$t3 = mysql_field_name($result,3);
$t4 = mysql_field_name($result,4);
$t5 = mysql_field_name($result,5);


    $query = array();
    $result = mysql_query("SELECT * FROM search_prof");
    $vars = array('$t1', '$t2', '$t3', '$t4', '$t5'); 

    foreach ($vars as $v)
    {
        if (isset($_GET[$v]))
        {
            $query[] = $v.' = "'.addslashes($_GET[$v]).'"';
        }
    }
    $query = implode(' AND ', $query); 

      

+3


source to share


3 answers


You should take a look at the php documentation: http://php.net/manual/de/function.mysql-field-name.php

The second parameter in this function is NOT optional, so you need to follow the second approach.



If you want to make it dynamic, you can use the mysql_num_field function which gives you the number of columns. After that, you can build a loop that iterates over and over by calling the mysql_field_name function each time.

+2


source


If you want your current approach to work, I think you could do something like:

//Get fields in table
$numberOfFields = mysql_num_fields($result) - 1;

$fields = array();
for ($i = 0; $i <= $numberOfFields; $i++) {
    $fields[] = mysql_field_name($result, $i);
}

//Intersect
$parameters = array_intersect(array_keys($_GET), $fields);

//Query
$q = array();
foreach($parameters as $parameter) {
    $q[] = $v . '="' . addslashes($_GET[$parameter]) . '"';
}

$q = implode(" AND ", $q);

      



Perhaps you can also try running a DESCRIBE query on a table and parse these results, but you are not aware of the performance of DESCRIBE.

+1


source


You can use something like this to get the fields.

$query = array();
$result = mysql_query("SELECT * FROM search_prof");
$numFields = mysql_num_fields($result);
$vars = array();
for ( $i = 0; $i < $numFields; $i++ )
    $vars[] = mysql_field_name($result, $i);

foreach ($vars as $v)
{
    if (isset($_GET[$v]))
    {
        $query[] = $v.' = "'.addslashes($_GET[$v]).'"';
    }
}
$query = implode(' AND ', $query); 

      

+1


source







All Articles