如何在数据库中插入数组变量的每个值

时间:2016-12-29 18:30:48

标签: php

如何在数据库中插入数组变量的每个值,每当我尝试使用数组变量插入值时,它会给我一个错误“数组到字符串转换”。实际上我想将学生的出勤存储到“考勤数据库表”中,我正在从学生数据库中检索学生的ID和名称,学生的这些信息存储在数组中但是当我使用数组变量“ value_counts.saveAsNewAPIHadoopFile( AttributeError: 'TransformedDStream' object has no attribute 'saveAsNewAPIHadoopFile' ”将学生的名字插入到attendence_tbl数据库时,它给出了数组错误字符串转换。

$result

3 个答案:

答案 0 :(得分:0)

如果我理解你,你想要上传这样的内容:

Array([1] => '1', [2] => '2')

进入一个表,这是行不通的。因此,您必须使用JSON来 stringify 数组。例如:

<?php
    $value = 'Some string';
    $value2 = 'Some other string';
    $values = Array('String 1', 'String 2', 'String 3');

    $json_values = json_encode($values);

    $mysqli = new mysqli('HOSTNAME', 'USERNAME', 'PASSWORD', 'DATABASE'); // Connecting to SQL Server

    // Checking if connection was successfull
    if( $mysqli->connect_errno ){
        echo 'There was an error connection to the SQL Server<br>';
        echo '(' . $mysqli->connect_errno . ') ' . $mysqli->connect_error;
        exit; // FAIL
    }

    // Preparing a statement
    $stmt = $mysqli->prepare('INSERT into TABLENAME(value, value2, values) VALUES(?, ?, ?)');

    // Checking if php prepared the statement successfully
    if(!$stmt){
        echo 'There was an error preparing the statement!';
        exit;
    }

    if( !$stmt->bind_param('sss', $value, $value2, $json_values) ){
        echo 'There was an error binding params to the statement!';
        exit;
    }

    $stmt->execute();
?>

答案 1 :(得分:0)

似乎你想把一个数组变量数据直接放到应该抛出错误的表中,

这是解决方案。

要将数组的所有值直接添加到表中,必须先将数组转换为json,然后再将其插入数据库。喜欢这个..

$resultJson = json_encode($result);
$query = mysql_query("Insert into tbl_attendence (StudentRollNumber,SubjectId,Attendence,Date)VALUES(".$stud.", ".$resultJson.", ".$present.", ".$date.")");

如果要分别为每行的每个值将所有数组值添加到数据库中,则必须确保运行循环,然后将每个值插入到每个记录的数据库中。

答案 2 :(得分:0)

将数组发布到数据库中我使用这种方法:

       //database connection class
      class Database{ 

    // specify your own database credentials 
    private $host = "YOUR HOST"; 
    private $db_name = "DATABASE NAME"; 
    private $username = "USERNAME"; 
    private $password = "PASSWORD"; 
    public $conn; 

    // get the database connection 
    public function getConnection(){ $this->conn = null;

        try{
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
        }catch(PDOException $exception){
            echo "Connection error: " . $exception->getMessage();
        }

        return $this->conn;
    }
}

//model class
class Model{ 
    // database connection
    private $conn; 

    // constructor with $db as database connection 
    public function __construct($db){ 
        $this->conn = $db;
    }

    // add info to db
function create($fieldset){
     $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    // query to insert record
    $query = "INSERT INTO 
               tbl_attendence 
            SET 
                 $fieldset";

    // prepare query
    $stmt = $this->conn->prepare($query);

    // execute query
    if($stmt->execute()){
        return true;
    }else{
        return false;
    }
  }
}



//part that will handle the post

// get database connection 
$database = new Database(); 
$db = $database->getConnection();

//instatiate model
$model = new Model($db);



//function that will filter posted values
 function filter($value){

 $value = trim($value);
 $value = strip_tags($value);
 $value = stripslashes($value);
 $value = htmlentities($value);
 return $value; 
}

         if(!empty($_POST)){
              //Get Variables
                foreach($_POST as $key => $value){

                    //this part will tackle values which are arrays
                    if(is_array($value)){
                                $val=implode(",",filter($value));
                                $groupVal[] = $val;
                                $groupKeys[] = $key;
                        }

                        else{
                              $groupVal[] = $this->filter($value);
                              $groupKeys[] = $key;
                        }
                }

            //count items in array to establish a limit     
            $limit = count($_POST);

            //arranges the data into "key = value" format
            for($i=0;$i<$limit;$i++){
                $prepFieldset[$i]  = "$groupKeys[$i] = $groupVal[$i]";
            }

            //prepares the fieldset to be used in SQL query
            $fieldset = implode(",",$prepFieldset);

             //process them in the model
             $status = $model->create($fieldset);

             //show response
             if($status == true){


                     $response = 'Data saved';

             }


             else{
                      $response = 'Error when saving data';
             }
            }