下面是我在Sublime中的代码,但数据库没有被调用。
<?php$username="root";
$password="changedpassword";$database="User";
$field1-name=$_POST['name'];
$field2-name=$_POST['password'];
$field3-name=$_POST['email'];
$field4-name=$_POST['sex'];
$field5-name=$_POST['school'];
$field6-name=$_POST['birth'];
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$query = "INSERT INTO create_user (name, password, email, sex, school, birth) VALUES('','$field1-name','$field2-name',
'$field3-name','$field4-name','$field5-name','$field6-name')";mysql_query($query);mysql_close();?>
答案 0 :(得分:0)
让我们一步一步地完成这一过程。首先,这是您当前的代码,整理起来可读:
<?php
$username = "root";
$password = "changedpassword";
$database = "User";
$field1_name = $_POST['name'];
$field2_name = $_POST['password'];
$field3_name = $_POST['email'];
$field4_name = $_POST['sex'];
$field5_name = $_POST['school'];
$field6_name = $_POST['birth'];
mysql_connect(localhost, $username, $password);
@mysql_select_db($database) or die("Unable to select database");
$query = "
INSERT INTO
create_user
(
name,
password,
email,
sex,
school,
birth
)
VALUES
(
'',
'$field1_name',
'$field2_name',
'$field3_name',
'$field4_name',
'$field5_name',
'$field6_name'
)
";
mysql_query($query);
mysql_close();
?>
我只进行了两次更改(整理了空白,并使用_name
代替-name
,因为PHP变量不能包含连字符),但它已经有了很大的改进。代码不再是一个眼睛。它没有语法错误,并且可读。但是,仍然存在大量问题。
首先,您看到我们将七个值插入六列。这将是一个问题。通过删除第一个空白值来解决此问题:
$query = "
INSERT INTO
create_user
(
name,
password,
email,
sex,
school,
birth
)
VALUES
(
'$field1_name',
'$field2_name',
'$field3_name',
'$field4_name',
'$field5_name',
'$field6_name'
)
";
现在我们有了可能真正有用的东西。它非常不安全,具有巨大的SQL注入攻击潜力,并且它不会使用最新的PHP,因为mysql_
函数已被删除,但它实际上可能在某处工作。你不想把它投入生产,但出于测试目的,我们已经到了某个地方。
答案 1 :(得分:0)
MySQL自PHP 5.6以来已被弃用且不安全,请改用PDO或MySQLi。
与MySQLi连接
<?php
//MySQLi information
$db_host = "localhost";
$db_username = "username";
$db_password = "password";
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die("Error " . mysqli_error());
//select MySQLi dabatase table
$db = mysqli_select_db($connection, "table") or die("Error " . mysqli_error());
$field1_name = $_POST['name'];
$field2_name = $_POST['password'];
$field3_name = $_POST['email'];
$field4_name = $_POST['sex'];
$field5_name = $_POST['school'];
$field6_name = $_POST['birth'];
$query = mysqli_query($connection, "INSERT INTO create_user
(name, password, email, sex, school, birth ) VALUES
(
'$field1_name',
'$field2_name',
'$field3_name',
'$field4_name',
'$field5_name',
'$field6_name'
)
");
使用它,你会很好。我希望这对你有帮助!