简体   繁体   中英

php form inserting to mysql

My php code doesn't seem to be working. 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. The else part functions and it's connecting with the mysql db but that one if statement does nothing.

Here's the 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:

<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. You need to learn how to bind parameters to prevent this as well as use a non-deprecated API. I would also recommend that you check REQUEST_METHOD rather than if $_POST['word'] is set as it can be empty.

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...

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

As mentioned in the comments...

Why shouldn't I use mysql_* functions in PHP?

And don't forget about input sanitization.

How can I prevent SQL injection in PHP?

xkcd.com

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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