Jump to content

Variable as the field name problem PHP/mysql


danx30

Recommended Posts

The basic format for an UPDATE query is

 

UPDATE table_name SET field_name=new value

 

In order for it to function $id will HAVE to be set to a field name. What are you trying to do? What is $id set to? Maybe your query is supposed to be:

$query4 = "UPDATE users SET id='$id' WHERE name='$n1'";

There are about 20 columns, all with different names.  When the user hits the php page it will parse a specific column name which is the variable $id.  So I need it to insert a 1 into that column if it's used.  But because there could be any of 20 different ones I have to use a variable.  So I need the field name to be a variable.

Apprently I am not making myself very clear.  Lets try this again..

 

Someone hits the page and parses a 12 to the $id variable.  Which in my database there is a column named 12..  I need it to insert a 1 into that field.

 

But not everyone will parse a 12, some may parse another number which will have columns already setup for in the database.

Someone hits the page and parses a 12 to the $id variable.  Which in my database there is a column named 12.. 

IIRC, you can't have a column name that begins with a numeric value in mySQL, or most other databases

How does 12 get passed to the page? Via the url like

 

filename.php?id=12

 

In which case to get the id from the url you'll use $_GET['id'] like so

 

if(isset($_GET['id']) && is_numeric($_GET['id']))
{
    $id = (int) $_GET['id'];

    $query4 = "UPDATE users SET $id='1' WHERE name='$n1'";

    // rest of code
}

If you fields named a1 .. to .. a12 and you're using the example code I made above

 

Then you'd do:

if(isset($_GET['id']) && is_numeric($_GET['id']))
{
    $id = 'a'.$_GET['id'];

    $query4 = "UPDATE users SET $id='1' WHERE name='$n1'";

    // rest of code
}

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.