如何判断PDO插入是否成功?

时间:2016-10-31 12:45:09

标签: php mysql pdo

我正在将使用MySQLi构建的网站转换为PDO。

我到处搜索,但我找不到一个好例子。我只需要正确的方法来执行插入查询。

数据库文件

$host_name = "localhost";
$db_username = "root";
$db_password = "mysql";
$db_name = "mydatabase";


try {
    $conn = new PDO("mysql:host=$host_name;dbname=$db_name", $db_username, $db_password);

    $conn->exec("set names utf8");

    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }

提交文件(从用户提交的表格中获取数据

if($_POST)
{   


$post_title         = $_POST['post'];
$post_cat              = $_POST['post_cat'];

$stmt = $conn->prepare("INSERT INTO posts post_title, post_cat)
    VALUES (:p_title, :p_cat)");
    $stmt->bindParam(':p_title', $post_title);
    $stmt->bindParam(':p_cat', $post_cat);

    $stmt->execute();

    $conn = null;
}

这会将数据插入数据库而不会出现任何问题。但是如何检查行是否插入。并显示消息"已发布"或者如果出现错误"失败"

0 个答案:

没有答案