我不能得到表单数据进入数据库。我究竟做错了什么? [英] I cant get the form data to go into database. What am I doing wrong?

查看:159
本文介绍了我不能得到表单数据进入数据库。我究竟做错了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码已更新,尚未运作。
我知道我显然使用mysql函数,这将是过时的。但现在我想要的是让这个代码工作。我想知道我做错了什么:(



我对php和数据库非常新...我一直在努力得到简单的html表单数据进入数据库表,我只是不能得到它的工作:(任何人可以帮助,看看我的代码是什么错了我只是做了一个简单的表在数据库中的字段ID,FIRSTNAME和SURNAME。
这是代码:

 <?php 
//连接到数据库
$ mysql_host ='localhost';
$ mysql_user ='root';
$ mysql_pass ='';

$ mysql_db ='test';

if(!mysql_connect($ mysql_host,$ mysql_user,$ mysql_pass)||!mysql_select_db($ mysql_db)){
die(mysql_error());

}
b $ b //代码
if(isset($ _ POST ['firstname'])&&
isset($ _ POST ['surname'])){

$ firstname = $ _POST ['firstname'];
$ surname = $ _POST ['surname'];

if(!empty($ username)&&!empty密码)){
$ query =INSERT INTO`test`.`testtestabab'
VALUES('','。 mysql_real_escape_string($ firstname)。 ','。 mysql_real_escape_string($ surname)。 ');
/ * $ query =INSERT INTO`test`.`test_tabell` VALUES(``,`。$ firstname.`,`。$ surname.`); * /
$ query_run = mysql_query($ query);
if(!$ query_run)echo mysql_error();
}
}
?>

< form action =add.phpmethod =POST>
名字:< br> < input type =textname =firstnamevalue =<?php if(isset($ firstname)){echo $ firstname;}?""< br>
姓氏:< br> < input type =textname =surnamevalue =<?php if(isset($ surname)){echo $ surname;}?""< br>
< input type =submitvalue =Submit>
< / form>

谢谢!

解决方案

不要使用mysql特定的语法,它已经过时,当你需要做一些高级的东西,它开始烦人,你不能切换到sqlite或postgresql。



我建议使用PDO,你可以这样做:

  //用法:$ db = connectToDataBase($ dbHost,$ dbName,$ dbUsername,$ dbPassword); 
// Pre:$ dbHost是数据库主机名,
// $ dbName是数据库本身的名称,
// $ dbUsername是访问数据库的用户名,
// $ dbPassword是数据库用户的密码。
// Post:$ db是基于输入参数的到数据库的PDO连接。
函数connectToDataBase($ dbHost,$ dbName,$ dbUsername,$ dbPassword)
{
try
{
return new PDO(mysql:host = $ dbHost; dbname = $ dbName; charset = UTF-8,$ dbUsername,$ dbPassword);
}
catch(PDOException $ PDOexception)
{
exit(< p>发生错误:无法连接到数据库。< / p>< p> ; More preciesly:。$ PDOexception-> getMessage()。< / p>);
}
}

然后init的变量(我想你忘了定义数据库的名称);

  $ host ='localhost'; 
$ user ='root';
$ dataBaseName ='databaseName';
$ pass ='';

现在您可以通过

访问您的数据库

  $ GLOBALS ['db'] = connectToDataBase($ host,$ databaseName,$ user,$ pass); 

现在您有一个PDO数据库连接的实例。



我要指出的一点是,你可以对sql注入进行vonable,你想在查询中使用预处理语句,例如:

  $ query =INSERT INTO test(first_name,sur_name)VALUES(:firstname,:surname);; 

我们将对查询执行两个变量$ firstName和$ surName, :firstName和:surName,让我通过创建一个简单的插入函数告诉你:

  function insertFunction($ db,$ query ,$ firstName,$ surName)
{
$ statement = $ db-> prepare($ query);
return $ statement-> execute(array(:firstName=> $ firstName,:surName=> $ surName)
}

因此,您可以轻松地执行

  $ firstName ='Smith'; 
$ surName ='John';
$ db = $ GLOBALS ['db'];

$ success = insertFunction($ db,$ query,$ firstName,$ surName);

现在你可以通过检查$ success是true还是false来检查它是否成功。



如果您想要更高级地使用PDO(多行等),那么您可以在这里查看我的一个注释: Javascript函数为php?
(不是顶部注释)。



<我希望这有助于。如果有什么奇怪,请评论。


CODE UPDATED, STILL NOT WORKING. I know I´m apparently using mysql function which will be outdated. But for now all I want is for this code to work. I want to know what I´m doing wrong:(

I´m very new to php and databases... I have been struggling to get simple html form data to go into the database table. And I just can´t get it to work:( Can anyone help and see what is wrong with my code? I´ve just done a simple table in the database with the fields ID, FIRSTNAME and SURNAME. Here is the code:

    <?php 
    //connect to database
    $mysql_host = 'localhost';
    $mysql_user = 'root';
    $mysql_pass = '';

    $mysql_db = 'test';

    if (!mysql_connect ($mysql_host, $mysql_user, $mysql_pass)||!mysql_select_db ($mysql_db) ) {
        die(mysql_error());

    }   

    // Code     
    if (isset($_POST['firstname'])&&
    isset($_POST['surname'])) {

    $firstname = $_POST['firstname'];
    $surname = $_POST['surname'];

    if (!empty($username)&&!empty($password)) {
    $query = "INSERT INTO `test`.`test_tabell` 
    VALUES ('', '" . mysql_real_escape_string($firstname) . "', '" . mysql_real_escape_string($surname) . "')";
    /*$query = "INSERT INTO `test`.`test_tabell` VALUES (``, `.$firstname.`, `.$surname.`)"; */
    $query_run = mysql_query($query);
if (!$query_run) echo mysql_error(); 
}
}
    ?>

    <form action="add.php" method="POST">
    Firstname:<br> <input type="text" name="firstname" value="<?php if (isset($firstname)) { echo $firstname; } ?>"><br><br>
    Surname:<br> <input type="text" name="surname" value="<?php if (isset($surname)) { echo $surname; } ?>"><br><br>
    <input type="submit" value="Submit">
    </form> 

Thank you!

解决方案

Don't use mysql specific syntax, It's outdated and it begins to be annoying when you need to do some high level stuff, and you can't switch to sqlite or postgresql.

I recommend using PDO, you can do something like:

// Usage:   $db = connectToDataBase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre:     $dbHost is the database hostname, 
//          $dbName is the name of the database itself,
//          $dbUsername is the username to access the database,
//          $dbPassword is the password for the user of the database.
// Post:    $db is an PDO connection to the database, based on the input parameters.
function connectToDataBase($dbHost, $dbName, $dbUsername, $dbPassword)
{
    try
    {
         return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
    }
    catch(PDOException $PDOexception)
    {
        exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
    }
}

And then init the variables (I think you forgot to define the name of the database);

$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';

Now you can access your database via

$GLOBALS['db'] = connectToDataBase($host , $databaseName, $user, $pass);

Now you have an instance of a PDO database donnection.

One thing I want to point out is that you're vonurable to sql injections, you want to use prepared statements in your query, like:

$query = "INSERT INTO test(first_name, sur_name) VALUES (:firstname, :surname);";

Where we will execute two variables $firstName and $surName on the query, making them replace the values of :firstName and :surName, let me show you by first creating a simple insertion function:

function insertFunction($db, $query, $firstName, $surName)
{
    $statement = $db->prepare($query);
    return $statement->execute(array(":firstName" => $firstName, ":surName" => $surName));
}

So It's easy for you to do something like

$firstName = 'Smith';
$surName = 'John';
$db = $GLOBALS['db'];

$success = insertFunction($db, $query, $firstName, $surName);

Now you can check if it was successful or not, by checking whether $success is true or false.

If you want to see more advanced use of PDO (multiple rows etc) then you can check out one of my comments here: Javascript function as php? (Not the top comment).

I hope this helps. Please comment if anything is odd.

这篇关于我不能得到表单数据进入数据库。我究竟做错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆