Forum Moderators: coopster

Message Too Old, No Replies

Using a PHP variable as a column name in a MySQL query

         

jdbnd

4:01 am on Oct 23, 2008 (gmt 0)

10+ Year Member



I am trying to query a MySQL table using the inputs from a web form, in the following way.

There are dropdown boxes where the user selects an option. However, the IDs of the available options are actually *column names* in the MySQL table (with binary values).

And I can't get the query to work. It gets called through another PHP function called get_all_rows - the relevant code is below (I am just trying to get it to work with one variable first). What I am trying to get it to do is return all rows with a value of 1 in the column whose NAME is represented by $page_vars['specialty'].

Any ideas?

Thanks!

<?php
$db = new db();

if ( isset( $_POST['select-state'] ) ){
$page_vars['state'] = $_POST['select-state'];
}
if ( isset( $_POST['select-role'] ) ){
$page_vars['role'] = $_POST['select-role'];
}
if ( isset( $_POST['select-population'] ) ){
$page_vars['population'] = $_POST['select-population'];
}
if ( isset( $_POST['select-specialty'] ) ){
$page_vars['specialty'] = $_POST['select-specialty'];
}

$order['featured_school'] = 'DESC';
$order['institution_name'] = 'ASC';

$data = $db->get_all_rows('"'.$page_vars['specialty'].'"', 'schools_main', $order);

Here's the get_all_rows code:

function get_all_rows( $where = '', $table = '', $order = NULL, $array_key = '' ) {
if(empty($table)) $table = $this->table;

if(!empty($where)) $where = 'AND '.$where;
$sql_order = $this->set_sql_order($order, $table);
$sql = "SELECT * FROM `$table` WHERE (1=1 $where) $sql_order";

$rows = array();
if( $this->query($sql) ) {
$rows = $this->last_result;
if(!empty($array_key) && isset($rows[0][$array_key])){
$rows = array();
foreach($this->last_result as $row){
$rows[ $row[$array_key] ] = $row;
}
}
}
return $rows;
}

Alt_F4

4:27 am on Oct 23, 2008 (gmt 0)

10+ Year Member



Hi,

have you tried

if(!empty($where)) $where = 'AND '.$where.'=1';

in the get_all_rows code?

jdbnd

4:32 am on Oct 23, 2008 (gmt 0)

10+ Year Member



You know, I actually trimmed the double quotes out of the get_all_rows arguments and it seems to be working. It always takes the pressure off when I post something here. Then I seem to get it right away for some weird reason.

But I will also try adding the code you suggested as well - thanks for the quick response.

Joe

Alt_F4

4:38 am on Oct 23, 2008 (gmt 0)

10+ Year Member



No worries,

Actually if the data type of your column is binary then what i posted may not work. I didn't check that!

Anyhow glad to see you figured it out

Cheers