programing

PHP로 MySQL 데이터베이스에 배열 삽입

oldcodes 2023. 10. 21. 10:48
반응형

PHP로 MySQL 데이터베이스에 배열 삽입

데이터베이스에 저장할 배열이 다음과 같습니다.

$insData = array(
    'uid' => $fbme['id'],
    'first_name' => $fbme['first_name'],
    'last_name' => $fbme['last_name'],
    'email' => isset($fbme['email']) ? $fbme['email'] : '',
    'link' => $fbme['link'],
    'affiliations' => $networks,
    'birthday' => $info[0]['birthday_date'],
    'current_location' => isset($fbme['location']['name']) ? $fbme['location']['name'] : '',
    'education_history' => $education,
    'work' => $workInfo,
    'hometown_location' => isset($fbme['hometown']['name']) ? $fbme['hometown']['name'] : '',
    'interests' => $info[0]['interests'],
    'locale' => $info[0]['locale'],
    'movies' => $movies,
    'music' => $music,
    'political' => $info[0]['political'],
    'relationship_status' => $info[0]['relationship_status'],
    'sex' =>  isset($fbme['gender']) ? $fbme['gender'] : '',
    'tv' => $television,
    'status' => '0',
    'created' => $now,
    'updated' => $now,
);

이 작업을 수행하는 방법에 대해 Google을 검색했는데 테이블에 삽입하기 전에 배열을 분할해야 한다는 정보만 찾을 수 있습니다.이거 맞는건가요?순진해서 미안해요, php는 처음이에요.

MySQLPHP 데이터 형식을 이해하지 못하기 때문에 배열을 MySQL에 직접 삽입할 수 없습니다.MySQLSQL만 이해합니다.MySQL 데이터베이스에 배열을 삽입하려면 SQL 문으로 변환해야 합니다.이 작업은 수동으로 수행하거나 라이브러리에서 수행할 수 있습니다.출력은 다음 값이어야 합니다.INSERT진술.

PHP7용 업데이트

PHP 5.5 mysql_real_escape_string를 사용하지 않게 되었고 PHP7 현재 제거되었습니다.새로운 절차에 대한 php.net 의 설명서를 참조하십시오.


원래 답변:

여기 표준 MySQL 삽입 문이 있습니다.

INSERT INTO TABLE1(COLUMN1, COLUMN2, ....) VALUES (VALUE1, VALUE2..)

배열의 키에 표시된 열이 있는 표가 있는 경우 이 작은 토막글과 함께 삽입할 수 있습니다.배열이 이 문으로 변환되는 방법은 다음과 같습니다.

$columns = implode(", ",array_keys($insData));
$link = mysqli_connect($url, $user, $pass,$db);
$escaped_values = array_map(array($link, 'real_escape_string'), array_values($insData));

$values  = implode("', '", $escaped_values);
$sql = "INSERT INTO `fbdata`($columns) VALUES ('$values')";

다양한 방법이 있습니다...준비된 문장을 사용한 예를 들어보겠습니다.

$prep = array();
foreach($insData as $k => $v ) {
    $prep[':'.$k] = $v;
}
$sth = $db->prepare("INSERT INTO table ( " . implode(', ',array_keys($insData)) . ") VALUES (" . implode(', ',array_keys($prep)) . ")");
$res = $sth->execute($prep);

여기서 바람을 피우고 있는데 첫 번째 배열의 키가 SQL 테이블의 열 이름이라고 가정합니다.또한 PDO를 사용할 수 있다고 가정합니다.더 많은 정보는 http://php.net/manual/en/book.pdo.php 에서 확인할 수 있습니다.

수락된 답변을 바탕으로 이에 대한 저의 전체적인 해결책은 다음과 같습니다.

:

include("./assets/php/db.php");
$data = array('field1' => 'data1', 'field2'=> 'data2');
insertArr("databaseName.tableName", $data);

db.

<?PHP
/**
 * Class to initiate a new MySQL connection based on $dbInfo settings found in dbSettings.php
 *
 * @example
 *    $db = new database(); // Initiate a new database connection
 *    mysql_close($db->get_link());
 */
class database{
    protected $databaseLink;
    function __construct(){
        include "dbSettings.php";
        $this->database = $dbInfo['host'];
        $this->mysql_user = $dbInfo['user'];
        $this->mysql_pass = $dbInfo['pass'];
        $this->openConnection();
        return $this->get_link();
    }
    function openConnection(){
    $this->databaseLink = mysql_connect($this->database, $this->mysql_user, $this->mysql_pass);
    }

    function get_link(){
    return $this->databaseLink;
    }
}

/**
 * Insert an associative array into a MySQL database
 *
 * @example
 *    $data = array('field1' => 'data1', 'field2'=> 'data2');
 *    insertArr("databaseName.tableName", $data);
 */
function insertArr($tableName, $insData){
    $db = new database();
    $columns = implode(", ",array_keys($insData));
    $escaped_values = array_map('mysql_real_escape_string', array_values($insData));
    foreach ($escaped_values as $idx=>$data) $escaped_values[$idx] = "'".$data."'";
    $values  = implode(", ", $escaped_values);
    $query = "INSERT INTO $tableName ($columns) VALUES ($values)";
    mysql_query($query) or die(mysql_error());
    mysql_close($db->get_link());
}
?>

dbSettings.php

<?PHP
$dbInfo = array(
    'host'      => "localhost",
    'user'      => "root",
    'pass'      => "password"
);
?>

개인적으로 저는 배열을 json_encoding하고(필요한 탈출 등을 고려하여) 전체 로트를 적절한 크기의 텍스트/블롭 필드에 저장할 것입니다.

이를 통해 "구조화되지 않은" 데이터를 매우 쉽게 저장할 수 있지만 실제 PITA를 검색/인덱스할 수 있습니다.

간단한 json_decode는 데이터를 배열로 "폭발"시켜 줍니다.

$columns = implode(", ",array_keys($data));
$escaped_values = array_map(array($con, 'real_escape_string'),array_values($data));
$values  = implode("', '", $escaped_values);
return $sql = "INSERT INTO `reservations`($columns) VALUES ('$values')";

이것은 Shiplu Mokaddim에서 제공하는 솔루션에 대한 개선입니다.

$query = "INSERT INTO table ( " . implode(', ', array_keys($insData)) . ")
    VALUES (" . implode(', ', array_values($insData)) . ")";

배열을 데이터베이스에 삽입하기 위해 이 줄만 쓰면 됩니다.

implode(', ', array_keys($insData)): 모든 키를 문자열 형식으로 제공합니다.

implode(', ', array_values($insData)): 모든 값을 문자열 형식으로 제공합니다.

두 가지 방법이 있습니다.

  • 배열의 각 키에 대한 필드가 있는 테이블(또는 여러 개의 테이블이 함께 연결됨)을 만들고 각 필드에 배열의 해당 값을 삽입할 수 있습니다.이것이 가장 일반적인 방법입니다.
  • 한 개의 필드가 있는 테이블을 가지고 여기에 배열을 직렬화하면 됩니다.그렇게 하는 것을 권장하지 않지만 복잡한 데이터베이스 스키마를 원하지 않는 경우 유용합니다.

배열을 직렬화하면 문제를 해결할 수 있는 텍스트가 데이터베이스 열에 표시됩니다.

예를 들어 객체를 저장하기 위해 객체를 쉽게 검색할 수 있습니다.

mysql php에 배열 데이터 삽입

배열 데이터가 있습니다.그 데이터를 데이터베이스에 게시하고 싶습니다.

1: 제 어레이 데이터입니다.

stdClass Object
(
    [questions] => Array
        (
            [0] => stdClass Object
                (
                    [question_id] => 54
                    [question] => Which%20of%20the%20following%20is%20a%20rational%20number%20(s)%3F%3Cbr%20%2F%3E%0D%0A%3Cbr%20%2F%3E
                    [option_1] => %3Cimg%20align%3D%22middle%22%20%20%20src%3D%22formula%2F54%2F010779c34ce28fee25778247e127b82d.png%22%20alt%3D%22%22%20%2F%3E%3Cspan%20class%3D%22Apple-tab-span%22%20style%3D%22white-space%3A%20pre%3B%20%22%3E%09%3C%2Fspan%3E
                    [option_2] => %26nbsp%3B%3Cimg%20align%3D%22middle%22%20%20%20src%3D%22formula%2F54%2F3af35a16c371ffaaf9ea6891fb732478.png%22%20alt%3D%22%22%20%2F%3E
                    [option_3] => %26nbsp%3B%3Cimg%20align%3D%22middle%22%20%20%20src%3D%22formula%2F54%2F4a57d5766a79f0ddf659d63c7443982b.png%22%20alt%3D%22%22%20%2F%3E
                    [option_4] => %26nbsp%3BAll%20the%20above%26nbsp%3B
                    [iscorrect] => yes
                    [answerGiven] => D
                    [marksobtain] => 2
                    [timetaken] => 3
                    [difficulty_levelval] => 2
                )


   [1] => stdClass Object
                (
                    [question_id] => 58
                    [question] => %3Cdiv%3EIf%20A%20%26nbsp%3B%3A%20Every%20whole%20number%20is%20a%20natural%20number%20and%3C%2Fdiv%3E%0D%0A%3Cdiv%3E%26nbsp%3B%20%26nbsp%3BR%20%3A%200%20is%20not%20a%20natural%20number%2C%3C%2Fdiv%3E%0D%0A%3Cdiv%3EThen%20which%20of%20the%20following%20statement%20is%20true%3F%3C%2Fdiv%3E
                    [option_1] => %26nbsp%3BA%20is%20False%20and%20R%20is%20true.
                    [option_2] => A%20is%20True%20and%20R%20is%20the%20correct%20explanation%20of%20A
                    [option_3] => %26nbsp%3BA%20is%20True%20and%20R%20is%20false
                    [option_4] => %26nbsp%3BBoth%20A%20and%20R%20are%20True
                    [iscorrect] => no
                    [answerGiven] => D
                    [marksobtain] => 0
                    [timetaken] => 2
                    [difficulty_levelval] => 2
                )

        )

)

해당 데이터를 삽입하는 데 사용한 코드:

코드 ::

<?php 
 //require_once("config_new2012.php");

require("codelibrary/fb/facebook.php");
include("codelibrary/inc/variables.php");
include_once(INC."functions.php");
include_once(CLASSES."frontuser_class.php");
include_once(CLASSES."testdetails_class.php");



$data = file_get_contents('php://input');
$arr_data = explode("=",$data);
$final_data = urldecode($arr_data[1]);
$final_data2 = json_decode($final_data);


 //print_r ($final_data2);



 if(is_array($final_data2)){
echo 'i am in array ';
    $sql = "INSERT INTO p_user_test_details(question_id, question, option_1, option_2, option_3, option_4,iscorrect,answerGiven,marksobtain,timetaken,difficulty_levelval) values ";

    $valuesArr = array();
    foreach($final_data2 as $row){

        $question_id = (int) $row['question_id'];
        $question = mysql_real_escape_string( $row['question'] );
        $option_1 = mysql_real_escape_string( $row['option_1'] );
    $option_2 = mysql_real_escape_string( $row['option_2'] );
    $option_3 = mysql_real_escape_string( $row['option_3'] );
    $option_4 = mysql_real_escape_string( $row['option_4'] );
    $iscorrect = mysql_real_escape_string( $row['iscorrect'] );
    $answerGiven = mysql_real_escape_string( $row['answerGiven'] );
        $marksobtain = mysql_real_escape_string( $row['marksobtain'] );
        $timetaken = mysql_real_escape_string( $row['timetaken'] );
        $difficulty_levelval = mysql_real_escape_string( $row['difficulty_levelval'] );
        $valuesArr[] = "('$question_id', '$question', '$option_1','$option_2','$option_3','$option_4','$iscorrect','$answerGiven','$marksobtain','$timetaken','$difficulty_levelval')";
    }

    $sql .= implode(',', $valuesArr);

    mysql_query($sql) or exit(mysql_error()); 
}
else{

echo 'no one is there ';
}

같은 문제에 대해 검색해 보지만, 배열을 튜플로 추가하지 않기 위해 파일에 저장하고 싶었기 때문에 serialize() 함수와 unserialize() 함수가 필요할 수 있습니다.

이 http://www.wpfasthelp.com/insert-php-array-into-mysql-database-table-row-field.htm 보기

<?php
 function mysqli_insert_array($table, $data, $exclude = array()) {
    $con=  mysqli_connect("localhost", "root","","test");
     $fields = $values = array();
    if( !is_array($exclude) ) $exclude = array($exclude);
    foreach( array_keys($data) as $key ) {
        if( !in_array($key, $exclude) ) {
            $fields[] = "`$key`";
            $values[] = "'" . mysql_real_escape_string($data[$key]) . "'";
        }
    }
    $fields = implode(",", $fields);
    $values = implode(",", $values);
    if( mysqli_query($con,"INSERT INTO `$table` ($fields) VALUES ($values)") ) {
        return array( "mysql_error" => false,
                      "mysql_insert_id" => mysqli_insert_id($con),
                      "mysql_affected_rows" => mysqli_affected_rows($con),
                      "mysql_info" => mysqli_info($con)
                    );
    } else {
        return array( "mysql_error" => mysqli_error($con) );
    }
}

 $a['firstname']="abc";
 $a['last name']="xyz";
 $a['birthdate']="1993-09-12";
 $a['profilepic']="img.jpg";
 $a['gender']="male";
 $a['email']="abc@hightecit.com";
 $a['likechoclate']="Dm";
 $a['status']="1";
$result=mysqli_insert_array('registration',$a,'abc');
if( $result['mysql_error'] ) {
    echo "Query Failed: " . $result['mysql_error'];
} else {
    echo "Query Succeeded! <br />";
    echo "<pre>";
    print_r($result);
    echo "</pre>";
}
?>

아마도 이 질문은 복잡할 것입니다만, 분명 당신에게 그 일을 해 줄 것입니다.배열 삽입뿐만 아니라 데이터베이스 쿼리, 파일 업데이트 및 삭제를 처리하기 위해 두 개의 클래스를 만들었습니다."MySqliConnection" 클래스는 (새 개체의 중복을 방지하기 위해) db 연결 인스턴스 하나만 만드는 데 사용됩니다.

    <?php
    /**
     *
     * MySQLi database connection: only one connection is allowed
     */
    class MySqliConnection{
        public static $_instance;
        public $_connection;

        public function __construct($host, $user, $password, $database){
            $this->_connection = new MySQLi($host, $user, $password, $database);
            if (isset($mysqli->connect_error)) {
                echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
                echo $mysqli->host_info . "\n";
            }
        }

        /*
        * Gets instance of connection to database
        * @return (MySqliConnection) Object
        */
        public static function getInstance($host, $user, $password, $database){
            if(!self::$_instance){ 
                self::$_instance = new self($host, $user, $password, $database); //if no instance were created - new one will be initialize
            }
            return self::$_instance; //return already exsiting instance of the database connection
        }

        /*
        * Prevent database connection from bing copied while assignig the object to new wariable
        * @return (MySqliConnection) Object
        */
        public function getConnection(){
            return $this->_connection;
        }

        /*
        * Prevent database connection from bing copied/duplicated while assignig the object to new wariable
        * @return nothing
        */
        function __clone(){

        }
    }


    /*// CLASS USE EXAMPLE 
        $db = MySqliConnection::getInstance('localhost', 'root', '', 'sandbox');
        $mysqli = $db->getConnection();
        $sql_query = 'SELECT * FROM users;
            $this->lastQuery = $sql_query;
            $result = $mysqli->query($sql_query);
        while($row = $result->fetch_array(MYSQLI_ASSOC)){
            echo $row['ID'];
        }

    */

두 번째 "TableManager" 클래스는 조금 더 복잡합니다.위에 올린 MySqliConnection 클래스도 활용합니다.따라서 두 가지를 모두 프로젝트에 포함시켜야 합니다.Table Manager를 사용하면 삽입 업데이트 및 삭제를 쉽게 할 수 있습니다.클래스에는 읽기 및 쓰기를 위한 자리 표시자가 별도로 있습니다.

<?php

/*
* DEPENDENCIES:
* include 'class.MySqliConnection.inc'; //custom class
*
*/

class TableManager{

    private $lastQuery;
    private $lastInsertId;
    private $tableName;
    private $tableIdName;
    private $columnNames = array();
    private $lastResult = array();
    private $curentRow = array();
    private $newPost = array();

    /*
    * Class constructor 
    * [1] (string) $tableName // name of the table which you want to work with
    * [2] (string) $tableIdName // name of the ID field which will be used to delete and update records
    * @return void
    */
    function __construct($tableName, $tableIdName){
        $this->tableIdName = $tableIdName;
        $this->tableName = $tableName;
        $this->getColumnNames();
        $this->curentRow = $this->columnNames;
    }

public function getColumnNames(){
    $sql_query = 'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = "'.$this->tableName.'"';
    $mysqli = $this->connection();
    $this->lastQuery = $sql_query;
    $result = $mysqli->query($sql_query);
    if (!$result) {
        throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
    }
    while($row = $result->fetch_array(MYSQLI_ASSOC)){           
        $this->columnNames[$row['COLUMN_NAME']] = null;
    }
}

    /*
    * Used by a Constructor to set native parameters or virtual array curentRow of the class
    * [1] (array) $v
    * @return void
    */
    function setRowValues($v){

        if(!is_array($v)){
            $this->curentRow = $v;
            return true;    
        }
        foreach ($v as $a => $b) {
            $method = 'set'.ucfirst($a);
            if(is_callable(array($this, $method))){
                //if method is callable use setSomeFunction($k, $v) to filter the value
                $this->$method($b);
            }else{
                $this->curentRow[$a] = $b;
            }
        }

    }

    /*
    * Used by a constructor to set native parameters or virtual array curentRow of the class
    * [0]
    * @return void
    */
    function __toString(){
        var_dump($this);
    }

    /*
    * Query Database for information - Select column in table where column = somevalue
    * [1] (string) $column_name // name od a column
    * [2] (string) $quote_pos // searched value in a specified column
    * @return void
    */
    public function getRow($column_name = false, $quote_post = false){
        $mysqli = $this->connection();
        $quote_post = $mysqli->real_escape_string($quote_post);
        $this->tableName = $mysqli->real_escape_string($this->tableName);
        $column_name = $mysqli->real_escape_string($column_name);
        if($this->tableName && $column_name && $quote_post){
            $sql_query = 'SELECT * FROM '.$this->tableName.' WHERE '.$column_name.' = "'.$quote_post.'"';
            $this->lastQuery = $sql_query;
            $result = $mysqli->query($sql_query);
            if (!$result) {
                throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
            }
            while($row = $result->fetch_array(MYSQLI_ASSOC)){
                $this->lastResult[$row['ID']] = $row;
                $this->setRowValues($row);
            }
        }
        if($this->tableName && $column_name && !$quote_post){
            $sql_query = 'SELECT '.$column_name.' FROM '.$this->tableName.'';
            $this->lastQuery = $sql_query;
            $result = $mysqli->query($sql_query);
            if (!$result) {
                throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
            }
            while($row = $result->fetch_array(MYSQLI_ASSOC)){           
                $this->lastResult[] = $row;
                $this->setRowValues($row);
            }       
        }
        if($this->tableName && !$column_name && !$quote_post){
            $sql_query = 'SELECT * FROM '.$this->tableName.'';
            $this->lastQuery = $sql_query;
            $result = $mysqli->query($sql_query);
            if (!$result) {
                throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
            }
            while($row = $result->fetch_array(MYSQLI_ASSOC)){           
                $this->lastResult[$row['ID']] = $row;
                $this->setRowValues($row);
            }       
        }
    }


    /*
    * Connection class gets instance of db connection or if not exsist creats one
    * [0]
    * @return $mysqli
    */
    private function connection(){
        $this->lastResult = "";
        $db = MySqliConnection::getInstance('localhost', 'root', '', 'sandbox');
        $mysqli = $db->getConnection();
        return $mysqli;
    }

    /*
    * ...
    * [1] (string) $getMe
    * @return void
    */
    function __get($getMe){
        if(isset($this->curentRow[$getMe])){
            return $this->curentRow[$getMe];
        }else{
            throw new Exception("Error Processing Request - No such a property in (array) $this->curentRow", 1);
        }

    }

    /*
    * ...
    * [2] (string) $setMe, (string) $value
    * @return void
    */
    function __set($setMe, $value){
        $temp = array($setMe=>$value);
        $this->setRowValues($temp);
    }

    /*
    * Dumps the object
    * [0] 
    * @return void
    */
    function dump(){
        echo "<hr>";
        var_dump($this);
        echo "<hr>";
    }

    /*
    * Sets Values for $this->newPost array which will be than inserted by insertNewPost() function
    * [1] (array) $newPost //array of avlue that will be inserted to $this->newPost
    * @return bolean
    */
    public function setNewRow($arr){

        if(!is_array($arr)){
            $this->newPost = $arr;
            return false;   
        }
        foreach ($arr as $k => $v) {
            if(array_key_exists($k, $this->columnNames)){
                $method = 'set'.ucfirst($k);
                if(is_callable(array($this, $method))){
                    if($this->$method($v) == false){ //if something go wrong
                        $this->newPost = array(); //empty the newPost array and return flase
                        throw new Exception("There was a problem in setting up New Post parameters. [Cleaning array]", 1);
                    }
                }else{
                    $this->newPost[$k] = $v;
                }
            }else{
                $this->newPost = array(); //empty the newPost array and return flase
                throw new Exception("The column does not exsist in this table. [Cleaning array]", 1);
            }
        }

    }


    /*
    * Inserts new post held in $this->newPost
    * [0]
    * @return bolean
    */
    public function insertNewRow(){
        // check if is set, is array and is not null
        if(isset($this->newPost) && !is_null($this->newPost) && is_array($this->newPost)){
            $mysqli = $this->connection();
            $count_lenght_of_array = count($this->newPost);

            // preper insert query
            $sql_query = 'INSERT INTO '.$this->tableName.' (';
            $i = 1;
            foreach ($this->newPost as $key => $value) {
                $sql_query .=$key;
                if ($i < $count_lenght_of_array) {
                    $sql_query .=', ';
                }

                $i++;
             } 

            $i = 1;  
            $sql_query .=') VALUES (';
            foreach ($this->newPost as $key => $value) {
                $sql_query .='"'.$value.'"';
                if ($i < $count_lenght_of_array) {
                    $sql_query .=', ';
                }

                $i++;
             }  

            $sql_query .=')';
            var_dump($sql_query);
            if($mysqli->query($sql_query)){
                $this->lastInsertId = $mysqli->insert_id;
                $this->lastQuery = $sql_query;
            }

            $this->getInsertedPost($this->lastInsertId);
        }
    }   

    /*
    * getInsertedPost function query the last inserted id and assigned it to the object.
    * [1] (integer) $id // last inserted id from insertNewRow fucntion
    * @return void
    */
    private function getInsertedPost($id){
        $mysqli = $this->connection();
        $sql_query = 'SELECT * FROM '.$this->tableName.' WHERE '.$this->tableIdName.' = "'.$id.'"';
        $result = $mysqli->query($sql_query);
        while($row = $result->fetch_array(MYSQLI_ASSOC)){
            $this->lastResult[$row['ID']] = $row;
            $this->setRowValues($row);
        }       
    }

    /*
    * getInsertedPost function query the last inserted id and assigned it to the object.
    * [0]
    * @return bolean // if deletion was successful return true
    */
    public function deleteLastInsertedPost(){
        $mysqli = $this->connection();
        $sql_query = 'DELETE FROM '.$this->tableName.' WHERE '.$this->tableIdName.' = '.$this->lastInsertId.'';
        $result = $mysqli->query($sql_query);
        if($result){
            $this->lastResult[$this->lastInsertId] = "deleted";
            return true;
        }else{
            throw new Exception("We could not delete last inserted row by ID [{$mysqli->errno}] {$mysqli->error}");

        }
        var_dump($sql_query);       
    }

    /*
    * deleteRow function delete the row with from a table based on a passed id
    * [1] (integer) $id // id of the table row to be delated
    * @return bolean // if deletion was successful return true
    */
    public function deleteRow($id){
        $mysqli = $this->connection();
        $sql_query = 'DELETE FROM '.$this->tableName.' WHERE '.$this->tableIdName.' = '.$id.'';
        $result = $mysqli->query($sql_query);
        if($result){
            $this->lastResult[$this->lastInsertId] = "deleted";
            return true;
        }else{
            return false;
        }
        var_dump($sql_query);       
    }

    /*
    * deleteAllRows function deletes all rows from a table
    * [0]
    * @return bolean // if deletion was successful return true
    */
    public function deleteAllRows(){
        $mysqli = $this->connection();
        $sql_query = 'DELETE FROM '.$this->tableName.'';
        $result = $mysqli->query($sql_query);
        if($result){
            return true;
        }else{
            return false;
        }       
    }

    /*
    * updateRow function updates all values to object values in a row with id
    * [1] (integer) $id
    * @return bolean // if deletion was successful return true
    */
    public function updateRow($update_where = false){
        $id = $this->curentRow[$this->tableIdName];
        $mysqli = $this->connection();
        $updateMe = $this->curentRow;
        unset($updateMe[$this->tableIdName]);
        $count_lenght_of_array = count($updateMe);
        // preper insert query
        $sql_query = 'UPDATE '.$this->tableName.' SET ';
        $i = 1;
        foreach ($updateMe as $k => $v) {
            $sql_query .= $k.' = "'.$v.'"';
            if ($i < $count_lenght_of_array) {
                $sql_query .=', ';
            }

            $i++;
         }
        if($update_where == false){ 
            //update row only for this object id
            $sql_query .=' WHERE '.$this->tableIdName.' = '.$this->curentRow[$this->tableIdName].'';
        }else{
            //add your custom update where query
            $sql_query .=' WHERE '.$update_where.'';
        }

        var_dump($sql_query);
        if($mysqli->query($sql_query)){
            $this->lastQuery = $sql_query;
        }
        $result = $mysqli->query($sql_query);
        if($result){
            return true;
        }else{
            return false;
        }       
    }

}



/*TO DO

1 insertPost(X, X) write function to isert data and in to database;
2 get better query system and display data from database;
3 write function that displays data of a object not databsae;
object should be precise and alocate only one instance of the post at a time. 
// Updating the Posts to curent object $this->curentRow values
->updatePost();

// Deleting the curent post by ID

// Add new row to database

*/





/*
USE EXAMPLE
$Post = new TableManager("post_table", "ID"); // New Object

// Getting posts from the database based on pased in paramerters
$Post->getRow('post_name', 'SOME POST TITLE WHICH IS IN DATABASE' );
$Post->getRow('post_name');
$Post->getRow();



MAGIC GET will read current object  $this->curentRow parameter values by refering to its key as in a varible name
echo $Post->ID.
echo $Post->post_name;
echo $Post->post_description;
echo $Post->post_author;


$Task = new TableManager("table_name", "table_ID_name"); // creating new TableManager object

$addTask = array( //just an array [colum_name] => [values]
    'task_name' => 'New Post',
    'description' => 'New Description Post',
    'person' => 'New Author',
    );
$Task->setNewRow($addTask); //preper new values for insertion to table
$Task->getRow('ID', '12'); //load value from table to object

$Task->insertNewRow(); //inserts new row
$Task->dump(); //diplays object properities

$Task->person = "John"; //magic __set() method will look for setPerson(x,y) method firs if non found will assign value as it is. 
$Task->description = "John Doe is a funny guy"; //magic __set() again
$Task->task_name = "John chellange"; //magic __set() again

$test = ($Task->updateRow("ID = 5")) ? "WORKS FINE" : "ERROR"; //update cutom row with object values
echo $test;
$test = ($Task->updateRow()) ? "WORKS FINE" : "ERROR"; //update curent data loaded in object
echo $test;
*/

가장 쉬운 방법

for ($i=0; $i < count($tableData); $i++) { 

        $cost     =$tableData[$i]['cost'];
        $quantity =$tableData[$i]['quantity'];
        $price    =$tableData[$i]['price'];
        $p_id     =$tableData[$i]['p_id'];

        mysqli_query($conn,"INSERT INTO bill_details (bill_id, price, bill_date, p_id, quantity, cost) VALUES ($bill_id[bill_id],$price,$date,$p_id,$quantity,$cost)");
    }
function insertQuery($tableName,$cols,$values,$connection){
  $numberOfColsAndValues = count($cols);
  $query = 'INSERT INTO '.$tableName.' ('.getColNames($cols,$numberOfColsAndValues).') VALUES ('.getColValues($values,$numberOfColsAndValues).')';
   if(mysqli_query($connection, $query))
      return true;
   else{
      echo "Error: " . $query . "<br>" . mysqli_error($connection);
      return false;
   }
}

function getColNames($cols,$numberOfColsAndValues){
  $result = '';
  foreach($cols as $key => $val){
    $result = $result.$val.', ';
  }
    return substr($result,0,strlen($result)-2);
}


function getColValues($values,$numberOfColsAndValues){
  $result = '';
  foreach($values as $key => $val){
    $val = "'$val'";
    $result = $result.$val.', ';
  }
    return substr($result,0,strlen($result)-2);
}

탈출하여 삽입하는 가장 간단한 방법:

global $connection;
$columns = implode(", ",array_keys($array_data));
$func = function($value) {
    global $connection;
    return mysqli_real_escape_string($connection, $value);
};
$escaped_values = array_map($func, array_values($array_data));
$values  = implode(", ", $escaped_values);
$result = mysqli_query($connection, "INSERT INTO $table_name ($columns) VALUES ($values)");

이와 같은 질문을 통해 배울 수 있는 가장 중요한 것, 즉 SQL 주입을 잊지 말자.

PDO준비된 문을 사용합니다.

PDO에 대한 자습서를 보려면 여기를 클릭하십시오.

최근에,워드프레스를 배우고 있는데, 데이터베이스를 운영할 수 있는 클래스 WP_QUERY를 제공합니다.배열 또는 객체를 데이터베이스에 삽입할 수 있습니다.저는 그것이 놀랍다고 느껴져서, 그것을 성취하는 방법을 보러 갑니다.아마, 거기서 얻을 수 있는 아이디어가 있을 겁니다.주요 기능은 apply_filters 입니다.

apply_filters( $tag, $value, $key);

첫 번째 매개 변수, treat 두 번째 매개 변수를 배열로 무시할 수 있습니다. 함수는 배열을 문자열로 검사하는 것입니다.

데이터베이스에 삽입하면 다음을 볼 수 있습니다.

key     s:12:"focal_length";s:3:"190";s:3:"iso";s:3:"400";s:13:"shutter_speed";s:6:"0.0004";s:5:"title";s:0:"";}}

제 생각에는 간단한 방법은

ob_start(); //Start output buffer
print_r($var);
$var = ob_get_contents(); //Grab output
ob_end_clean(); //Discard output buffer

배열 출력은 단순 변수로 기록됩니다.

serialized() 방식으로 할 수 있습니다.

$serialized_userdata = serialize ($data); $sql = "$tableName(details) 값에 삽입('$serialized_userdata')"; $result = mysqli_query($con, $sql);

<html>
    <input type="hidden" name="item_id[]" value="<?php echo $value->item_id; ?>">
    <input type="hidden" name="cart_id[]" value="<?php echo $value->cart_id; ?>">
    <input type="hidden" name="item_price[]" value="<?php echo $TotalItemValue; ?>">
    <input type="hidden" name="order_id[]" value="<?php echo $value->cart_order_id; ?>">
    <input type="hidden" name="commision[]" value="<?php echo number_format($commissionamount); ?>">
</html>

$myarray = array();

foreach ($this->input->post('item_id') as $key => $val) {
    $myarray = [
        'item_id' => $val,
        'order_id' => $order_id[$key],
        'recon_gt_amount' => $recon_gt_amount[$key],
        'recon_gt_commision' => $recon_gt_commision[$key],
        'recon_gt_payment' => $recon_gt_payment[$key],
        'cart_id' => $cart_id[$key],
    ] ;

    $result['save_recon_finance'] = $this->productmodel->recondata_financeinsert($myarray);
}

이거 해보세요, 제가 이런 대본을 제 시스템에 사용했어요.

foreach ($insData as $insData) {
    $insdate = array();

    foreach ($insData as $insData) {
        array_push($arr, $dbname);
    }

    $sql = "INSERT INTO tblname (uid, first_name, last_name,email,link)
        VALUES ('$uid', '$first_name', '$last_name', '$email', '$link')";

    if ($conn->query($sql) === TRUE) {
        echo "Successfully insert into db";
    } else {
        echo "Please try again" . "<br>" . $conn->error;
    }
}

답변 기준 [https://stackoverflow.com/a/10054657/7404511 ]

여기 표준 MySQL 삽입 문이 있습니다.

INSERT INTO TABLE1(COLUMN1, COLUMN2, ....) VALUES (VALUE1, VALUE2..)

fbdata라는 이름의 표가 있고 배열의 키에 표시된 열이 있는 경우 이 작은 토막글을 삽입할 수 있습니다.배열이 이 문으로 변환되는 방법은 다음과 같습니다.

견적을 명시적으로 추가하는 이 솔루션을 사용합니다.'string'구체적으로nullnull 값의 경우:

$columns = implode(", ",array_keys($insData));
$escaped_values = array_map(
    function($value) {
        if (is_string($value)) {
            return "'" . $mysqli->real_escape_string($value) . "'";
        }
        if (is_null($value)) {
            return 'null';
        }
        return $value;
    },
    array_values($insData)
);
$values  = implode(", ", $escaped_values);
$sql = "INSERT INTO `fbdata`($columns) VALUES ($values)";
                                    $count = count($data);

                                    for($i=0; $i<$count; $i++){ 
                                        $name = $data[$i]['name'];
                                        $web_id = $data[$i]['web_id'];
                                        $status = $data[$i]['status'];
                                        $sql = "INSERT INTO pws_xdata_chiefcomplain(name, web_id,status) VALUES (:name,:web_id,:status)";
                                        $stmt = $this->conn->prepare($sql);
                                        $result= $stmt->execute([
                                                'name' =>$name,
                                                'web_id' =>$web_id,
                                                'status' =>$status,
                                        ]);
                                         
                                      } 

언급URL : https://stackoverflow.com/questions/10054633/insert-array-into-mysql-database-with-php

반응형