从用户表单:我试图插入以下数据: 1)名字2)姓氏3)专业4)毕业年度
我能够连接到数据库,并选择我需要的数据库 - 但我无法从表单中插入数据。我能够创建记录,但数据没有保存到数据库中。基本上,现在我正在创建空白表格。
变量$ uInput保存用户数据。我尝试将$ uInput传递给函数doAction(),但我相信这就是问题所在。我试图弄清楚如何将用户数据传递给函数doAction()。
<?php
//Call function mainline
mainline();
// Declare the function mainline
function mainline() {
$uInput = getUserInput();
$connectDb = openConnect(); // Open Database Connection
selectDb($connectDb); // Select Database
doAction($uInput);
//closeConnect();
//display();
}
//Declare function getUserInput ------------------------------------------------------------------------------------
function getUserInput() {
echo "In the function getUserInput()" . "<br/>";
// Variables of User Input
$idnum = $_POST["idnum"]; // id (NOTE: auto increments in database)
$fname = $_POST["fname"]; // first name
$lname = $_POST["lname"]; // last name
$major = $_POST["major"]; // major
$year = $_POST["year"]; // year
$action = $_POST["action"]; // action (select, insert, update, delete)
$userInput = array($idnum, $fname, $lname, $major, $year, $action);
//echo "info from getUserInput: " . $action;
return $userInput;
}
function doAction($pUserInput) {
// if user selects INSERT from dropdown menu, then call function insert
//and pass $uInput
if ($pUserInput[5] == "ins") {
insert($uInput);
}
}
// Create a database connection --------------------------------------------------------
function openConnect() {
$connection = mysql_connect("localhost", "root_user", "password");
echo "Opened Connection!" . "<br/>";
if(!$connection) {
die("Database connection failed: " . mysql_error());
}
return $connection;
}
// Select a database to ----------------------------------------------------------------
function selectDb($pConnectDb) {
$dbSelect = mysql_select_db("School", $pConnectDb);
if(!$dbSelect) {
die("Database selection failed: " . mysql_error());
} else {
echo "You are in the School database! <br/>";
}
}
// function insert ---------------------------------------------------------------------
function insert($pUInput) {
$sql="INSERT INTO tblStudents (first_name, last_name, major, year)
VALUES
('$pUInput[1]','$pUInput[2]','$pUInput[3]', '$pUInput[4]')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
}
?>
答案 0 :(得分:1)
您的doAction()
功能有问题。您将参数作为$pUserInput
输入函数,但将{(1}}作为insert()函数发送。
你应该这样做:
$uInput
答案 1 :(得分:0)
更改插入($ uInput);要插入的函数($ pUserInput);