我的表单正在连接数据库并插入,但它没有获取我的表单数据并插入空白字段。
<form method="post" action="add.php">
<input type="text" name="firstname" placeholder="Firstname" id="firstname"><br><br>
<input type="text" name="lastname" placeholder="Lastname" id="lastname"><br><br>
<input type="submit" name="submit" value="Sent">
</form>
这是add.php脚本:
<?
mysql_connect("localhost","******","******");//database connection
mysql_select_db("testrentals");
//inserting data order
$order = "INSERT INTO customers (firstname, lastname) VALUES ('$firstname', '$lastname')";
//declare in the order variable
$result = mysql_query($order); //order executes
if($result){
echo("<br>Input data is workin and adding!");
} else{
echo("<br>Input data is failing =(");
}
?>
我的数据库表有和id,firstname和last以及加入日期。
但如上所述,提交时它表明它正在工作,并且会出现一条记录,但在firstname或lastname字段中没有任何内容(我还没有进行连接日期部分。)
答案 0 :(得分:3)
让我们将所有这些切换到PDO并使其正确。这是add.php的样子:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('USER', '*****');
define('PASS', '*****');
function dataQuery($query, $params) {
// what kind of query is this?
$queryType = explode(' ', $query);
// establish database connection
try {
$dbh = new PDO('mysql:host=localhost;dbname=testrentals', USER, PASS);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
}
// run query
try {
$queryResults = $dbh->prepare($query);
$queryResults->execute($params);
if($queryResults != null && 'SELECT' == $queryType[0]) {
$results = $queryResults->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
$queryResults = null; // first of the two steps to properly close
$dbh = null; // second step tp close the connection
}
catch(PDOException $e) {
$errorMsg = $e->getMessage();
echo $errorMsg;
}
}
$order = "INSERT INTO `customers` (`firstname`, `lastname`) VALUES (?,?)";
$params = array($_POST['firstname'], $_POST['lastname']);
$results = dataQuery($order, $params);
?>
详细解释了here的技术。
答案 1 :(得分:2)
您需要从$_POST
获取值$_POST['firstname']
。如果您要直接从$ _POST获取数据,那么在将任何内容保存到数据库之前,您最好过滤并验证表单中的内容。
答案 2 :(得分:1)
您需要从$ _POST数组中提供数据。这是在提交数据http://php.net/manual/en/reserved.variables.post.php
之后的数据$firstname = $_POST['firstname'];
$lastname= $_POST['lastname'];
$order = "INSERT INTO customers (firstname, lastname) VALUES ('".$firstname."', '".$lastname."')";
答案 3 :(得分:1)
你应该使用你的帖子变量,如...
$_POST['firstname'];
$_POST['lastname'];