0

I am having an array of fields and after using implode function and converting them to string, I am trying to use this string as names of columns in mysql_query() function as follows:

$field_array = array('course','batch','branch');

$fields = implode(", ",$field_array);
$resource = mysql_query("SELECT $fields FROM some_table") or die(mysql_error());

but I am getting the following error. What is that I am doing wrong here ?

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM fix_data' at line 1

Below is the exact code I am using

function fetch_resource_db_nowhere($table_name,$field_array,$return_type,$return_type_name) {



    if($field_array[0]=='ALL') {
        //echo "asda";
        $resource = mysql_query("SELECT * FROM ".$table_name."") or die(mysql_error());
    }
    else {
        $fields = implode(",",$field_array);
        $sql = "SELECT ".$fields." FROM ".$table_name."";
        echo $sql;
        $resource = mysql_query($sql) or die(mysql_error());
    }


    if($return_type == 'resource') {
        return $resource;
    }

    if($return_type == 'resource_array') {
        return mysql_fetch_assoc($resource);
    }

    if($return_type == 'resource_array_value') {
        $resource_array = mysql_fetch_assoc($resource);
        return $resource_array[$return_type_name];
    }


}

$data = fetch_resource_db_nowhere('fix_data',array('course','branch','name'),'resource','');
2
  • what does echo "SELECT $fields FROM some_table"; yield? Commented Oct 30, 2012 at 11:02
  • SELECT course,branch,name FROM fix_dataSELECT FROM fix_data this is the exact out put I am getting. now something is definitely wrong here. Commented Oct 30, 2012 at 12:06

1 Answer 1

3

You were trying to implode an array called field_array, even though your example shows an array called fields_array:

$fields_array = array('course','batch','branch');
$fields = implode(", ",$fields_array);
$resource = mysql_query("SELECT $fields FROM some_table") or die(mysql_error());

Edit: You changed your code again. Could you please give us the exact code that you're working with?

Sign up to request clarification or add additional context in comments.

7 Comments

@Rijk I just updated the answer. He was imploding an array called field_array when it was actually an array called fields_array.
Removed my downvote. Even though I think it's not the answer to his problem (read the error).
Of course it's the answer, syntax near from because the fields is empty.
If the implode was incorrect, he'd be selecting nothing, which would cause the SQL error in question.
Error says near 'FROM fix_data'. Where does "fix_data" come from?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.