2013-02-21 97 views
0

我的php代码似乎并没有工作。昨天正在运作,但我必须改变一些东西,现在不是。据我可以告诉它是导致问题的if($ word)。 else部分的功能,它与mysql数据库连接,但一个if语句什么都不做。php表单插入到mysql

这里的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> 
+2

[**在新的代码,请不要使用'mysql_ *'功能**](http://bit.ly/phpmsql)。他们不再被维护[并且被正式弃用](http://j.mp/XqV7Lp)。看到[**红框**](http://j.mp/Te9zIL)?学习[*准备的语句*](http://j.mp/T9hLWi),并使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli) - [这篇文章](http://j.mp/QEx8IB)将帮助你决定哪个。 – Kermit 2013-02-21 18:45:03

+0

'据我可以告诉它是导致问题的if($ word) - 你能提供一些理由,你为什么认为导致了这个问题?它造成什么问题? – Growler 2013-02-21 18:45:43

+0

您的查询具有SQL注入,请参阅http://stackoverflow.com/a/60195/813069如何处理输入 – Winston 2013-02-21 18:47:56

回答

4

您应立即停止使用此代码。它容易受到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); 
} 
?> 

documentation是一个良好的开端。

+0

尽管这可能是OP的最佳答案,但您应该将他指向OOP PHP,因为他似乎对此很新颖。更好地从OOP开始,而不是仅仅学习程序,以便稍后再去挠头。 – Amelia 2013-02-21 19:00:27

+0

@Hiroto我不明白为什么我应该把他指向OOP,也不知道为什么它更好。编程风格是由OP决定的。我在答案下的评论应该足够了。 – Kermit 2013-02-21 19:02:29

1

你最有可能需要引用您$word值...

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

正如在评论中提到...

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

而且不要忘记输入清理。

How can I prevent SQL injection in PHP?

xkcd.com

+0

'INSERT INTO words SET(word)VALUES($ word)'是无效的MySQL语法。 – 2013-02-21 18:49:02

+1

OP的查询没有任何理由不起作用。 – Kermit 2013-02-21 18:49:58

+1

++为鲍比表。 – Amelia 2013-02-21 18:50:25