简体   繁体   English

PHP表格插入到MySQL

[英]php form inserting to mysql

My php code doesn't seem to be working. 我的PHP代码似乎无法正常工作。 Was functioning yesterday but I must have changed something and now it isn't. 昨天工作正常,但我必须进行了一些更改,现在却没有。 As far as I can tell it's the if($word) that's causing the problem. 据我所知,导致问题的是if($ word)。 The else part functions and it's connecting with the mysql db but that one if statement does nothing. else部分起作用,它与mysql db连接,但是那条if语句不起作用。

Here's the php: 这是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.";
      }
  }
?>

and this is the html form: 这是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>

You should immediately stop using this code. 您应该立即停止使用此代码。 It is vulnerable to SQL injection. 它容易受到SQL注入的攻击。 You need to learn how to bind parameters to prevent this as well as use a non-deprecated API. 您需要学习如何绑定参数以防止这种情况以及使用不建议使用的API。 I would also recommend that you check REQUEST_METHOD rather than if $_POST['word'] is set as it can be empty. 我还建议您检查REQUEST_METHOD而不要检查$_POST['word']是否设置为空。

Since you don't have any type of error catch functions, it is difficult to tell what could be the problem. 由于您没有任何类型的错误捕获功能,因此很难说出可能是什么问题。 If I had to guess, it's probably because you're missing single quotes around your posted variable: 如果我不得不猜测,可能是因为您在发布的变量周围缺少单引号

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

Using parameters: 使用参数:

<?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);
}
?>

The documentation is a good place to start. 文档是一个很好的起点。

You most likely need to quote your $word value... 您很可能需要引用$word值...

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

As mentioned in the comments... 如评论中所述...

Why shouldn't I use mysql_* functions in PHP? 为什么我不应该在PHP中使用mysql_ *函数?

And don't forget about input sanitization. 并且不要忘记输入清理。

How can I prevent SQL injection in PHP? 如何防止PHP中进行SQL注入?

xkcd.com

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

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