【发布时间】:2016-04-23 00:37:33
【问题描述】:
我在从 php 脚本向 mySql db 中插入记录时遇到问题。这是我的代码:
// Set fields for post record insertion
$insertPostSql = "INSERT INTO tl_posts(title, city, city_id, video_url, thumbnail_url, description, longitude, latitude, user_id, category, hotel_id, restaurant_id, activity_id, creation_date, qualified)
VALUES(:title, :city, :cityId, :video, :thumbnail, :description, :long, :lat, :userid, :category, :hotelId, :restoId, :activityId, :crea, :checked)";
$insertPostStmt = $pdo->prepare($insertPostSql);
$insertPostStmt->bindValue(':title', $title);
$insertPostStmt->bindValue(':city', $city);
$insertPostStmt->bindValue(':cityId', $cityId);
$insertPostStmt->bindValue(':video', substr($videoPath, strlen(ROOT_PATH)));
$insertPostStmt->bindValue(':thumbnail', substr($thumbnailPath, strlen(ROOT_PATH)));
$insertPostStmt->bindValue(':description', $description);
$insertPostStmt->bindValue(':long', $longitude);
$insertPostStmt->bindValue(':lat', $latitude);
$insertPostStmt->bindValue(':userid', $userId);
$insertPostStmt->bindValue(':category', $category);
$insertPostStmt->bindValue(':hotelId', ($category === 'hotel' ? $categoryId : "NULL"));
$insertPostStmt->bindValue(':restoId', ($category === 'restaurant' ? $categoryId : "NULL"));
$insertPostStmt->bindValue(':activityId', ($category === 'activity' ? $categoryId : "NULL"));
$insertPostStmt->bindValue(':crea', $now);
$insertPostStmt->bindValue(':checked', $checked);
// New post transaction
$pdo->beginTransaction();
try {
$insertPostStmt->execute();
$pdo->commit();
$response['result']['database'] = "Post added successfully";
} catch (Exception $e) {
$pdo->rollBack();
$response['result']['database'] = "Error! Post not saved in database";
die("Error! ".$e->getMessage());
}
它导致“发布添加成功响应”,但没有任何内容保存到数据库中。 每个值都可以,我之前已经回显过它们进行测试。 SQL 语法也可以,因为它适用于数据库 SQL 命令面板。 基本上,所有字段都是 Varchar。除了 'id' 和最后两个 Datetime 和 Boolean 之外的类型。
我不得不说我之前使用过这个语句并且它工作正常,所以数据库也可以:
$insertSql = "INSERT INTO tl_posts(title, city, video_url, thumbnail_url, description, longitude, latitude, user_id, category, creation_date, qualified)
VALUES(:title, :city, :video, :thumbnail, :description, :long, :lat, :userid, :category, :crea, :checked)";
$insertStmt = $pdo->prepare($insertSql);
$insertStmt->bindValue(':title', $title);
$insertStmt->bindValue(':city', $city);
$insertStmt->bindValue(':video', substr($videoPath, strlen(ROOT_PATH)));
$insertStmt->bindValue(':thumbnail', substr($thumbnailPath, strlen(ROOT_PATH)));
$insertStmt->bindValue(':description', $description);
$insertStmt->bindValue(':long', $longitude);
$insertStmt->bindValue(':lat', $latitude);
$insertStmt->bindValue(':userid', $userId);
$insertStmt->bindValue(':category', $category);
$insertStmt->bindValue(':crea', $now);
$insertStmt->bindValue(':checked', $checked);
我很好奇找到关于它的最后一句话。感谢您的帮助
【问题讨论】:
-
注意:你需要捕获正确的异常,即
PDOException而不是Exception。
标签: php mysql pdo insert commit