2014-12-13 87 views
-2

我想做一個網站,並通過我的'創建新學生'頁面,我嘗試使用從phpmyadmin生成的一些MySQL代碼,當我插入一個新的測試行。但是,當我執行此代碼時,它不會將其插入到我的數據庫中。PHP mysql代碼沒有執行

connection.php

<?php 

define("DB_SERVER", "localhost"); 
define("DB_USER", "root"); 
define("DB_PASS", "root"); 
define("DB_NAME", "spelling"); 

$connection = new mysqli(DB_SERVER,DB_USER,DB_PASS,DB_NAME); 

if (mysqli_connect_errno()) { 
    exit("Database connection failed: " . mysqli_connect_error());}; 
?> 

addstudent.php

<?php session_start(); 
require_once("connection.php"); 
?> 
<!DOCTYPE html> 
<html> 
<head> 
    <title> 
    Add a student 
    </title> 
</head> 
<body> 
<form action="addstudent.php" method="post"> 
     Full Name: 
     <input type="text" name="fullname" autocomplete="off"> 
     <br /> 
     Username: 
     <input type="text" name="username" autocomplete="off"> 
     <br /> 
     Password: 
     <input type="password" name="password" autocomplete="off"> 
     <br /> 
     <br /> 
     <input type="submit" value="Add Student" name="submit"> 
     </form> 
<?php 

if(isset($_POST["submit"])){ 
    $_POST = array_map("strip_tags",$_POST); 
    $_POST = array_map("trim",$_POST); 

    $fullname = $_POST["fullname"]; 
    $username = $_POST["username"]; 
    $password = $_POST["password"]; 

    $query = "INSERT INTO `spelling`.`students` (`SID`, `fullname`, `CID`, `username`, `password`) VALUES (NULL, '".$fullname."', '1', '".$username."', '".$password."')"; 
    } 
?> 
</body> 
</html> 
+0

你不執行查詢。 – Gumbo 2014-12-13 19:16:24

+0

那麼查詢在哪裏執行?編寫查詢字符串並不意味着您執行查詢。 – 2014-12-13 19:16:27

+0

除此之外,您的代碼易受SQL注入攻擊;你應該閱讀[如何在PHP中防止它們](http://stackoverflow.com/q/60174/53114)。 – Gumbo 2014-12-13 19:17:07

回答

3

你忘了執行查詢:

$query = "INSERT INTO `spelling`.`students` (`SID`, `fullname`, `CID`, `username`, `password`) VALUES (NULL, '".$fullname."', '1', '".$username."', '".$password."')"; 
$result = mysqli_query($connection, $query); 

或者在同一時間檢查錯誤。

$result = mysqli_query($connection, $query) or die(mysqli_error($connection)); 

exit("Database connection failed: " . mysqli_connect_error());}; // <= 

改變它還能去除雜散;

if (mysqli_connect_errno()) { 
    exit("Database connection failed: " . mysqli_connect_error()); 
    } 
+0

我的代碼仍然不會將學生添加到數據庫,所以問題出在哪裏? – marcnetz 2014-12-13 19:27:34

+0

檢查'mysqli_error()'查看MySQL報告錯誤 – 2014-12-13 19:33:47

+0

@marcnetz重新加載答案。變量的位置有一個小小的錯誤。 – 2014-12-14 00:20:36