簡體   English   中英

在一個查詢中,每行保存一個數組。 我怎樣才能做到這一點?

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

我正在嘗試使用php和mysql進行調查,但是我對代碼有些不滿意,因為當我與調查一起提交表格時,它只保存了調查的最后一個問題,並且是因為輸入名稱。

這是代碼。

數據庫結構。

“問題”(idquestion,問題)

“調查”(idsurvey,idquestion,答案,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

提前致謝。 :)

這是你的答案。 您的插入命令未分配列,僅分配值:

在課外使用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"]."')");
                    }  
            } ?>

這是代碼Rasclatt

問題庫

<?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']);    

?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM