简体   繁体   中英

PDO UPDATE array using php mysql

Hello I'm trying to make a code to UPDATE or EDIT the survey answers and comments per answer but when I execute the function submiting the form, it did not save any value into the database. What can I do to fix it?

I'm new in PDO.

Thanks in advance.

Database Structure

"Questions" (idquestion, question)

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

Update function

public function ModifySurveyMulti($answer = array())
{                           
    if(!empty($answer)) {
        foreach($answer as $questi => $value  ) {
            $this->MyDB->Write("UPDATE survey SET(
                      `idquestion` = '".$questi."',                             
                      `answers` = '".$value[0]."',
                      `comments_per_answer`= '".$_POST["comment"][$questi]."')");
        }
    }
}

modify_surveyform.php

<th><?php echo $row["questions"];?></th>
<td>
  <input type  = "text" 
         name  = "answer[<?php echo $row['idquestion'];?>][]"
         value = "<?php echo $row["answers"];?>">
  </input>
</td>
<td>
  <Textarea type = "text"
            name = "comment[<?php echo $row['idquestion'];?>]"
            cols = "50" rows = "3"/> <?php echo $row["comment"];?
  </textarea>
</td>
</tr><?php } ?>

Mydbconnect.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();
      }
}?>

Few things you need to do:

  • First of all ditch this code, it is useless and expose you to sql injection
  • Use PDO directly with prepared statement
  • The query you need is :

UPDATE survey SET(`answers`= ?,`comments_per_answer`= ?) WHERE idquestion = ?

You will need to adjust your class to only create the connection

class DBConnect
{
    public   $con;

    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) {
            die($e);
        }
    }

    public function get_connection(){
        return $this->con;
    }

}

So that you can create it like this:

$db = new DBConnect(/*pass arguments here*/);
$this->MyDB = $db->get_connection();

Modify and use it in your function:

public function ModifySurveyMulti($answer = array(), $comments)
{
    $sql = 'UPDATE survey SET(`answers`= ?,`comments_per_answer`= ?) 
            WHERE idquestion = ?';
    $stmt->prepare($sql);
    foreach($answer as $questi => $value ) {
        $stmt->execute(array($value, $comments[$questi],$questi));
        $count = $stmt->rowCount();
        echo $count > 0 ? $questi.' updated' : $questi.' did not update';
    }
}

Call the function :

if(isset($_POST['answer'], $_POST['comments'])){
    $answers =  $_POST['answer'];
    $comments =  $_POST['comments'];
    ModifySurveyMulti($answers, $comments);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM