Search code examples
phpmysqlarrayssurvey

Save an array Row per Row in one query. How can I do that?


I'm trying to make a survey using php and mysql but I have a little inconvinient with the code, because when I submit the form with the survey, it only saves the last question of the survey, and It is because of the INPUT name.

here is the code.

DATABASE STRUCTURE.

"Questions" (idquestion, question)

"Surveys" (idsurvey, idquestion, answers, survey_number)

config.php

<?php

class Connection{
    
    //variables para los datos de la base de datos
    public $server;
    public $userdb;
    public $passdb;
    public $dbname;
    
    public function __construct(){
        
        //Iniciar las variables con los datos de la base de datos
        $this->server = 'localhost';
        $this->userdb = 'root';
        $this->passdb = '';
        $this->dbname = 'sistema_bss';
        
    }
    
    public function get_connected(){
        
        //Para conectarnos a MySQL
        $con = mysql_connect($this->server, $this->userdb, $this->passdb);
        //Nos conectamos a la base de datos que vamos a usar
        mysql_select_db($this->dbname, $con);
        
        
    }
    
}

?>

Questions.php

 public function show_questions(){

    $query = "SELECT * FROM questions  Where questionsnumber = 1";
    $this->result = $this->objDb->select($query);
    return $this->result;       
    
}

public function new_survey(){
        
    
        
        $query = "INSERT INTO survey VALUES('',  
        
            '".$_POST["questi"]."', 
            '".$_POST["answer"]."')";
        $this->objDb->insert($query);
                
        
    }   

            

Survey_form.php

hint: The form it's ok, it execute the query but the problem is, that it only store one question and answer of the survey, instead store all the questions and answers (array's rows) at the time.

   <form name="newDona" action="new_survey_exe.php" method="post" value= "">

 <?php
            
            //it calls the function that shows all the questions that are stored in the db
                $numrows = mysql_num_rows($survey);
                
            if($numrows > 0){
                
                while($row=mysql_fetch_array($survey)){?>
                    
                
                        
                        <td>
                    
                        <?php 
                        
                        
                        echo $row["question"];?></td>
                    
                        
                        
                        
                          <th><select name="answer" >
                
                        <option value=""></option>
                        <option value="yes">yes</option>
                        <option value="NO">NO</option>
                    
                    </select>
                        
                        <tr><td colspan="5" align="center"><input type="submit" name="send" id="send" value="SAVE" /></td></tr>
            
                            

I think the problem is the "select" name, maybe because it rewrites the other questions and answers for every question of the survey so it only stores the last question and answer.

I want to store multiple rows using one form :D

Thanks in advance. :)


Solution

  • Here is your answer. Your insert command was not assigning columns, just values:

    USE PDO CONNECTION OUTSIDE OF CLASS

    In your case, if you want to just run sql queries you will want to use the raw format of the DB. That requires two changes in my DBEngine. Where it says protected $con; change it to public $con; then when you want to call any kind of sql statement do as follows:

    // If the DB is already set don't do this step portion
    require_once('includes/classes/dbconnect.php');
    $db =   new DBConnect('localhost','sistema_bss','root','');
    // Here is where you use the PDO class
    
    $query = $db->con->prepare("SELECT MAX(surveynumber) FROM survey");
    $query->execute();
    
    if($query->rowCount()>0) {
            while($result = $query->fetch(PDO::FETCH_ASSOC)) {
            print_r($result);
        }
    }
    

    newsurvey.php

    <?php
        // Not sure if this is proper path back to root then back
        //to files, so you'll have to fix that if wrong
        // Include db
        require_once('includes/classes/dbconnect.php');
        // Include questions class
        require_once('apps/survey/classes/questions.php');
        // Create connection
        $con    =   new DBConnect('localhost','sistema_bss','root','');
    
        // If answers not submitted, show form
        if(!isset($_POST['answer'])) {
                include_once('apps/survey/new.form.php');
            }
        // If answers submitted process the form
        else {
                // Create questions class, forward DB connection
                $objDona = new Questions($con);
                // Run the insert class 
                $objDona->NewSurveyMulti($_POST['answer']);
                $display    =   $con->Fetch("select * from survey");
                print_r($display);
            } ?>
    

    new.form.php

    <?php
        // Fetch questions
        $cuestionario   =   $con->Fetch("SELECT * FROM questions"); ?>
    
        <form name="newDona" action="" method="post">
        </table><?php
        // Confirm there are questions being drawn from database
        $numrows        =   (is_array($cuestionario))? count($cuestionario): 0;
        if($numrows > 0) {
                // Loop through questions
                foreach($cuestionario as $row) { ?>
                <tr>
                    <!-- Write the question -->
                    <td><?php echo $row["question"];?></td>
                </tr>
                <th>
                    <!-- Set the question id -->
                    <select name="answer[<?php echo $row['idquestion']; ?>][]">
                        <option value=""></option>
                        <option value="1">yes</option>
                        <option value="no">NO</option>
                    </select>
                </th><?php } ?>
                <tr>
                    <td colspan="5" align="center">
                        <input type="submit" name="send" id="send" value="SAVE" />
                    </td>
                </tr>
            </table>
        </form>
        <?php } ?>
    

    dbconnect.php

    <?php
        // I'm adding my PDO database because yours is deprecated
        class DBConnect
            {
                public   $con;
                // Create a default database element
                public  function __construct($host = '',$db = '',$user = '',$pass = '')
                    {
                        try {
                                $this->con  =   new PDO("mysql:host=$host;dbname=$db",$user,$pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
                            }
                        catch (Exception $e) {
                              return 0;
                            }
                    }
    
                // Simple fetch and return method
                public  function Fetch($_sql)
                    {
                        $query  =   $this->con->prepare($_sql);
                        $query->execute();
    
                        if($query->rowCount() > 0) {
                                while($array = $query->fetch(PDO::FETCH_ASSOC)) {
                                        $rows[]   =   $array;
                                    }
                            }
    
                        return (isset($rows) && $rows !== 0 && !empty($rows))? $rows: 0;
                    }
    
                // Simple write to db method
                public  function Write($_sql)
                    {
                        $query  =   $this->con->prepare($_sql);
                        $query->execute();
                    }
            } ?>
    

    questions.php

    <?php
            class Questions
                {
                    //atributos
                    public $nameDono;
                    public $objDb;
                    public $result;
                    public $connect;
    
                    public function __construct($dbconnection){
                            // My PDO connection
                            $this->MyDB     =   $dbconnection;
                        }
    
                    public function NewSurveyMulti($answer = array())
                        {
                            if(!empty($answer)) {
                                    foreach($answer as $questi => $value) {
                                            $this->MyDB->Write("INSERT INTO survey (`idquestion`,`answers`) VALUES('".$questi."', '".$value[0]."')");
                                        }
                                }
                        }
    
                    public function mostrar_survey()
                        {
                            $this->result = $this->MyDB->Fetch("SELECT * FROM questions");
                            return $this->result;       
                        }
    
                    public function new_survey()
                        {
                            $this->MyDB->Write("INSERT INTO survey (`idquestion`,`answers`,`surveynumber`) VALUES("'".$_POST["questi"]."','".$_POST["answer"]."','".$_POST["numsurvey"]."')");
                        }  
                } ?>