2012-03-22 47 views
1

我已經努力調試下面的insert.php文件。在運行此程序和關聯的webform文件inwamp服務器時沒有錯誤,但它沒有向數據庫讀取數據。有人可以對此發表評論嗎?下面給出的insert.php有什麼問題嗎?

?php 
if (isset($_POST['submit'])) { 


//Connect to the database 



$host="localhost"; 
$user="root"; 
$password=""; 
$dbc=mysql_connect($host,$user,$password) or die("Connection Error"); 
$db_name="userregistration"; 
mysql_select_db("$db_name") or die ("Could not select database"); 



//Reading data from form and writing to the DB 
$fname = $_POST['fname']; 
$institution = $_POST['institute']; 
$email = $_POST['email']; 
$phone = $_POST['phone']; 
$pgm = $_POST['pgm']; 
$address = $_POST['address']; 



//Examining for input errors 
$error = FALSE; 


if (isset($address)) { 
$address = trim($address); 
$address = strip_tags($address); 
} 

if (isset($fname) && 
isset($institute) && 
isset($email) && 
isset($phone) && 
isset($pgm) && 
isset($address) && 
$error == FALSE) { 
$process = TRUE; 
} else { 
$process = FALSE; 
} 

//Writing the multiple answers for user selected programs 

while ((list($key,$val) = each($pgm))) { 
$pgm .= "[" . $val . "]"; 
} 



//Creating the table 
$query = "create table userdata 
(sid int unsigned not null auto_increment primary key, 
fname char(50) not null, 
institute char(50) not null, 
email char(50) not null, 
phone int unsigned, 
pgm text not null, 
address char(200) not null)"; 
$q = mysql_query($query); 




//Inserting the data 
$query = "insert into userdata values ('','$fname','$institute','$email','$phone','$pgm','$address')"; 
$q = mysql_query($query); 


//Check whether data was properly inserted 
if (!$q) { 
exit("<p>MySQL Insertion failure.</p>"); 
} else { 
mysql_close(); 
echo "<p>MySQL Insertion Successful</p>"; 
} 

} 
?> 

有人可以評論這個嗎?

+1

不要忘記逃避你發佈變量。現在你的代碼容易受到sql-injects的影響 – Tim 2012-03-22 16:31:08

+1

爲什麼每次裝入這個東西時都會創建一個表? – Tim 2012-03-22 16:32:07

+0

www.bobby-tables.com – 2012-03-22 16:33:20

回答

1

試試您的mysql_query($查詢)後加入

or die(mysql_error()); 

。這肯定會顯示錯誤,如果它失敗...

+0

在Wamp服務器中運行文件時,會發生什麼情況是我得到一個空白頁面,並且沒有任何內容插入到數據庫中。即使桌子沒有被創建。 – 2012-03-23 03:20:20

+0

仍然沒有錯誤..... – 2012-03-23 13:53:50

1

你試圖回聲$ q?它應該告訴什麼是試圖添加到數據庫時出錯..

+0

@Andrew De Forest:你能解釋一下$ error問題嗎? 現在,我在大學。一旦我到家,我會公佈結果。 – 2012-03-23 03:24:07

+0

感謝Asaf,Andrew和Tim的回答。我很新的PHP和MySQL。就在前天,我是否拿到了我的書。我編寫了一些在線教程幫助的代碼。我將回顯插入查詢並檢查是否彈出錯誤。 – 2012-03-23 13:40:53

1
//Check whether data was properly inserted 
if (!$q) { 
die(mysql_error()); 
exit(); 
} else { 
mysql_close(); 
echo "<p>MySQL Insertion Successful</p>"; 
} 
+0

上面的代碼我寫過了嗎?據我所知,兩者都是一樣的,除了我已經加入回聲..... – 2012-03-23 03:19:04

0

我最好的猜測是,該表已存在,因此當用戶提交表單你的代碼試圖再次創建表「用戶數據」這已經在那裏然後死亡。

您應該從代碼中移除create語句,因爲每次提交時都會嘗試創建一個已經存在的表。在傳遞給SQL語句之前,您還應該查看有關轉義子數據的內容,因爲您現在只是要求SQL注入攻擊。

+0

Hei Hairzo,在執行insert.php之後,表格沒有被創建。我通過檢查phpmyadmin頁面來確定它。 – 2012-03-23 03:17:45