SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Aug 2001
    Location
    Canada
    Posts
    64
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    using variables as mysql table names

    I have several pages that access the same database. So, in a separate script, I wrote a function to connect to the database and setup variable names for the tables that I use. I just include this script and call that function in all my other files.
    So, in my connect script, I have the table names setup as
    PHP Code:
    $table1 "table1"$table2 "table2"
    etc.

    My first question is if is this is an acceptable/recommended coding practice.

    Second, when I run a mysql_query in my other pages, I keep getting an error saying I have an sql syntax error. The query that I use is:
    PHP Code:
    $result mysql_query("SELECT * FROM $table1"); 
    . I also tried using concatenation:
    PHP Code:
    $result mysql_query("SELECT * FROM ".$table1); 
    and even adding extra quotes at the end with the concatenation method:
    PHP Code:
    $result mysql_query("SELECT * FROM ".$table."\""); 
    .
    None of these work - they all give me the same error telling me I have an error in my sql syntax. What am I doing wrong?

    Thanks.

  2. #2
    Dumb PHP codin' cat
    Join Date
    Aug 2000
    Location
    San Diego, CA
    Posts
    5,460
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Are yo usure table1 and table2 exist in your database, as your syntax is correct. Also are you sure the file is being included, try echoing the value of $table1 just above the query to see if its holds a value.


    PHP Code:
    print ($table1 != '') ? "\$table1 has a value of $table1"\$table1 is empty maybe I forgot to include";
    $result mysql_query("SELECT * FROM $table1"); 
    Please don't PM me with questions.
    Use the forums, that is what they are here for.

  3. #3
    SitePoint Enthusiast
    Join Date
    Aug 2001
    Location
    Canada
    Posts
    64
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ya, they're both there. I don't know what the problem was, but in the script that defined all the variables, etc. I just removed the function declaration. I just let it do all the database connection, variable definition and stuff as soon as it was executed. It works now.

  4. #4
    Dumb PHP codin' cat
    Join Date
    Aug 2000
    Location
    San Diego, CA
    Posts
    5,460
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ah well you never said that your query was in a function. Did you make them global inside tyhe function or pass them to the function as args?
    Please don't PM me with questions.
    Use the forums, that is what they are here for.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •