优秀的开发人员远在天边! 我只是想问一下我的代码有什么问题,我正在尝试使用html,css,php和数据库制作网页。现在,我已经以html形式创建了一个php,并且数据库已经连接,但是每次我以创建的html形式提交信息时,数据库中都不会出现任何内容。
<?php
if(isset($_POST['save'])){
$FName = $_POST['FName'];
$MName = $_POST['MName'];
echo "Successfully Added";
$sql= "INSERT INTO 'tbstudinfo' (Transaction_Number, First_Name, `Middle_Name') VALUES ('000',$FName,$MName)";
} else{
echo "<p>Insertion Failed.</p>";
}
?>
答案 0 :(得分:1)
您只是不执行查询。使用MySQLi:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "dbthesis";
$conn = new mysqli($servername, $username, $password, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['save'])){
$FName = $_POST['FName'];
$MName = $_POST['MName'];
$sql = "INSERT INTO tbstudinfo (Transaction_Number, First_Name, Middle_Name) VALUES ('000', '$FName', '$MName')";
if ($conn->query($sql) === TRUE) {
echo "Successfully Added";
} else {
echo "<p>Insertion Failed.</p>";
}
}
$conn->close();
答案 1 :(得分:1)
就像@executable提到的那样,您正在代码中定义查询,但不执行查询。
定义连接对象(Mysqli,PDO ..)
准备查询和绑定变量
执行查询
这是使用准备好的语句的示例
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if( isset($_POST['save']) ){
// prepare and bind
$stmt = $conn->prepare("INSERT INTO 'tbstudinfo' (Transaction_Number, First_Name, Middle_Name) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $transaction_number, $FName, $MName);
// set parameters and execute
$transaction_number = '000';
$FName= $_POST['FName'];
$MName= $_POST['MName'];
$stmt->execute();
echo "Successfully Added";
}else{
echo "<p>Nothing Posted</p>";
}
W3Schools和PHP.Net都有很好的示例,说明如何使用准备好的语句使SQL查询从SQL Injections更加安全。
答案 2 :(得分:0)
您仅进行查询,而不运行查询。此代码
$FName = $_POST['FName'];
$MName = $_POST['MName'];
$sql = "INSERT INTO tbstudioinfo (Transaction_Number, First_Name, Middle_Name) VALUES ('000','$FName','$MName')";
// code below runs your query
if (mysqli_query($conn, $sql)) {
echo "Successfully Added";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}