Jump to content

PDO->MySQL


RobertP

Recommended Posts

i am having an issue with a prepared statement. if i replace my '?' with a 4, it works as expected. only 1 issue is that the variable $max is dynamic.

 

example code

<?php

ini_set('display_errors',1);
ini_set('date.timezone','America/Toronto');

$connection = new PDO('mysql:host=127.0.0.1;port=3390;dbname=gludoe','user','pass');
$connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);

$max = 4;

$stmt = $connection->prepare('select * from plugin_simsmanager_items order by add_date desc limit ?;');
$stmt->execute(array($max));

print_r($stmt->fetchAll());

?>

 

output

Array
(
)

 

expected output

Array
(
    [0] => Array
        (
            [item_id] => 1
            [item_name] => Test 1
            [image_id] => commons/plugins/simsManager/test1.jpg
            [add_date] => 0.0000
            [item_description] => 
            [file_id] => 
            [age_group] => 
        )

    [1] => Array
        (
            [item_id] => 2
            [item_name] => Test 2
            [image_id] => commons/plugins/simsManager/test2.jpg
            [add_date] => 0.0000
            [item_description] => 
            [file_id] => 
            [age_group] => 
        )

    [2] => Array
        (
            [item_id] => 3
            [item_name] => Test 3
            [image_id] => commons/plugins/simsManager/test3.jpg
            [add_date] => 0.0000
            [item_description] => 
            [file_id] => 
            [age_group] => 
        )

    [3] => Array
        (
            [item_id] => 4
            [item_name] => Test 4
            [image_id] => commons/plugins/simsManager/test4.jpg
            [add_date] => 0.0000
            [item_description] => 
            [file_id] => 
            [age_group] => 
        )

)

Link to comment
Share on other sites

When you supply the values via an array to the ->execute() method -

All values are treated as PDO::PARAM_STR.

 

This results in single quotes being added around the number, which is invalid for the LIMIT clause.

 

You need to specifically bind the value as an integer -

 

$stmt->bindParam(1, $max, PDO::PARAM_INT);

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.