【问题标题】:PHP Multiple Value String in Single Query单个查询中的 PHP 多值字符串
【发布时间】:2014-08-09 02:35:06
【问题描述】:

我有一个 HTML 文本区域,每行包含 100-1000 个用户:密码对,我现在想使用 PDO 将它们插入我的数据库中。由于我对 PDO 非常陌生,因此我需要您的帮助,也许您知道一些优化方法,以实现更快的插入或更简单的代码。

这可能是我的 textarea 的内容:

User1:Pass1
User2:Pass2
User3:Pass3

这就是我尝试过的:

$query = "INSERT INTO Refs (username,password,targetLevel,idOrder) VALUES :accounts";
$ps_insert = $db->prepare($query);

//this iy my textarea from the form
$accounts = $_POST['accounts']; 

// Convert Accountaray to user:password tuples
// Write the SQL Statement of the VALUE pairs into
// an string array in this style '(user,password)'  
$msg = explode("\n", $accounts);
for($i = 0; $i < sizeof($msg); $i++) 
{ 
        list($user, $pass) = explode(":", $msg[$i]);
        if(!empty($user)){
            $insert_parts[$i]="('" . $user . "','" . $pass . "',10,0)";
        }
}

// Content of this string is: (user1,pass1,10,0), (user2,pass2,10,0), (user3,pass3,10,0)
$accountInserts = implode(',', $insert_parts);
$ps_insert->bindParam(':accounts', $insert_parts);
$ps_insert->execute();

之前我使用了“众所周知的”MySQL 查询,但我想使用 PDO,因为我会将它用于其他事情以及常见的准备语句。感谢您的帮助!

问题:MySQL 插入不起作用。我应该如何解决这个问题?对(速度/代码)优化有何建议?

【问题讨论】:

标签: php mysql sql pdo


【解决方案1】:

绑定参数指定单个标量值。在您的INSERT 语句中,绑定占位符:account 表示分配给一列的值。您只能通过绑定变量提供数据值,不能包含要解释为 SQL 文本的括号和逗号。

如果您为绑定占位符提供值,例如:

"('foo','bar',7,1)"

这将被解释为一个 single 值,不会被“视为”为 SQL 文本,而只是一个字符串,即要分配给单个列的值。


您需要如下所示的 SQL 语句:

INSERT INTO Refs (username,password,targetLevel,idOrder) VALUES (:v1, :v2, :v3, :v4)

您需要为每个绑定占位符提供一个值。

【讨论】:

  • 但是它不是具有多个值的单个查询。当我添加 10k 查询时,我需要等待 2-3 秒,直到此查询完成。还是我误解了您的解决方案?
猜你喜欢
  • 2014-10-11
  • 2018-09-29
  • 2013-03-29
  • 1970-01-01
  • 2017-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多