使用PHP和MySQLi

时间:2017-02-17 11:28:19

标签: php variables mysqli

抱歉,如果这是非常基本的,但我已经在圈子里走了一段时间。我是PHP的新手,但是没有一个文档似乎有帮助,这里没有任何一个问题可以解释它。

我正在尝试创建一个简单的表单,它接受用户输入并在数据库中创建记录,但我所拥有的代码似乎并不认识提供的变量。当我使用字符串时,插入操作完成,所以我知道连接不是问题。

我没有收到任何错误消息 - 页面刷新,好像什么都没发生一样。

<form action="" method="post">
    <input type="text" name="new_word" id="word" required="required"/>
    <input type="text" name="book_ref" id="book" required="required"/>
    <input type="text" name="page_range" id="page" required="required"/>
    <input type="submit" value="Submit" name="submit"/>
</form>
<?php
if(isset($_POST["submit"])){
    $servername = "localhost";
    $username = "user";
    $password = "pass";
    $dbname = "database";
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $stmt = $conn->prepare("INSERT INTO `words` (`Word`, `Book ID`, `Page`) 
VALUES (?,?,?)");
    $stmt->bind_param(1, $word);
    $stmt->bind_param(2, $book);
    $stmt->bind_param(3, $page);
    $word = $_POST["new_word"];
    $book = $_POST["book_ref"];
    $page = $_POST["page_range"];
    $stmt->execute();
    $conn->close();
}
?>

4 个答案:

答案 0 :(得分:2)

您需要在使用它们之前定义变量。

您的代码应如下所示:

$word = $_POST["new_word"];
$book = $_POST["book_ref"];
$page = $_POST["page_range"];

$stmt = $conn->prepare("INSERT INTO `words` (`Word`, `Book ID`, `Page`) 
VALUES (?,?,?)");
$stmt->bind_param("sss", $word, $book, $name);
$stmt->execute();
$conn->close();

答案 1 :(得分:0)

您必须先分配值然后再使用它们。

$word = $_POST["new_word"];
$book = $_POST["book_ref"];
$page = $_POST["page_range"];    

$stmt = $conn->prepare("INSERT INTO `words` (`Word`, `Book ID`, `Page`) 
VALUES (?,?,?)");
$stmt->bind_param(1, $word);
$stmt->bind_param(2, $book);
$stmt->bind_param(3, $page);



$stmt->execute();

$conn->close();

答案 2 :(得分:0)

试试这个

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="new_word" id="word" required="required"/>
<input type="text" name="book_ref" id="book" required="required"/>
<input type="text" name="page_range" id="page" required="required"/>
<input type="submit" value="Submit" name="submit"/>
</form>

<?php
if(isset($_POST["submit"])){
  $servername = "localhost";
  $username = "user";
  $password = "pass";
  $dbname = "database";
  $conn = new mysqli($servername, $username, $password, $dbname);
  if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
  }
$word = $_POST["new_word"];
$book = $_POST["book_ref"];
$page = $_POST["page_range"];
 $stmt = $conn->prepare("INSERT INTO `words` (`Word`, `Book ID`, `Page`) VALUES (?,?,?)");
$stmt->bind_param(1, $word);
$stmt->bind_param(2, $book);
$stmt->bind_param(3, $page);
$stmt->execute();
$conn->close();
}
?>

答案 3 :(得分:0)

为什么不这样写:

$stmt->bind_param('sss', $_POST['new_word'], $_POST['book_ref'], $_POST['page_range']);

它将插入每个元素而不创建多余的变量,并且因为看起来所有POST内容都来自文本字段,所以它们都是所有字符串。如果只有数字,您可以将相应的s更改为d