【问题标题】:Insert multi-dimensional Array with both strings and numbers into MySQL将包含字符串和数字的多维数组插入 MySQL
【发布时间】:2014-01-05 21:25:35
【问题描述】:

我见过许多使用 foreach 和 implode 函数循环遍历数组的示例,以构建 MySQL 插入查询的 sql 字符串。但是,所有这些示例都假定 Array 中的所有值和 MySQL 表中的所有列都是字符串或数字。有没有办法做类似的事情,但是使用一个同时包含字符串和数字的数组,并且要插入到具有字符串和数字列的 MySQL 表中?

$insertArr[] = array(
        'order_id' => $orderID, 
        'user_id' => $userID,         
        'price' => $price, 
        'quantity' => $quantity);

$colNames = "( " . implode(", ",array_keys($insertArr[0])) . " )";
foreach ( $insertArr as $row )
{        
    $colValuesArr[] = "( '" . implode("', '", $row) . "' )";
}
$colValues = implode(", ", $colValuesArr);
$strsql = "INSERT INTO tbl_orders $colNames 
            VALUES $colValues";

上面的代码不能正常工作,因为order_id 和user_id 是字符串,而price 和quantity 是数字。用引号和逗号爆破它假定所有值都是字符串,不带引号爆破它假定所有值都是数字。有没有一种方法,无需遍历数组中的每个元素,就可以做到这一点?

【问题讨论】:

  • 变量 $strsql 的 SQL 语法无效。这可以解释为什么代码不起作用。
  • MySQL 可以很好地引用数字。如果你想保持简单,只需引用所有内容。 (但请记住转义您的数据!)或者,查看准备好的语句;从长远来看,它们会让你的事情变得更容易。
  • Gordon Linoff,$strsql SQL 语法有什么问题?这对我来说似乎很好。我打印了,看不出有什么问题。你能说得更具体点吗?

标签: php mysql sql arrays


【解决方案1】:

假设这是您想要处理事情的方式,并且您不想循环遍历数组或使用准备好的语句,我认为这应该可行。我重新格式化了您的代码,但整体逻辑仍然完好无损。我添加的逻辑基本上是创建两个单独的数组。一个用于数值。另一个用于文本值:

// Test data.
$orderID = 'testorderid';
$userID = 'testuserid';
$price = 7.99;
$quantity = 2;

// Create the text values array.
$insertArrText[] = array('order_id' => $orderID, 'user_id' => $userID);

// Create the numerical values array.
$insertArrNumerical[] = array('price' => $price, 'quantity' => $quantity);

// Get the array keys & merge them into one combined array.
$array_keys = array_merge(array_keys($insertArrText[0]), array_keys($insertArrNumerical[0]));

// Set the column names.
$colNames = "( " . implode(", ", $array_keys) . " )";

// Loop through the '$insertArrText'
foreach ($insertArrText as $key => $row ) {

  // Set the numerical values.
  $numerical_values = implode(", ", $insertArrNumerical[$key]);

  // Set the text values.
  $text_values = "'" . implode("', '", $row) . "'";

  // Set the column values array.
  $colValuesArr[] = "(" . $text_values . "," . $numerical_values . ")";
}

// Set the column values string.
$colValues = implode(", ", $colValuesArr);

// Create the MySQL query.
$strsql = "INSERT"
        . " INTO tbl_orders " . $colNames
        . " VALUES " . $colValues
        ;

// Echo the output for testing.
echo $strsql;

该脚本的输出是:

INSERT INTO tbl_orders ( order_id, user_id, price, quantity ) VALUES ('testorderid', 'testuserid',7.99, 2)

EDIT 这是使用gettype 检测字符串类型的重新设计。更加灵活和健壮。这当然是使用测试数据,但应该很容易适应现实世界的场景。

// Test data.
$orderID = 'testorderid';
$userID = 'testuserid';
$price = 7.99;
$quantity = 2;

// Create an array map based on strings & MySQL DB field values.
$array_map = array();
$array_map['orderID'] = 'order_id';
$array_map['userID'] = 'user_id';
$array_map['price'] = 'price';
$array_map['quantity'] = 'quantity';

// Create the text arrays.
$insertArrText = array();
$insertArrNumerical = array();

// Set arrays for text and numberical types.
$text_types = array('string');
$numerical_types = array('double','integer');

// Lopop through the array map & assign values based on type.
foreach ($array_map as $array_map_key => $array_map_value) {
  if (in_array(gettype($$array_map_key), $text_types)) {
    $insertArrText[0][$array_map_value] = $$array_map_key;
  }
  else if (in_array(gettype($$array_map_key), $numerical_types)) {
    $insertArrNumerical[0][$array_map_value] = $$array_map_key;
  }
}

// Get the array keys & merge them into one combined array.
$array_keys = array_merge(array_keys($insertArrText[0]), array_keys($insertArrNumerical[0]));

// Set the column names.
$colNames = "( " . implode(", ", $array_keys) . " )";

// Loop through the '$insertArrText'
foreach ($insertArrText as $key => $row ) {

  // Set the numerical values.
  $numerical_values = implode(", ", $insertArrNumerical[$key]);

  // Set the text values.
  $text_values = "'" . implode("', '", $row) . "'";

  // Set the column values array.
  $colValuesArr[] = "(" . $text_values . "," . $numerical_values . ")";
}

// Set the column values string.
$colValues = implode(", ", $colValuesArr);

// Create the MySQL query.
$strsql = "INSERT"
        . " INTO tbl_orders " . $colNames
        . " VALUES " . $colValues
        ;

// Echo the output for testing.
echo $strsql;

这段代码的输出是:

INSERT INTO tbl_orders ( order_id, user_id, price, quantity ) VALUES ('testorderid', 'testuserid',7.99, 2)

【讨论】:

  • 如果仅用于特定目的,这可能会起作用。但是,我正在尝试构建一个可以随时使用的函数,并且每次数组可能是不同的、不同的值类型。
  • 那么,如何使用gettype 来确定一个值是字符串还是整数,然后根据该值将其放入文本或数字数组中?
  • 你会如何使用准备好的语句?
  • 问别人,因为准备好的陈述不是我的答案。
  • gettype 是一个选项,因为我可以在第一行执行此操作,因为假设所有接下来的行都将具有相同的类型。这样我就不必遍历数组中的每个元素,只需遍历第一行。我会试试的。
【解决方案2】:

使用array_map:

$row = array_map(function ($a) {
  if (is_numeric($a)) return $a;
  else return "'".$a."'";
},$row);

假设您的数据是安全的,否则请使用 mysql_real_escape 之类的内容或使用 PDO 准备好的语句。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-11
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-06
    • 2021-04-05
    • 1970-01-01
    相关资源
    最近更新 更多