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 );
作为替代方案,您可以使用 substr
和 str_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/