Jump to content

MySQL INSERT into putting array on seperate table rows


jimmyt1988

Recommended Posts

Hi again all,

 

Why does the foreach loop im doing, put the array values from collection, into seperate table rows rather than 1 row per whole array?

 


    <?php
        class registration{                    
            public $fields = array("username", "email", "password");
            public $data = array();
            public $table = "users";
            public $dateTime = "";
            public $datePos = 0;
            public $dateEntryName = "date";
            public $connection;
            
            function timeStamp(){
                return($this->dateTime = date("Y-m-d H:i:s"));
            }
            
            function insertRow($collection){      
                    //HERE
                    foreach($this->fields as $row => $value){
                        mysql_query("INSERT INTO $this->table ($value)
                        VALUES ('$collection[$row]')");
                    }
                    
                    mysql_close($this->connection->connectData);
            }
            
            function validateFields(){            

                $this->connection = new connection();
                $this->connection->connect(); 
                        
                foreach($this->fields as $key => $value){
                    array_push($this->data, $_POST[$this->fields[$key]]);
                }
                $this->dateTime = $this->timeStamp();
                array_unshift($this->data, $this->dateTime);                
                array_unshift($this->fields, $this->dateEntryName);   
                
                foreach($this->data as $value){
                    echo "$value";
                }
                
                $this->insertRow($this->data);
            }
        }
        
        $registration = new registration();
        $registration->validateFields();
    ?>


 

I end up with 3 rows

 

row 1: username

row 2: email

row 3 : password

 

rather than row 1:username email password.

I got this to work... Is there a better way with the foreach thingy?

 


            function insertRow(){      
                $row = implode(', ', $this->fields);
                $str = implode('\', \'', $this->data);
                
                mysql_query("INSERT INTO $this->table ($row)
                VALUES ('$str')");
                                        
                mysql_close($this->connection->connectData);
            }

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.