0

我有这个将表单中的数据插入数据库的 php 脚本。代码总是返回错误。可能是什么问题。注意:表单中的字段名称匹配正确。

<?php 
$db_hostname = 'localhost';
$db_database = 'townmanagement';
$db_username = 'root';
$db_password = '';

// Connect to server.
$db_server = mysql_connect($db_hostname, $db_username, $db_password)
or die("Unable to connect to MySQL: " . mysql_error());

mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());

// Get values from form
$fname= mysql_escape_string(trim ($_POST['fname']));
$lastname= mysql_escape_string(trim ($_POST['lname']));
$dpt=mysql_escape_string(trim($_POST['dpt']));
$user= mysql_escape_string(trim ($_POST['username']));
$psswd=mysql_escape_string(trim ($_POST['password']));



// Insert data into mysql
$sql="INSERT INTO staff_reg (fname, lname, dpt, username, password, registration_date)
VALUES ($fname, $lastname, $dpt, $user, SHA1($password), NOW())";
$result = mysql_query($sql); 

if($result){
echo ("sUCCESSFUL");
}
else {
echo "error";;
}

?>

<?php
// close connection
mysql_close();
?>
4

4 回答 4

3

您需要在 SQL 语句中引用您的参数

  $sql="INSERT INTO staff_reg (fname, lname, dpt, username, password, registration_date)
VALUES ('$fname', '$lastname', '$dpt', '$user', SHA1('$password'), NOW())";

如果可能的话,你应该升级到mysqlipdo

于 2013-05-21T16:07:35.230 回答
2

您的价值观周围缺少引号:

$sql="INSERT INTO staff_reg (fname, lname, dpt, username, password, registration_date)
VALUES ('$fname', '$lastname', '$dpt', '$user', SHA1($password), NOW())";

为了更好地进行故障排除,请考虑在mysql_query语句中添加以检测查询失败的时间和原因:

$result = mysql_query($sql) or die( mysql_error() ); 

最后,请注意这些mysql_*功能已被弃用。请考虑更新您的代码以使用mysqliPDO

于 2013-05-21T16:07:27.353 回答
1
mysql_select_db($db_database,$db_server)
or die("Unable to select database: " . mysql_error());
//you have to select db using connection previously established
于 2013-05-21T16:08:25.873 回答
0

试试这个:你应该知道,我不鼓励你使用mysql_它,因为它已被弃用,你应该在未来学习和实施 PDO:

<?php 
$db_hostname = 'localhost';
$db_database = 'townmanagement';
$db_username = 'root';
$db_password = '';

// Connect to server.
$db_server = mysql_connect($db_hostname, $db_username, $db_password)
or die("Unable to connect to MySQL: " . mysql_error());

mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());

// Get values from form
$fname= mysql_escape_string(trim ($_POST['fname']));
$lastname= mysql_escape_string(trim ($_POST['lname']));
$dpt=mysql_escape_string(trim($_POST['dpt']));
$user= mysql_escape_string(trim ($_POST['username']));
$psswd=mysql_escape_string(trim ($_POST['password']));

$psswd2 = SHA1($psswd);

// Insert data into mysql
$sql="INSERT INTO staff_reg (fname, lname, dpt, username, password, registration_date)
VALUES ('".$fname."', '".$lastname."', '".$dpt."', '".$user."', '".$psswd2."', "NOW()" )";

if(mysql_query($sql)); {
echo ("sUCCESSFUL");
}else {
echo "error";;
}
mysql_close();
?>
于 2013-05-21T17:54:06.487 回答