简体   繁体   English

为什么上传到数据库时会收到 PDO 异常

[英]Why am I receiving a PDO Exception when Uploaing to the Database

I am trying to upload some data to a MySQl DB using a PDO object.我正在尝试使用 PDO 对象将一些数据上传到 MySQl DB。 However, whenever I attempt to submit the query it throws a PDOException.但是,每当我尝试提交查询时,它都会抛出 PDOException。 I have followed multiple tutorials by the book and this should be a simple task.我遵循了本书的多个教程,这应该是一项简单的任务。 I have no idea why it throws an exception.我不知道为什么它会抛出异常。

Here is my code:这是我的代码:

    // Add a new image data to db and return ID (ID column of pelagicsschema.images)
    public  function addImage(string $name, string $species, string $rarity, string $description){
    //Global PDO Object
    global $pdo;
    //trim strings to remove extra spaces
    $name = trim($name);
    $species = trim($species);
    $rarity = trim($rarity);
    $description = trim($description);



   // Add the new Image

   /* Insert query template */
   $query = 'INSERT INTO pelagicsSchema.images (Name,Species,Rarity,Description) VALUES    (:name,:species,:rarity,:description)';
   /* Values array for PDO */
   $values = array(':name'=>$name, ':species'=>$species, ':rarity'=>$rarity, ':description'=>$description);
   /* Execute the query */
   try
   {
       $res = $pdo->prepare($query);
       $res->execute($values);
   }
   catch (PDOException $e)
   {
      /* If there is a PDO exception, throw a standard exception */
      throw new Exception('Database query error');
   }

       /* Return the new ID */
        return $pdo->lastInsertId();
    }

To Note: The query executes perfectly if I use exec() instead of prepare/execute, but as this request will be made multiple times with different data, I believe prepare/execute is the way to go.注意:如果我使用 exec() 而不是准备/执行,查询会完美执行,但由于此请求将使用不同的数据多次发出,我相信准备/执行是要走的路。

EDIT: The Exception that I am receiving is:编辑:我收到的例外是:

SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'Name' at row 1

Does this mean I need to change the datatype for that column in my DB?这是否意味着我需要更改数据库中该列的数据类型? Currently it is set to VARCHAR(30).目前它被设置为 VARCHAR(30)。

It looks like you are trying to insert data that is longer that the column definition's maximum size.看起来您正在尝试插入比列定义的最大大小更长的数据。

If you wanna store strings bigger than 255 characters, you should use another type for the name column definition, text for example.如果您想存储大于 255 个字符的字符串,您应该为name列定义使用另一种类型,例如text

http://www.sqlerror.de/db2_sql_error_-404_sqlstate_22001.html http://www.sqlerror.de/db2_sql_error_-404_sqlstate_22001.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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