Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
492 views
in Technique[技术] by (71.8m points)

php - Laravel complains about query with duplicate named parameters

When I do (in laravel):

<?php
DB::select('SELECT * FROM my_table WHERE id = :id || id = :id', [
    'id' => 1,
]);

It says:

SQLSTATE[HY093]: Invalid parameter number (SQL: SELECT * FROM my_table WHERE id = :id || id = :id)

But when I do (in pure php):

<?php
$dbh = new PDO('mysql:dbname=...', '...', '...');
$stmt = $dbh->prepare('SELECT * FROM my_table WHERE id = :id || id = :id');
$r = $stmt->execute([
    'id' => 1,
]);
while ($row = $stmt->fetch()) {
    var_dump($row['id']);
}

It succeeds. What am I doing wrong?

P.S. Apparently, the query I ran when I encountered the issue was more meaningful.

UPD More or less real query:

SELECT id
FROM objects
WHERE ACOS(
    SIN(RADIANS(lat)) * SIN(RADIANS(:lat))
    + COS(RADIANS(lat)) * COS(RADIANS(:lat)) * COS(RADIANS(:lng - lng))
) * 6371 < 10
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From what I can see it all comes down to mysql being unable to deal with named parameters.

mysqli::prepare:

This parameter can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.

pdo::prepare:

You must include a unique parameter marker for each value you wish to pass in to the statement when you call PDOStatement::execute(). You cannot use a named parameter marker of the same name more than once in a prepared statement, unless emulation mode is on.

Laravel has emulation mode disabled by default. One can enable it in config/database.php by adding 'options' => [PDO::ATTR_EMULATE_PREPARES => TRUE] to connection settings. That way you will get the same result as in pure php. Not sure that's a good idea, though.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...