繁体   English   中英

PHP表格插入到MySQL

[英]php form inserting to mysql

我的PHP代码似乎无法正常工作。 昨天工作正常,但我必须进行了一些更改,现在却没有。 据我所知,导致问题的是if($ word)。 else部分起作用,它与mysql db连接,但是那条if语句不起作用。

这是PHP:

<?php
  require('connect.php');
  $word=$_POST['word'];
  $submit=$_POST['submit'];

  if($submit){
      if($word){
         mysql_query("INSERT INTO words (word) VALUES ($word)");
      }
      else{
         echo "Enter a word.";
      }
  }
?>

这是html形式:

<form name="form" id="form" method="post" action="index.php">
    <p><label>Label</label></p>
    <p><input type="text" name="word" id="word" maxlength="16"/></p>
    <p><input type="submit" name="submit" id="submit" value="Save"/></p>
</form>

您应该立即停止使用此代码。 它容易受到SQL注入的攻击。 您需要学习如何绑定参数以防止这种情况以及使用不建议使用的API。 我还建议您检查REQUEST_METHOD而不要检查$_POST['word']是否设置为空。

由于您没有任何类型的错误捕获功能,因此很难说出可能是什么问题。 如果我不得不猜测,可能是因为您在发布的变量周围缺少单引号

...INSERT INTO words (word) VALUES ('$word')...

使用参数:

<?php

if( $_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['submit']) ) {

    $link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');

    /* check connection */
    if (!$link) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

    $stmt = mysqli_prepare($link, "INSERT INTO words (word) VALUES (?)");
    mysqli_stmt_bind_param($stmt, 's', $_POST['word']);

    /* execute prepared statement */
    mysqli_stmt_execute($stmt);

    printf("%d Row inserted.\n", mysqli_stmt_affected_rows($stmt));

    /* close statement and connection */
    mysqli_stmt_close($stmt);

    /* close connection */
    mysqli_close($link);
}
?>

文档是一个很好的起点。

您很可能需要引用$word值...

INSERT INTO words (word) VALUES ('$word')

如评论中所述...

为什么我不应该在PHP中使用mysql_ *函数?

并且不要忘记输入清理。

如何防止PHP中进行SQL注入?

xkcd.com

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM