使用 PDO 创建表

2021-12-26 00:00:00 php pdo

我对 php 和这个论坛很陌生,所以请原谅任何错误或错位的问题.在我提供的代码中,我只是想在数据库mydb"中创建一个表.我测试了与数据库的连接(它有效).这只是我遇到问题的创建表.任何建议或批评将不胜感激.谢谢

I am very new to php and this forum, so please excuse any errors or misplaced questions. In the code i provided, I am just looking to CREATE a Table in the DB "mydb". I tested the connection to the DB(It works). It is just the creating the table i am having issues with. Any advice or criticisms would be appreciated. Thx

<?php
/*
*
* File:         PDOcreateTabletcompany.php
* By:          Jay
* Date:       24-10-13
*
*  This script createsTableintoDB
*
*====================================
*
*/
try {
    $db = new PDO("mysql:dbname=mydb;host=localhost", "root", "" );
} catch(PDOException $e) {
    echo $e->getMessage();
}
$table= "tcompany";
$columns = "ID INT( 11 ) AUTO_INCREMENT PRIMARY KEY, Prename VARCHAR( 50 ) NOT NULL, Name VARCHAR( 250 ) NOT NULL,
 StreetA VARCHAR( 150 ) NOT NULL, StreetB VARCHAR( 150 ) NOT NULL, StreetC VARCHAR( 150 ) NOT NULL, 
 County VARCHAR( 100 ) NOT NULL, Postcode VARCHAR( 50 ) NOT NULL, Country VARCHAR( 50 ) NOT NULL " ;


$createTable = $db->exec("CREATE TABLE IF NOT EXISTS mydb.$table ($columns)");

if ($createTable) 
{
    echo "Table $table - Created!<br /><br />";
}
else { echo "Table $table not successfully created! <br /><br />";
}
?>

推荐答案

由于创建表时没有行受到影响 $createTable 返回 0 参见 手册

As no rows are affected when creating table $createTable returns 0 see manual

PDO::exec() 返回修改或删除的行数通过您发出的 SQL 语句.如果没有行受到影响,PDO::exec()返回 0.

PDO::exec() returns the number of rows that were modified or deleted by the SQL statement you issued. If no rows were affected,PDO::exec() returns 0.

当您创建表时,如果您的列名是硬编码的(如下面的代码所示),您将不会受到 SQL 注入的影响.我已经离开 $table = "tcompany"; 因为你想打印创建的表(我自己会忽略它)

As you are CREATING a table you will be free from SQL injection if your column names are hard coded( as in the code below). I have left $table = "tcompany";as you want to print table created( I would leave it out myself)

我添加了错误处理 将显示 try 块中的任何错误.

I have added error-handling which will show any errors in try block.

$table = "tcompany";
try {
     $db = new PDO("mysql:dbname=mydb;host=localhost", "root", "" );
     $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );//Error Handling
     $sql ="CREATE table $table(
     ID INT( 11 ) AUTO_INCREMENT PRIMARY KEY,
     Prename VARCHAR( 50 ) NOT NULL, 
     Name VARCHAR( 250 ) NOT NULL,
     StreetA VARCHAR( 150 ) NOT NULL, 
     StreetB VARCHAR( 150 ) NOT NULL, 
     StreetC VARCHAR( 150 ) NOT NULL, 
     County VARCHAR( 100 ) NOT NULL,
     Postcode VARCHAR( 50 ) NOT NULL,
     Country VARCHAR( 50 ) NOT NULL);" ;
     $db->exec($sql);
     print("Created $table Table.
");

} catch(PDOException $e) {
    echo $e->getMessage();//Remove or change message in production code
}

注意回答评论使用

CREATE TABLE IF NOT EXISTS

相关文章