Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

php mysql query

  • 21-12-2005 04:39PM
    #1
    Registered Users, Registered Users 2 Posts: 673 ✭✭✭


    hey,

    There is probably a really easy solution to this but i cant seem to figure it out.

    i am doing a php query of a mysql database with the following code:
    $query = "SELECT user_answer_q".$question_code."
    		FROM w1_survey_results
    		WHERE survey_user_id = ".$_SESSION['user_id']."";
    		$results = mysql_query($query)
    			or die(mysql_error());
    
    		while ($rows = mysql_fetch_array($results)) {
    		extract ($rows);
    		echo ?????????
    		}
    

    The select statament has to be partly made up of a variable i.e. "SELECT user_answer_q".$question_code."

    When i get to the bottom of the query and try and echo the results what do i put in for the variable to be echo'd out?


Comments

  • Registered Users, Registered Users 2 Posts: 68,173 ✭✭✭✭seamus


    Ah I see.

    Use an alias for the column you want to select , eg..
    SELECT user_answer_q".$question_code." as answer
    		FROM w1_survey_results
    

    Then you can just write
    echo $answer;
    


  • Registered Users, Registered Users 2 Posts: 673 ✭✭✭Bananna man


    Got it sorted FINALLY!!!! Cheers m8 :D


  • Registered Users, Registered Users 2 Posts: 68,173 ✭✭✭✭seamus


    If you *really* want to know if it's possible to do it using the original name of the column, you could have done
    $col_name = "user_answer_q".$question_code;
    .....
    echo $$col_name;
    
    Much harder to read (and marginally less efficient) than the other solution.


  • Registered Users, Registered Users 2 Posts: 673 ✭✭✭Bananna man


    Similar question again!!

    Now im trying to create a table with a php script where the table name has a variable in it:

    $sql = "CREATE TABLE ".$week."_survey_results

    is this done with an as statement as well?


  • Registered Users, Registered Users 2 Posts: 68,173 ✭✭✭✭seamus


    No.

    If you need to refer to this table later on, I would set the name of the table as a variable, e.g.

    $table_name = $week."_survey_results";

    $sql = "CREATE TABLE $table_name";

    Without viewing the rest of your code, I suspect there may be an easier way to do it than dynamically creating tables.


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 673 ✭✭✭Bananna man


    Thanks again m8, your a life saver ;)


Advertisement