2016-11-10 42 views
1

所以我無法連接或插入數據到我的數據庫中。我正在使用表單來收集我需要的信息。然後我嘗試插入到我的數據庫中。我不確定問題是什麼,但我認爲我在連接時遇到了問題。我正在使用兩個文件來嘗試完成此操作。你如何使用php插入到mysql數據庫?

addQuite.html文件

<!DOCTYPE html> 
<html> 
<head> 
    <title>AddQuote</title> 
    <link href="styles.css" type="text/css" rel="stylesheet" /> 
</head> 

<body> 

<h2> Add a Quote <h2> 

    <form action="index.php" method="get"> 
     <div> 
      Quote:<br> 

      <textarea rows="6" cols="60" name="quote" id="quote"> 

      </textarea> 

      <br> 

      Author: <input type="text" name="author" id="author"/> <br> 

      <input class = "input2" type="submit" value="Save Quotation"/> 
     </div> 
    </form> 
    </body> 


    </html> 

這是我的index.php文件這是我在哪裏嘗試連接,並插入到我的數據庫

<!DOCTYPE html> 
    <html> 
    <head> 
    <title>Quotes</title> 
    <link href="styles.css" type="text/css" rel="stylesheet" /> 
    </head> 

    <body> 


<h1> Quotes </h1> 

<form action="addQuote.html"> 
<input class="input1" type="submit" value="Add Quote"/> 
</form> 

<?php 
//connet to server 
$db = new PDO("mysql:host=server;dbname=quotes", "root" , ""); 

//check connections 
if($db===false){ 
    die("ERROR: Could not connect. "); 
} 

//get name and quote 
$name = $_GET['author']; 
$quote = $_GET['quote']; 

//attemp insert query execution 
$sql = "INSERT INTO quotations (name, quote, rating) VALUES 
('$name', '$quote', 0)"; 

?> 

</body> 


</html> 
+0

如果您在本地系統中運行代碼,請檢查您的主機名,通常它是'localhost'。 –

+0

你目前的代碼很容易被sql注入。你應該確保這不會通過準備或逃避而發生 –

回答

0

在下面的例子中

看看
<?php 
$servername = "localhost"; 
$username = "username"; 
$password = "password"; 
$dbname = "myDBPDO"; 

try { 
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); 
    // set the PDO error mode to exception 
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    $sql = "INSERT INTO MyGuests (firstname, lastname, email) 
    VALUES ('John', 'Doe', '[email protected]')"; 
    // use exec() because no results are returned 
    $conn->exec($sql); 
    echo "New record created successfully"; 
    } 
catch(PDOException $e) 
    { 
    echo $sql . "<br>" . $e->getMessage(); 
    } 

$conn = null; 
?> 
0

您的查詢從未執行,請將「$ db-> exec($ sql);」添加到您的代碼中。

<?php 
//connet to server 
$db = new PDO("mysql:host=server;dbname=quotes", "root" , ""); 

//check connections 
if($db===false){ 
    die("ERROR: Could not connect. "); 
} 

//get name and quote 
$name = $_GET['author']; 
$quote = $_GET['quote']; 

//attemp insert query execution 
$sql = "INSERT INTO quotations (name, quote, rating) VALUES 
('$name', '$quote', 0)"; 
$db->exec($sql); 
?> 
相關問題