简体   繁体   English

(PHP)数组中的键值对数目未知,如何在sql查询中使用它们?

[英](PHP) I have an unknown number of key value pairs in an array, how can I use them in an sql query?

I am trying to make an inventory / invoice web application. 我正在尝试制作库存/发票Web应用程序。 The user enters information such as order ID, date, order total, and then each of the products bought along with their respective quantity. 用户输入诸如订单ID,日期,订单总数之类的信息,然后输入所购买的每种产品及其各自的数量。 I'm using PDO for the sql queries. 我正在对SQL查询使用PDO。

I do not know in advance how many unique products are going to be in an invoice so I have an associative array that stores the products and their quantities (product name is used as the key) when the form is submitted. 我事先不知道发票中将包含多少个独特的产品,因此我有一个关联数组,用于在提交表单时存储产品及其数量(使用产品名称作为关键字)。

On submit a prepared statement is built/executed. 提交后,将构建/执行准备好的语句。
Right now I have the order_id, date, and order_total query done. 现在,我已经完成了order_id,日期和order_total查询。

$stmt = $connection->prepare("INSERT INTO table_1 (order_id, order_date, order_total) VALUES ('$orderid', '$date', '$total_cost')");
$stmt->execute();

That part is simple enough. 这部分很简单。 The aim of the other query is the following. 其他查询的目的如下。

$testStmt = $connection->prepare("INSERT INTO table_2 (keys from the assoc array are listed here) VALUES (values from the assoc arrays are listed here)");
$testStm->execute();

My array would end up looking like this once the user inputs some products: 一旦用户输入了一些产品,我的阵列将最终看起来像这样:

$array
    (
        "product1" => quantity1
        "product2" => quantity2

    )

The idea I have had so far is to make a string for columns that need to be included in the sql query and then a string for the values for the sql query. 到目前为止,我的想法是为需要包含在sql查询中的列创建一个字符串,然后为sql查询的值创建一个字符串。 Then iterate through the array and append the keys and values to the respective strings in such a way that I could use them in the sql query. 然后遍历数组并将键和值附加到相应的字符串,以使我可以在sql查询中使用它们。 I haven't gotten it to work and am worried that it could open myself up to sql injection (I am still quite unfamiliar with sql injection so I have been trying to read up on it). 我还没有开始使用它,并且担心它可能会使自己对sql注入开放(我仍然不太熟悉sql注入,因此我一直在尝试阅读它)。

$columns;
$values_input;

foreach($assoc_array as $product => $quant)
{
     $columns .= "' " . $product . "', ";
     $values_input .= "' " . $quant . "', ";
}

The idea being that $columns and $values_input string would end up containing all the appropriate column names and the quantities to be entered into those columns. 这样的想法是$ columns和$ values_input字符串最终将包含所有适当的列名称以及要输入到这些列中的数量。 Then I figured I could be able to use those strings as part of the SQL query. 然后我认为我可以在SQL查询中使用这些字符串。 Something like this. 这样的事情。

INSERT INTO $columns VALUES $values_input 

I'd appreciate any help or insight. 我将不胜感激。 If I'm way off here or doing something in a retarded way feel free to shout about it, I'd rather fix a screw up than continue on with it if that's the case. 如果我不在这里或以某种迟钝的方式做事,可以大声疾呼,我宁愿自己动手,也不要继续做下去。

Since you are trying to make an inventory/invoice application, do you happen to have a product database? 由于您尝试创建库存/发票申请,因此您碰巧有一个产品数据库吗? If you do, you may want to use the product id instead of the product names as key. 如果这样做,则可能要使用产品ID而不是产品名称作为键。 As product names sound like there could be duplicates or can change. 产品名称听起来可能重复或更改。 If product name changes, you will have problems querying. 如果产品名称更改,查询将会遇到问题。

Do you accept products not in db to be entered into the invoice? 您是否接受不在db中的产品输入发票? If so, it adds some complications. 如果是这样,它将增加一些复杂性。

On SQL injections, you should sanitize input before using it for queries. 在SQL注入中,应先清理输入,然后再将其用于查询。 Read: What's the best method for sanitizing user input with PHP? 阅读: 用PHP清理用户输入的最佳方法是什么?

Most modern frameworks have many built in protections against SQL injections if you do not query manually. 如果您不手动查询,大多数现代框架都有许多内置的防止SQL注入的保护措施。 So consider using them. 因此,请考虑使用它们。

Many of them use active record pattern see: http://www.phpactiverecord.org/projects/main/wiki/Basic_CRUD (So you don't have to deal with writing queries manually like you do.) 其中许多使用活动记录模式,请参见: http : //www.phpactiverecord.org/projects/main/wiki/Basic_CRUD (因此,您不必像手动那样处理手动编写查询。)

An example of active record in a framework: https://www.codeigniter.com/user_guide/database/query_builder.html 框架中活动记录的示例: https : //www.codeigniter.com/user_guide/database/query_builder.html

You are already using PDO, which is a good thing if you want to protect yourself from SQL injection. 您已经在使用PDO,如果您想保护自己免受SQL注入的侵害,这是一件好事。 You are even trying to prepare your statement, but since you are not binding any parameters, one could argue if that is really what you are doing. 您甚至试图准备语句,但是由于您没有绑定任何参数,因此有人可能会争辩说这是否确实在做。 Example 5 on the PHP docs page is in fact pretty close to what you want to do. 实际上,PHP docs页面上的示例5与您要执行的操作非常接近。 Allow me to adapt it to your use case: 请允许我根据您的用例进行调整:

// create a placeholders string looking like "?, ?, ..., ?"
$placeholders = implode(',', array_fill(0, count($params), '?'));

// prepare the statement
$qry = $connection->prepare("INSERT INTO table_2 ($params) VALUES ($params)");

// bind the parameters to the statement. (We first need all columns, then all values)
$qry->execute(array_merge(array_keys($params), array_values($params)));

This should result in a query that looks exactly like your first example, but with a dynamic number of columns, or parameters. 这将导致查询看起来与您的第一个示例完全一样,但是具有动态的列数或参数数。 And since you are preparing your statement and binding the parameters on execution, PDO should handle all quoting and escaping to prevent SQL injection. 而且由于您正在准备语句并在执行时绑定参数,所以PDO应该处理所有引用和转义以防止SQL注入。

As a side note, your table structure seems a bit of to me. 附带一提,您的表格结构对我来说似乎有点。 I don't think you normalized your data correctly, though it is a bit hard to tell with the table names you are using. 我认为您无法正确规范化数据,尽管很难用您正在使用的表名来区分。 I believe your structure should look something like this, and I fear it doesn't: 我相信您的结构应该看起来像这样,但我担心它不会:

TABLE orders (id, date, total, client_id)
TABLE products (id, name, price, ...)
TABLE order_lines (id, order_id, product_id, quantity)
TABLE clients (...)

The exact structure obviously depends on your use case, but I believe this is about the simplest structure you can get away with if you want to build an order system that you can easily query and that can serve as a base for possible expansion in the future. 确切的结构显然取决于您的用例,但是我认为,这是关于您想要构建一个可以轻松查询并可以作为将来可能扩展的基础的订单系统的最简单结构。 。

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

相关问题 如何从php的会话数组中获取未知数量的元素,并将其用作JavaScript中的单独变量? - How do I take an unknown number of elements from a session array in php and use them as separate variables in JavaScript? PHP:如何有选择地翻转数组键/值对? - PHP: How do I flip array key/value pairs selectively? 如何分解键值对并在查询中使用它们 - how to explode key value pairs and use them in query 如何创建具有键值对的数组? - How can I create an array with key value pairs? 如何在PHP中为MySQL查询提取数组键的值 - How can I extract the value of an array key in PHP for MySQL query php:我有5个数组,我怎么能把它们作为一个? - php: i have 5 array, how can i make them as one? 如何获取在php中检查了哪些清单项并使用它们进行sql查询? - How can I obtain which checklist items are checked in php and use them to make a sql query? PHP中的SQL查询,我可以将它们组合吗? - SQL QUERY IN PHP, can i combine them? 在MongoDB的文档中,我有一个键/值,使得该值是一个关联数组(使用php插入); 怎么迭代 - in a document of MongoDB, i have a key/value such that value is an association array (inserted using php); how can iterate 如何使用 PHP array_combine 和 for 循环添加可变数量的键值对? - How do I add variable numbers of key value pairs using PHP array_combine and for-loop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM