无法将数据放入数据库,PHP

时间:2014-01-20 06:34:49

标签: php database

有人帮助我,因为我真的很困惑为什么这个示例代码不会将数据放入数据库。是的,它可以成功连接到服务器,但它不会将数据放入数据库表,帮助,请解释。提前谢谢。

<html>
    <head></head>
    <body>
    <form method='post' action='#'>
    <table>
    <tr>
    <td>Username</td><td><input type='text' name='username'/></td>
    </tr>
    <tr>
    <td>Password</td><td><input type='password' name='password'/></td>
    </tr>
    <tr>
    <td></td><td><input type='submit' value='Login' name='button'/></td>
    </tr>
    </table>
    </form>
    <?php
    if(isset($_POST['button']))
    {
    $u_nam = $_POST['username'];
    $pw = $_POST['password'];
    echo $u_nam;
    echo $pw;
    $link = mysql_connect('localhost','root', '');
    if (!$link) {
        die('Could not connect: ' . mysql_error());
    }
    echo 'Connected successfully';
    $db_selected = mysql_select_db('test', $link);
    if (!$db_selected) {
        die ('Can\'t use for: ' . mysql_error());
    }

    $query = "INSERT INTO user VALUES(NULL,'$u_nam', '$pw')";
    mysql_query($query);
    mysql_close($link);
    }
    ?>

    </body>
    </html>

2 个答案:

答案 0 :(得分:0)

您的插入代码: $query = "INSERT INTO user VALUES(NULL,'$u_nam', '$pw')";

1:为什么你要插入NULL?如果列是主键而不是通过错误而你的数据将不会被插入。更好的想法是使用列名并离开并且不要为主列添加任何值键和自动增量。

像这样:

$query = "INSERT INTO user(a,b) VALUES('$u_nam', '$pw')";

2:尝试调试:

use mysql_error().
像这样:

$query = "INSERT INTO user VALUES('$u_nam', '$pw')";

mysql_query($query) or die(mysql_error());

答案 1 :(得分:-2)

试用此代码:

<body>
<form method='post' action='#'>

<table>
<tr>
<td>Username</td><td><input type='text' name='username'/></td>
</tr>
<tr>
<td>Password</td><td><input type='password' name='password'/></td>
</tr>
<tr>
<td></td><td><input type='submit' value='Login' name='button'/></td>
</tr>
</table>

</form>

<?php

if(isset($_POST['submit']))
{
$u_nam = $_POST['username'];
$pw = $_POST['password'];

echo $u_nam;
echo $pw;


$link = mysql_connect('localhost','root', '');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';


$db_selected = mysql_select_db('test', $link);
if (!$db_selected) {
    die ('Can\'t use for: ' . mysql_error());
}

$query = "INSERT INTO user VALUES('$u_nam', '$pw')";

mysql_query($query);

mysql_close($link);

}
?>

</body>

</html>