插入在PHP无法正常工作

时间:2013-05-21 16:05:07

标签: php

我有这个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 个答案:

答案 0 :(得分:3)

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

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

如果可能,您应该升级到mysqlipdo

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分: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();
?>