Jump to content

php form and mysql


darbok

Recommended Posts

The answer to your specific question is you'd use a $_GET or $_POST method.

Link to comment
Share on other sites

On 5/11/2017 at 9:15 PM, niche said:

The answer to your specific question is you'd use a $_GET or $_POST method.

I think i explained myself wrong possibly. I understand about submitting to mysql from php... but from what iv'e seen you need to list all the columns in the sql tables that the info has to go in from the php form. I was wondering if there was some way to do this without having to list all 30 fields  that the php/sql connect statement has to post to individual.

Link to comment
Share on other sites

It's best to list the fields.  You can leave out the field list and just have the values in the insert query, but if you ever modify the table it's going to break the code.  It's always best to list out what you're doing to avoid issues like that.

Link to comment
Share on other sites

On 5/15/2017 at 3:32 PM, justsomeguy said:

It's best to list the fields.  You can leave out the field list and just have the values in the insert query, but if you ever modify the table it's going to break the code.  It's always best to list out what you're doing to avoid issues like that.

So it's best to just it up and list all the fields?

Link to comment
Share on other sites

Rough example

 $sql = "SHOW COLUMNS FROM TableName";
        $stmt = $pdo->prepare($sql);
        $stmt->execute();

        $arr = [];

        while ($row = $stmt->fetchObject()) {

//check if column is non auto_increment
            if ($row->Extra !== 'auto_increment') {
                $arr[] = $row->Field;
            }
       
        }
        $convert_arr = implode(', ', $arr);
        
        $ins_sql = "INSERT INTO TableName ($convert_arr)VALUES (11, 4)";
        $pdo->exec($ins_sql);

You could even use column names retrieved to retrieve  $_POST/$_GET name values of the same named index.

Edited by dsonesuk
Link to comment
Share on other sites

So it's best to just it up and list all the fields?

Yep.  The alternative is to not list the columns in the table and only give the values:

INSERT INTO table VALUES ('val1', 'val2', 'val3')

But, like I said, if you ever change the structure of that table then that query is going to break if you've changed the number of columns.  It's best to just list everything out explicitly.  You don't have to pay per character in your source code, make the code as obvious as possible so that it's easy to maintain.  Ease of maintenance should always be a higher priority than something like how long the code is.

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...