为什么我不能用PHP将数据插入mysql数据库

时间:2012-09-13 18:32:08

标签: php mysql

它相当令人沮丧,我确信它很容易解决。据我所知,我的代码是现场导致我相信存在服务器问题。我创建了数据库,我可以从命令行将数据插入表中。如果它有助于我使用WAMP。

<?php

$host="localhost"; // Host name 
$username="root"; // Mysql username 
$password="permission"; // Mysql password 
$db_name="login"; // Database name 
$tbl_name="members"; // 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");

// username and password sent from form 
$myusername=$_POST['username']; 
$mypassword=$_POST['password']; 
$myfname=$_POST['fname'];
$mylname=$_POST['lname'];
$myemail=$_POST['email'];



// To protect MySQL injection 
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername'";
$result=mysql_query($sql);

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

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

// username taken
echo "Username already taken";
exit();
}

//protection against sql injection
if (get_magic_quotes_gpc())
{
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map(stripslashes_deep, $value) :
stripslashes($value) ;
return $value;
}
$_POST = array_map(stripslashes_deep, $_POST);
$_GET = array_map(stripslashes_deep, $_GET);
$_COOKIE = array_map(stripslashes_deep, $_COOKIE);
$_REQUEST = array_map(stripslashes_deep, $_REQUEST);
}

//insert form into DB members




'INSERT INTO members SET
username="' . $myusername . '",
password="' . $mypassword . '",
email="' . $myemail . '",
fname="' . $myfname . '",
lname="' . $mylname . '",';

session_register("myusername");
session_register("mypassword"); 
header("location:registersuccess.html");
?>

3 个答案:

答案 0 :(得分:2)

除了SQL注入问题之外,您还有一个不必要的尾随逗号。

变化:

lname="' . $mylname . '",'; 

为:

lname="' . $mylname . '"'; 

答案 1 :(得分:1)

可能是因为你有一个额外的尾随逗号: lname="' . $mylname . '",';应该是lname="' . $mylname.'"';

答案 2 :(得分:1)

另外,如果你不知道如何进行查询,就像这样:

$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Create table doesn't return a resultset */
if (mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}

参考。 http://php.net/manual/en/mysqli.query.php