无法在MySQL中添加新记录

时间:2016-10-31 07:20:18

标签: php mysql

基本上我可以使用它来创建记录,但它不会自动更新我的ID列以允许新记录。我需要在表达式中添加更新计数器吗?或者是否有一个按钮或开关使用phpmyadmin自动创建提交时的新ID?

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "message";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "INSERT INTO adminmessages (UserName, Message, Score)
    VALUES ('SammyWest', 'Test1', '100')";
    // use exec() because no results are returned
    $conn->exec($sql);
    echo "New record created successfully";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }

$conn = null;
?>

表架构

    1   IDPrimaryIndex  int(255)            No  None        Change Change   Drop Drop   
Primary Primary
Unique Unique
Index Index
Spatial Spatial
Fulltext Fulltext
More
    2   UserName    varchar(255)            No  None        Change Change   Drop Drop   
Primary Primary
Unique Unique
Index Index
Spatial Spatial
Fulltext Fulltext
More
    3   Message varchar(255)            No  None        Change Change   Drop Drop   
Primary Primary
Unique Unique
Index Index
Spatial Spatial
Fulltext Fulltext
More
    4   Score   int(255)            No  None        Change Change   Drop Drop   
Primary Primary
Unique Unique
Index Index
Spatial Spatial
Fulltext Fulltext
More

1 个答案:

答案 0 :(得分:0)

您必须使用以下命令将id列定义为自动增量主键字段:

ALTER TABLE adminmessages CHANGE id id INT AUTO_INCREMENT PRIMARY KEY;