PHP MySql:更新表与数组的值组合

时间:2017-11-16 23:32:18

标签: php mysql arrays foreach

我有以下数组

Array
(
["1074d0"] => "160.16"
["19f726"] => "234.32"
["1072ba"] => "256.88"
["183444"] => "325.42"
["1071bf"] => "342.22"
["112438"] => "353.30"
["1b326e"] => "365.78"
["15d8ab"] => "372.84"
["19d885"] => "395.72"
["193e61"] => "478.66"
["10aab2"] => "503.36"
["107155"] => "543.39"
["110669"] => "584.61"
["189b95"] => "584.61"
["16d78f"] => "597.70"
["18dd7d"] => "601.63"
["110851"] => "601.63"

)

使用以下代码获得(在用户的帮助下):

$codici_hotel_arr = $codici_price_arr = [];   
foreach($data_destin['results'] as $key=>$val) {         
$codici_hotel_arr[] = '"' . $val['hotel_code'] . '"'; 
$codici_price_arr[] = '"' . $val['products'][0]['price'] . '"'; }  
$result = array_combine($codici_hotel_arr,$codici_price_arr);           
print '<pre>';                                                  
print_r($result);                                                    
print '</pre>';

现在我想通过foreach更新表的值;更确切地说,我应该做那样的事情:

UPDATE table_demo SET price =&#34; 160.16&#34; WHERE id =&#34; 1074d0&#34 ;;

UPDATE table_demo SET price =&#34; 234.32&#34; WHERE id =&#34; 19f726&#34 ;;

UPDATE table_demo SET price =&#34; 256.88&#34; WHERE id =&#34; 1072ba&#34 ;;

等...

1 个答案:

答案 0 :(得分:0)

嗯,这是我的版本。它已激活error reportinginternal reporting functions。代码prepares是一个UPDATE语句。需要进行此准备,以避免SQL注入。对语句的标记(?)绑定了两个绑定变量($bindPrice&amp; $bindCode)。此外,阵列循环通过。在每个迭代步骤中,将当前数组值($price&amp; $code)分配给绑定变量,并执行该语句。最后准备好的声明已经结束。

<?php

// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'dbname');
define('USERNAME', 'user');
define('PASSWORD', 'pass');

// Error reporting.
error_reporting(E_ALL);
ini_set('display_errors', 1); // Set it to 0 on a live server!

/**
 * Enable internal report functions. This enables the exception handling, 
 * e.g. mysqli will not throw PHP warnings anymore, but mysqli exceptions 
 * (mysqli_sql_exception). They are catched in the try-catch block.
 * 
 * MYSQLI_REPORT_ERROR: Report errors from mysqli function calls.
 * MYSQLI_REPORT_STRICT: Throw a mysqli_sql_exception for errors instead of warnings. 
 * 
 * See: http://php.net/manual/en/class.mysqli-driver.php
 * See: http://php.net/manual/en/mysqli-driver.report-mode.php
 * See: http://php.net/manual/en/mysqli.constants.php
 */
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$codePricesArray = [
    "1074d0" => "160.16",
    "19f726" => "234.32",
    "1072ba" => "256.88",
    "183444" => "325.42",
    "1071bf" => "342.22",
    "112438" => "353.30",
    "1b326e" => "365.78",
    "15d8ab" => "372.84",
    "19d885" => "395.72",
    "193e61" => "478.66",
    "10aab2" => "503.36",
    "107155" => "543.39",
    "110669" => "584.61",
    "189b95" => "584.61",
    "16d78f" => "597.70",
    "18dd7d" => "601.63",
    "110851" => "601.63",
];

/**
 * Create a new db connection.
 * 
 * @see http://php.net/manual/en/mysqli.construct.php
 */
$connection = new mysqli(HOST, USERNAME, PASSWORD, DATABASE, PORT);

/*
 * The SQL statement to be prepared. Notice the so-called markers, 
 * e.g. the "?" signs. They will be replaced later with the 
 * corresponding values when using mysqli_stmt::bind_param.
 * 
 * See: http://php.net/manual/en/mysqli.prepare.php
 */
$sql = 'UPDATE `table_demo` SET price = ? WHERE code = ?';

/*
 * Prepare the SQL statement for execution - ONLY ONCE.
 * 
 * See: http://php.net/manual/en/mysqli.prepare.php
 */
$statement = $connection->prepare($sql);

/*
 * Bind variables for the parameter markers (?) in the 
 * SQL statement that was passed to prepare(). The first 
 * argument of bind_param() is a string that contains one 
 * or more characters which specify the types for the 
 * corresponding bind variables.
 * 
 * See: http://php.net/manual/en/mysqli-stmt.bind-param.php
 */
$statement->bind_param('ds', $bindPrice, $bindCode);

foreach ($codePricesArray as $code => $price) {
    // Assign iteration values ($code, $price) to the binded variables ($bindCode, $bindPrice).
    $bindPrice = $price;
    $bindCode = $code;

    /*
     * Execute the prepared SQL statement.
     * When executed, any parameter markers which exist ("?") will 
     * automatically be replaced with the appropriate data of the
     * binded variables.
     * 
     * See: http://php.net/manual/en/mysqli-stmt.execute.php
     */
    $executed = $statement->execute();
}

/*
 * Close the prepared statement. It also deallocates the statement handle.
 * If the statement has pending or unread results, it cancels them 
 * so that the next query can be executed.
 * 
 * See: http://php.net/manual/en/mysqli-stmt.close.php
 */
$statementClosed = $statement->close();

我使用了以下表格结构:

CREATE TABLE `table_demo` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `code` varchar(100) DEFAULT NULL,
  `price` double DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

请注意,id列是整数列,主键和自动增量。它不包含酒店代码,因为出于多种原因,在数据标识列中保存字符串并不是一个好主意(如id)。这就是为酒店代码创建列code的原因。

祝你好运。

P.S:由于您只是在谈论更新数据,因此我提供了仅涉及此操作类型的解决方案。