Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 为什么我在上传到数据库时收到PDO异常_Php_Mysql_Sql_Database - Fatal编程技术网

Php 为什么我在上传到数据库时收到PDO异常

Php 为什么我在上传到数据库时收到PDO异常,php,mysql,sql,database,Php,Mysql,Sql,Database,我正在尝试使用PDO对象将一些数据上传到MySQl数据库。但是,每当我尝试提交查询时,它都会抛出一个异常。我已经按照书中的多个教程,这应该是一个简单的任务。我不知道它为什么会抛出异常 这是我的密码: // Add a new image data to db and return ID (ID column of pelagicsschema.images) public function addImage(string $name, string $species, stri

我正在尝试使用PDO对象将一些数据上传到MySQl数据库。但是,每当我尝试提交查询时,它都会抛出一个异常。我已经按照书中的多个教程,这应该是一个简单的任务。我不知道它为什么会抛出异常

这是我的密码:

    // 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();
    }
注意: 如果我使用exec()而不是prepare/execute,那么查询会执行得非常完美,但是由于这个请求会使用不同的数据多次发出,因此我认为prepare/execute是一个不错的选择

编辑:我收到的例外情况是:

SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'Name' at row 1
这是否意味着我需要更改数据库中该列的数据类型?
当前它被设置为VARCHAR(30)。

看起来您试图插入的数据比列定义的最大大小更长

如果要存储大于255个字符的字符串,应使用另一种类型作为
name
列定义,例如
text


与其抛出带有自定义消息的新异常并丢弃PDOException,不如检查该异常的实际内容。@MagnusEriksson我很乐意这样做。如何做到这一点?在开发过程中,在
catch
-块中,只需添加:
die($e->getMessage())(在抛出<代码>之前),它应该显示消息。调试该问题后,您可能应该将
die()
更改为记录消息的函数/方法。应选择希望保存在此列中的数据库表列的类型。如果您知道
name
值的长度可以超过30个字符,则应将其更改为VARCHAR(255)(或name的最大预期长度)!或者为
名称
的输入字段设置长度限制。请同时检查字符集。如果不是utf8mb4,则需要更改它。