php - 使用 pdo 在数据库中插入多行

标签 php mysql pdo

insert into test (sometext) values ("?"),("?")
$a= array("weird' text","sdfa");

我想使用绑定(bind)参数将文本插入到列 sometext 中的表 test 中,并且我不希望循环中的执行语句。 我无法在 ("?"),( “?”) 形式,因为查询可能会崩溃,因为文本可以由引号组成。

那么有没有办法在 one(1) 执行语句中使用 PDO 来实现此目的?

最佳答案

I cannot implode the array in ("?"),("?") form as the query might crash coz the text can be composed of quotes.

准备好的语句是为了解决引用/转义问题。

此语法错误1:

insert into test (sometext) values ("?"),("?")

您不必用引号将参数括起来,您必须以这种形式编写查询:

INSERT INTO test (sometext) VALUES (?),(?)

然后,您可以使用 implode() 而不必担心引号:

$a     = array( "weird' text", "sdfa" );
$query = "INSERT INTO test (sometext) VALUES (" . implode( "),(", array_fill( 0, count( $a ), "?" ) ) . ")";
$stmt  = $db->prepare( $query );
$stmt->execute( $a );

作为替代方案,您可以使用 substrstr_repeat 而不是 implode:

$query = "INSERT INTO test (sometext) VALUES " . substr( str_repeat( "(?),", count( $a ) ), 0, -1 );
<小时/>

1 使用 insert into test (sometext) value ("?"),("?") 您可以在字段中插入两个问号。

关于php - 使用 pdo 在数据库中插入多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36570926/

相关文章:

php - PDO 对象不在函数范围内

php - 如果特定行数据尚未在同一日期插入,如何检查和插入数据

php - mysql换行格式化

php - 从 MySQL 表获取数据到 PHP 时,第一条数据不显示

mysql - 类图: How to show a user can assign role to another user?

MySQL插入一个选择计数

php - 警告:mysqli_error()期望恰好有1个参数,在register.php文件中给出的0个参数

php - PHP 中的 MySQL : Close connection at end of script?

mysql - Node js : check mysql connection before a query

php - 无法使用 php pdo 验证 MySQL 数据库