問題描述
我對 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
這篇關于使用 PDO 創建表的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!