简体   繁体   English

使用PDO创建表-不起作用

[英]Creating a table using PDO - not working

I know there are a few threads on this, but I've gone through them and haven't yet found a solution. 我知道有一些线程,但是我已经遍历了这些线程,还没有找到解决方案。

The problem I'm having is that when I execute my code to create a table using PHP's PDO object, nothing happens. 我遇到的问题是,当我执行代码以使用PHP的PDO对象创建表时,什么也没发生。 I don't get an error, but I don't get a table either. 我没有收到错误,但也没有得到表格。

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

    $pdo = new pdo('mysql:localhost;ijdb','root','');
try {  
    $sql = 'CREATE TABLE joke 
    (
            id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
            joketext TEXT,
            jokedate DATE NOT NULL
    ) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB'; 
    $pdo->exec($sql);
    $sql = 'INSERT INTO joke values
    (
        (1,"jokes","2014-04-22")
    )';
    $pdo->exec($sql);
 } 
catch (PDOException $e) {  $output = 'Error creating joke table: ' . $e->getMessage();
exit(); }

As I said, nothing happens at all, the table isn't created. 就像我说的,什么都没有发生,表没有创建。

Any help would be greatly appreciated! 任何帮助将不胜感激! And if this is a duplicate post, please point me in the right direction and I'll remove this post. 如果这是重复的帖子,请指出正确的方向,我将删除此帖子。

If you want to make this work, do the following: 如果要执行此操作,请执行以下操作:

Sidenote: This will create a new data entry of the same jokes and 2014-04-22 . 旁注:这将创建一个与2014-04-22相同的jokes的新数据条目。

If you don't want to keep adding the same, set a new query along with a seperate script using 如果您不想继续添加相同的内容,请使用以下命令设置新的查询以及单独的脚本
(PDO with) prepared statements . (带有PDO)准备好的语句 and/or set your columns to be UNIQUE . 和/或将列设置为UNIQUE

Nota: The 1 should be omitted from the INSERT , since your id column is AUTO_INCREMENT . 注意: INSERT应该省略1 ,因为您的id列是AUTO_INCREMENT

try {

 $pdo = new pdo('mysql:host=localhost;dbname=your_db', 'username', 'password_if_any');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = "CREATE TABLE IF NOT EXISTS joke
    (
            id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
            joketext TEXT,
            jokedate DATE NOT NULL

                ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

    INSERT INTO joke (joketext, jokedate) values ('jokes','2014-04-22')";

    $pdo->exec($sql);

 } 
catch (PDOException $e) {  

$output = 'Error creating joke table: ' . $e->getMessage();

echo $output;
exit(); 
}

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

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