在一个查询中保存每行的行数。我怎样才能做到这一点?

时间:2014-10-02 02:56:47

标签: php mysql arrays survey

我正在尝试使用php和mysql进行调查,但我对代码有点不方便,因为当我提交调查表单时,它只保存调查的最后一个问题,这是因为INPUT名称。

这是代码。

数据库结构。

  

“问题”(质疑,问题)

     

“调查”(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

提示:表格没问题,它执行查询但问题是,它只存储调查的一个问题和答案,而是存储当时的所有问题和答案(数组的行)。

   <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>

我认为问题是“选择”名称,可能是因为它重写了调查中每个问题的其他问题和答案,因此它只存储了最后一个问题和答案。

我想使用一种形式存储多行:D

提前致谢。 :)

2 个答案:

答案 0 :(得分:0)

这是你的答案。您的insert命令没有分配列,只是值:

在类之外使用PDO连接

在您的情况下,如果您只想运行SQL查询,您将需要使用数据库的原始格式。这需要我的DBEngine中的两个更改。如果它将protected $con;更改为public $con;,那么当您想要调用任何类型的sql语句时,请执行以下操作:

// 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"]."')");
                    }  
            } ?>

答案 1 :(得分:0)

这是代码Rasclatt

<强> QUESTIONS.PHP

<?php

    class Questions{

        //atributos
        public $nameDono;
        public $objDb;
        public $result;

        public function __construct(){ 

            $this->objDb = new Database();

        }



        public function NewSurveyMulti($answer) {
                    if(!empty($answer)) {
                            foreach($answer as $questi => $value) {
                                    $query = "INSERT INTO survey VALUES('','".$questi."', '".$value."')";
                                    $this->objDb->insert($query);
                                }
                        }
                }


                // I don't know what the class name is but this is how
    // you would apply this method


    //--------------------------------I don't know where I have to put it, the class name is Questions.
     if(isset($_POST['answer']))
         Questions->NewSurveyMulti($_POST['answer']);



                //this functions shows all the questions for the survey
        public function mostrar_survey(){

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

        }
        }

    ?>

<强> Survey_form.php

 <?php
    require'../class/questions.php';

        $cuestionario= $objBdonar->show_questions();
        $survey= $objBdonar->NewSurveyMulti($answer) ;

     <form name="newDona" action="new_survey_exe.php" method="post">
    </table><?php


    //it calls the function that shows all the questions that are stored in the db
    $numrows = mysql_num_rows($cuestionario);
    if($numrows > 0) {
            while($row = mysql_fetch_array($cuestionario)) { ?>
            <tr>
                <td>
                    <?php echo $row["question"];?>
                </td>
            </tr>
            <th>
                <select name="answer[<?php echo $row['questi']; ?>][]">
                    <option value=""></option>
                    <option value="yes">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 } ?>

<强> New_survey_exe.php

<?php

require'../class/questions.php';
$objCon = new Connection();
$objCon->get_connected();
$objDona = new Questions();

$objDona->NewSurveyMulti($answer) ;


header('Location: ' . $_SERVER['HTTP_REFERER']);    

?>