PHP数据保存到数据库

时间:2014-01-15 22:31:37

标签: php database save

==>的index.php:

<form action="anotherpage.php" method="POST"/>
<br>Username: <input type="text" name="user_name"><br><br>
Password: <input type="password" name="pwd"><br><br>
Repeat:   <input type="password" name="pwd2"><br><br>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female<br><br>
<input type="submit" value="Submit">
</form>

这是我的index.php,我创建了一个“anotherpage.php”。

==&GT; anotherpage.php

<?php

define('DB_NAME', 'test');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');

$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);

if (!$link) {
    die('Could not connect: '. mysql_error());
}

$db_selected = mysql_select_db(DB_NAME, $link);

if (!$db_selected) {
    die('Can\'t use '.DB_NAME.': '.mysql_error());
}

echo 'Connected successfully!<br>';

$username = mysql_real_escape_string($_POST['user_name']);
$password = mysql_real_escape_string($_POST['pwd']);
$sexuality = mysql_real_escape_string($_POST['sex']);

$sql = "INSERT INTO users (username, password, sexuality) VALUES ('".$username."','".$password."','".$sexuality."')";

if (!mysql_query($sql)) {
    die('Error: '. mysqli_error($con));
}

if(isset($_POST['user_name']) &&! empty($_POST['user_name']) && isset($_POST['pwd2']) &&! empty($_POST['pwd2']) && isset($_POST['pwd']) &&! empty($_POST['pwd']) && isset($_POST['sex']) &&! empty($_POST['sex']) or die('PART\'S ARE NOT FILLED!')) 
{
    $user_name = $_POST['user_name'];
    $user_name_up = strtoupper($user_name);
    $pwd = $_POST['pwd'];
    $pwd2 = $_POST['pwd2'];
    $sex = $_POST['sex'];

    $fp = fopen("formdata.txt", "a");
    $savestring = $user_name . "," . $pwd.",".$pwd2.",".$sex." - ";
    fwrite($fp, $savestring);
    fclose($fp);
}
if($pwd == $pwd2 or die('DIFFERENT PASSWORDS!'))
{
    echo $user_name_up.' ALL TAKEN!<BR>THANK YOU!!!<br><h1>You data has been saved!</h1>';
}


?>

我现在可以将输入保存到数据库中。但是,如果我的if语句成真,那么我想这样想。否则,即使密码不匹配,我也将输入保存到数据库中。我怎么能这样做?

如果我更改了代码的位置,我会收到错误。

现在感谢万分! :)

1 个答案:

答案 0 :(得分:0)

请注意sql注射,请阅读治疗How can I prevent SQL injection in PHP?

sql放错位置,下面的部分必须放在保存文件的if语句中。

$sql = 'INSERT INTO users (username, password, sexuality) VALUES ("$_POST[user_name]","$pwd","$sex")';

if (!mysql_query($sql)) {
      die('Error: '. mysqli_error($con));
}

您还更改了引号并添加字符串连接以使其正常工作

$sql = "INSERT INTO users (username, password, sexuality) VALUES ('".$_POST['user_name']."','".$pwd."','".$sex."')";

if (!mysql_query($sql)) {
      die('Error: '. mysqli_error($con));
}

但请注意,上面的代码仍然不安全,下面的代码更安全

$username = mysql_real_escape_string($_POST['user_name']);
$password = mysql_real_escape_string($pwd);
$sexuality = mysql_real_escape_string($sex);

$sql = "INSERT INTO users (username, password, sexuality) VALUES ('".$username."','".$password."','".$sexuality."')";

将密码直接保存到数据库中并不明智,请阅读以下How to change a SALT password in a database using PHP?