php - 你如何使用php插入到mysql数据库中?

标签 php mysql forms post

所以我在连接或插入数据到我的数据库时遇到了问题。我正在使用表格来收集我需要的信息。然后我尝试插入到我的数据库中。我不确定问题出在哪里,但我想我在连接时遇到了问题。我正在使用两个文件来尝试完成此操作。

添加Quite.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>

最佳答案

看看下面的例子

<?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', 'john@example.com')";
    // 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;
?>

关于php - 你如何使用php插入到mysql数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40519987/

相关文章:

php - ZF2 应用程序范围的 var(自定义唯一请求 id)

php - 查找两行中共同的数据,数据之间用逗号分隔

C# anchor 属性似乎不起作用

javascript - 如何获取div元素值

ruby-on-rails - 如何在不使用 form_for 和模型实例的情况下在 Rails 中创建表单?

php strtotime 返回 1970-01-01

php - 将 utf-8 编码的参数从 PHP 传递给 casper JS

php - mysqli_multi_query 数据库类错误

mysql - 我如何合并/加入然后用 mongodb 排序

php - SQL 按重复行计数和排序