2013-03-23 74 views
-3

我目前很難理解爲什麼下面的腳本將成功返回給瀏覽器,但實際上並沒有將數據插入到數據庫中。 我知道我使用舊的MySQL指令,但我懷疑這應該是造成這個問題。 由於提前阿利斯泰爾PHP沒有插入到MySQL數據庫中

<?php 

ob_start(); 
$host="localhost"; // Host name 
$username="XXXXXX"; // Mysql username 
$password="XXXXXXXXXXXXXXXXXXX"; // Mysql password 
$db_name="XXXXXXXX"; // Database name 
$tbl_name="XXXXXXXXXX"; // Table name 

// Connect to server and select databse. 
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB"); 

// Define Variables 
$myusername=$_POST['username']; 
$password1=$_POST['password1']; 
$password2=$_POST['password2']; 
$emailadd=$_POST['emailadd']; 

if($password1==$password2){ 
    //Ecnrypt Password Using SHA512 
    $password1 = hash("sha512", $password1); 
} 

else { 
    //Passwords don't match return user to form with parameter 
    header("location:adduser.php?pwnomatch"); 
} 

//Check user doesn't already exist 
$sqlcheckuser="SELECT * FROM $tbl_name WHERE username='$username'"; 
$result1=mysql_query($sqlcheckuser); 

// Mysql_num_row is counting table row 
$count=mysql_num_rows($result1); 

//If user exists redirect back to login form 
if($count==1){ 
    header("location:adduser.php?userexist"); 
} 

// To protect MySQL injection (more detail about MySQL injection) 
$username = stripslashes($myusername); 
$password1 = stripslashes($mypassword); 
$emailadd = stripslashes($emailladd); 
$myusername = mysql_real_escape_string($myusername); 
$mypassword = mysql_real_escape_string($mypassword); 
$emailadd = mysql_real_escape_string($emailladd); 
$sqlinsertuser="INSERT INTO $tbl_name ('username', 'password', 'emailaddress' VALUES ($username, $password1, $emailadd)"; 
mysql_query($sqlinsertuser); 

// Mysql_num_row is counting table row 
$count=mysql_num_rows($result2); 

// Register user then redirect to "viewuser.php" with success parameter 
header("location:viewuser.php?success"); 

ob_end_flush(); 
?> 
+1

SQL注入,我來了。 :) – hjpotter92 2013-03-23 11:46:24

回答

3
INSERT INTO $tbl_name ('username', 'password', 'emailaddress' VALUES ($username, $password1, $emailadd) 

您還沒有關閉了支架上的列名。因此,您的查詢應該是這樣的:

INSERT INTO $tbl_name (`username`, `password`, `emailaddress`) VALUES ($username, $password1, $emailadd) 

還有一點我沒有在我原來的職位通知;您使用了引號而不是反引號。

行情中查詢通常代表一個字符串,反引號進行了說明:

Using backticks around field names

+0

downvote的原因是什麼? – 2013-03-23 11:46:06

+2

我沒有downvote,但如果我有,這將是因爲引號不是反引號 – Strawberry 2013-03-23 11:49:13

+0

@Strawberry排序 – 2013-03-23 12:00:41

1

您的查詢字符串了很多錯誤。它應該是

$sqlinsertuser="INSERT INTO $tbl_name (`username`, `password`, `emailaddress`) 
     VALUES('$myusername', '$mypassword', '$emailadd')"; 

通知傳遞的字段名稱使用反引號,而不是單引號的。並且在VALUES內使用引號。


您在查詢中使用了錯誤的變量。