简体   繁体   English

使用 PHP 将数组插入 MySQL 数据库

[英]Insert array into MySQL database with PHP

I have the following array I want to store in my database...我有以下数组我想存储在我的数据库中......

$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,
);

I've tried searching google on how to do this and all I can find is information stating my array needs to be split, before inserting into the table.我已经尝试在谷歌上搜索如何执行此操作,我所能找到的只是说明我的数组在插入表之前需要拆分的信息。 Is this correct?这个对吗? Sorry for the naivity, very new to php.很抱歉天真,php 很新。

You can not insert an array directly to MySQL as MySQL doesn't understand PHP data types.您不能将数组直接插入MySQL ,因为MySQL不理解PHP数据类型。 MySQL only understands SQL . MySQL只理解SQL So to insert an array into a MySQL database you have to convert it to a SQL statement.因此,要将数组插入 MySQL 数据库,您必须将其转换为 SQL 语句。 This can be done manually or by a library.这可以手动完成或由图书馆完成。 The output should be an INSERT statement. output 应该是一个INSERT语句。

Update for PHP7 PHP7 更新

Since PHP 5.5 mysql_real_escape_string has been deprecated and as of PHP7 it has been removed .自 PHP 5.5 以来, mysql_real_escape_string已被弃用,从 PHP7 开始,它已被删除 See: php.net's documentation on the new procedure.请参阅: php.net 关于新过程的文档。


Original answer:原答案:

Here is a standard MySQL insert statement.这是一个标准的 MySQL 插入语句。

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

If you have a table with name fbdata with the columns which are presented in the keys of your array you can insert with this small snippet.如果您有一个名为fbdata的表,其中的列显示在数组的键中,您可以使用这个小片段插入。 Here is how your array is converted to this statement.以下是您的数组如何转换为该语句。

$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')";

There are a number of different ways... I will give you an example of one using prepared statements:有许多不同的方法......我会给你一个使用准备好的语句的例子:

$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);

I'm cheating here and assuming the keys in your first array are the column names in the SQL table.我在这里作弊并假设您的第一个数组中的键是 SQL 表中的列名。 I'm also assuming you have PDO available.我还假设您有可用的 PDO。 More can be found at http://php.net/manual/en/book.pdo.php更多信息请访问http://php.net/manual/en/book.pdo.php

Here is my full solution to this based on the accepted answer.这是我基于已接受的答案对此的完整解决方案。

Usage example:使用示例:

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

db.php数据库.php

<?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 dbSettings.php

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

Personally I'd json_encode the array (taking into account any escaping etc needed) and bung the entire lot into an appropriately sized text/blob field.我个人会对数组进行 json_encode(考虑到所需的任何 escaping 等)并将整个批次塞入适当大小的文本/blob 字段中。

It makes it very easy to store "unstructured" data but a real PITA to search/index on with any grace.它使存储“非结构化”数据变得非常容易,但真正的 PITA 可以轻松搜索/索引。

A simple json_decode will "explode" the data back into an array for you.一个简单的 json_decode 将为您将数据“分解”回数组。

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

Only need to write this line to insert an array into a database.只需要写这一行就可以将一个数组插入到数据库中。

implode(', ', array_keys($insData)) : Gives you all keys as string format implode(', ', array_keys($insData))以字符串格式为您提供所有键

implode(', ', array_values($insData)) : Gives you all values as string format implode(', ', array_values($insData))以字符串格式为您提供所有值

$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')";

This is improvement to the solution given by Shiplu Mokaddim这是对 Shiplu Mokaddim 给出的解决方案的改进

You have 2 ways of doing it:你有两种方法可以做到:

  • You can create a table (or multiple tables linked together) with a field for each key of your array, and insert into each field the corresponding value of your array.您可以为数组的每个键创建一个表(或链接在一起的多个表),并在每个字段中插入数组的相应值。 This is the most common way这是最常见的方式
  • You can just have a table with one field and put in here your array serialized .您可以只拥有一个包含一个字段的表,然后将序列化的数组放在这里。 I do not recommend you do do that, but it is useful if you don't want a complex database schema.我不建议您这样做,但如果您不想要复杂的数据库模式,它会很有用。

Serialize the array and you'll have a text on your database column, that will solve the problem.序列化数组,您将在数据库列中有一个文本,这将解决问题。

I do that, for instance to save objects, that way I can retrieve them easily.我这样做是为了保存对象,这样我就可以轻松检索它们。

Insert array data into mysql php插入数组数据 mysql php

I Have array data.. I want post that data in database我有数组数据..我想在数据库中发布该数据

1: this is my array data: 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
                )

        )

)

code used i used to insert that data:我用来插入该数据的代码:

Code::代码::

<?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 ';
}

I search about the same problem, but I wanted to store the array in a filed not to add the array as a tuple, so you may need the function serialize() and unserialize().我搜索了同样的问题,但我想将数组存储在一个字段中而不是将数组添加为元组,因此您可能需要 function serialize() 和 unserialize()。

See this http://www.wpfasthelp.com/insert-php-array-into-mysql-database-table-row-field.htm看到这个http://www.wpfathelp.com/insert-php-array-into-mysql-database-table-row-field.htm

Maybe it will be to complex for this question but it surely do the job for you.也许这个问题会很复杂,但它肯定能为您完成工作。 I have created two classes to handle not only array insertion but also querying the database, updating and deleting files.我创建了两个类,不仅可以处理数组插入,还可以查询数据库、更新和删除文件。 "MySqliConnection" class is used to create only one instance of db connection (to prevent duplication of new objects). "MySqliConnection" class 用于仅创建一个数据库连接实例(以防止新对象重复)。

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

    */

The second "TableManager" class is little bit more complex.第二个“TableManager”class 有点复杂。 It also make use of the MySqliConnection class which I posted above.它还使用了我在上面发布的 MySqliConnection class。 So you would have to include both of them in your project.所以你必须将它们都包含在你的项目中。 TableManager will allow you to easy make insertion updates and deletions. TableManager 将允许您轻松地进行插入更新和删除。 Class have separate placeholder for read and write. Class 有单独的占位符用于读取和写入。

<?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;
*/
<?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>";
}
?>

most easiest way最简单的方法

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);
}

The simplest method to escape and insert:最简单的转义和插入方法:

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)");

Let's not forget the most important thing to learn out of a question like this: SQL Injection .让我们不要忘记从这样的问题中学习的最重要的事情: SQL Injection

Use PDO and prepared statements .使用PDO准备好的语句

Click here for a tutorial on PDO.单击此处获取有关 PDO 的教程。

Recently,I'm learning Wordpress,it provide a class WP_QUERY to operate the database.最近在学习Wordpress,它提供了一个class WP_QUERY来操作数据库。 You can insert array or object to the database.I feel it is amazing,so I go to see how to achieve it.Maybe,some ideas you can get from it.The main function is: apply_filters .可以向数据库中插入数组或者object。感觉很神奇,所以我go看看怎么实现的。也许,你可以从中得到一些想法。主要的function是: apply_filters

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

you can ignore the first parameter,treat the second parameter as array,what the function do is sanitizing the array into string.您可以忽略第一个参数,将第二个参数视为数组,function 所做的是将数组清理为字符串。

after inserting into the database,you can see this:插入数据库后可以看到:

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:"";}}

I think the simple method would be using我认为简单的方法是使用

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

and your array output will be recorded as a simple variable你的数组 output 将被记录为一个简单的变量

You guys can try this, I used this kind of script in my system你们可以试试这个,我在我的系统中使用了这种脚本

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;
    }
}
<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);
}

We can Do it using serialized() method我们可以使用 serialized() 方法来完成

$serialized_userdata = serialize($data); $serialized_userdata = 序列化($data); $sql = "insert into $tableName (details) value ('$serialized_userdata')"; $sql = "insert into $tableName (details) value ('$serialized_userdata')"; $result = mysqli_query($con, $sql); $result = mysqli_query($con, $sql);

This based on answer [https://stackoverflow.com/a/10054657/7404511]这基于答案 [https://stackoverflow.com/a/10054657/7404511]

Here is a standard MySQL insert statement.这是一个标准的 MySQL 插入语句。

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

If you have a table with name fbdata with the columns which are presented in the keys of your array you can insert with this small snippet.如果您有一个名为 fbdata 的表,其中的列显示在数组的键中,您可以使用这个小片段插入。 Here is how your array is converted to this statement.以下是您的数组如何转换为该语句。

I'd use this solution where explicitly add quotes 'string' and explicily put null for null value:我会使用此解决方案,其中明确添加引号'string'并明确将null用于 null 值:

$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,
                                        ]);
                                         
                                      } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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