2017-08-27 82 views
3

正如我使用PHP連接到MySQL數據庫。我嘗試連接到數據庫,同樣我想在我的表單上單擊登錄按鈕時將數據插入數據庫。但是當我嘗試這段代碼時沒有顯示任何更改,所以請給予幫助。謝謝你..連接並插入到Mysql數據庫使用php

<?php 
     $servername = "localhost"; 
     $username = "root"; 
     $password = "password"; 
     $conn = new PDO("mysql:host=$servername;dbname=Akalpa", $username, $password); // connection to my sql database 

     if(isset($_POST['Log In'])){ 
      $username=$_POST['username']; 
      $query = "Insert into User(username) values('$username')"; //query to insert to db 

      if (mysql_query($query)) //checking the query 
      { 
       echo"<h3>Inserted Successfully</h3>"; //value inserted to db successfully   
      }  


     } 
    ?> 
+0

只需用'$ conn-> query($ query)'替換'mysql_query($ query)''看看Jack M的答案,因爲你應該做的更安全。 –

回答

2

看起來好像你正在做一個PDO連接,但使用mysql_函數。 你應該把你的代碼寫成這樣。

<?php 
     $servername = "localhost"; 
     $username = "root"; 
     $password = "password"; 
     $conn = new PDO("mysql:host=$servername;dbname=Akalpa", $username, $password); // connection to my sql database 

    if(isset($_POST['Log In'])){ 
     $username=$_POST['username']; 
     $query = "INSERT INTO User(username) VALUES(:username)"; //query to insert to db 
     $stmt = $conn->prepare($query); 
     $result = $stmt->execute(["username"=>$username]); 
     if ($result) //checking the query 
     { 
      echo"<h3>Inserted Successfully</h3>"; //value inserted to db successfully   
     } else { 
      die("query failed"); 
     }  


    } 
?> 

您的原始代碼容易受到SQL注入的影響,這並不好。我也不會推薦使用$ _POST [「Log In」],因爲在數組鍵中有空格是可怕的做法。嘗試一些比較簡單的方法,比如「submit」或者「login」。