简体   繁体   中英

Syntax error while executing a sql request with parameters in symfony?

I have a just simple problem I guess, I followed Symfony 4.3 documentation, and tried to do do exactly what they have done to execute a SQL request, but I get an error when passing parameters in the execute method, but I get no error while executing the same code but without passing parameters to the request.

I tried this and it worked:

    $conn = $this->getDoctrine()->getManager()->getConnection();

    $sql = '
        SELECT * FROM question_comment WHERE question=2 LIMIT 0, 3';
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    var_dump($stmt->fetchAll());

But this does not work, I get a syntax error:

    $question = $request->query->get('question');
    $row = $request->query->get('row');

    $question = intval($question);
    $beggining = intval($row*3);

    $conn = $this->getDoctrine()->getManager()->getConnection();

    $sql = '
        SELECT * FROM question_comment WHERE question=:question LIMIT :beggining , 3';
    $stmt = $conn->prepare($sql);
    $stmt->execute(['question' => $question, 'beggining' => $beggining]);
    var_dump($stmt->fetchAll());

This is the error:

An exception occurred while executing ' SELECT * FROM question_comment WHERE question= :question LIMIT :beggining , 3' with params [2, 0]:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''0' , 3' at line 1

Here is what I have followed, I did exactly what was there, but its not working.

I tried this solution to bind my parameters but it did not work too :

 $sql = '
            SELECT * FROM question_comment WHERE question=:question LIMIT :beggining , 3';
        $stmt = $conn->prepare($sql);
        $stmt->bindParam(':question', $question, \PDO::PARAM_INT); 
        $stmt->bindParam(':beginning', $beginning, \PDO::PARAM_INT); 
        $stmt->execute();

And I got this :

An exception occurred while executing ' SELECT * FROM question_comment WHERE question=:question LIMIT :beggining , 3' with params [2, null]:

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

alternative way to bind parameters is using this.

 $stmt->bindParam(':question', $question, PDO::PARAM_STR); 
 $stmt->bindParam(':beginning', $beginning, PDO::PARAM_INT); 

or to make it sure you binded the $beginning parameter, cast it to int.

$stmt->bindValue(':beginning', (int)trim($beginning), PDO::PARAM_INT);

or if you want to stick on your existing code.

$stmt->execute(['question' => $question, 'beggining' => (int)trim($beggining)]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM