简体   繁体   中英

PDO and PHP. Undefined index, but it is defined

I have a class:

class Media {
    private $media;
    private $thumb;
    private $slug;
    private $info;
    private $type;
    private $link;
}

And I try to save it to the DB using PHP PDO:

$PDO = new PDO("mysql:host=".DBHOST.";dbname=".DB, DBUSER, DBPASS);

$options = array('media' => 'image.jpg',
            'thumb' => 'image_thumb.jpg');
$media = new Media($options);

$media = (array)$media;

$STH = $PDO->prepare('INSERT INTO media (media, thumb, slug, info, type, link) values (?, ?, ?, ?, ?, ? )');

$STH->bindParam(1, $media['Mediamedia']);
$STH->bindParam(2, $media['Mediaslug']);
$STH->bindParam(3, serialize($media['Mediainfo']));  //line 150
$STH->bindParam(4, $media['Mediathumb']);
$STH->bindParam(5, $media['Mediatype']);
$STH->bindParam(6, $media['Medialink']);

$STH->execute();

The code above produces 1 error:

Notice: Undefined index: Mediainfo in C:\\wamp32\\www\\MM\\index.php on line 150

But print_r($media); outputs:

Array
(
    [Mediamedia] => image.jpg
    [Mediathumb] => image_thumb.jpg
    [Mediaslug] => image
    [Mediainfo] => Array
    (
        [title] => image.jpg
        [alt] => image.jpg
        [description] => image.jpg
    )
    [Mediatype] => .jpg
    [Medialink] => 0
)

Edit: Fixed second error, quite dumb like @dleiftah said, but one persists.

When you cast an object to an array, the private and protected members are mangled. The private members have null bytes \\x00 surrounding the class name. To use them in this fashion, you would need:

$STH->bindParam(1, $media["\x00Media\x00media"]);
$STH->bindParam(2, $media["\x00Media\x00slug"]);
$STH->bindParam(3, serialize($media["\x00Media\x00info"]));
$STH->bindParam(4, $media["\x00Media\x00thumb"]);
$STH->bindParam(5, $media["\x00Media\x00type"]);
$STH->bindParam(6, $media["\x00Media\x00link"]);

If they were protected members, they would start with \\x00*\\x00

Also, it appears that the order you are binding parameters does not match the order of fields in your insert statement.

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