php php如何在数据库中插入数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6659672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:56:03  来源:igfitidea点击:

How to insert data in database using php

phpsql-server

提问by user99

I have just started to work with php. I write a simple code in php to insert data in a table customer. I am using mssql database.

我刚刚开始使用 php。我在php中编写了一个简单的代码来在表customer中插入数据。我正在使用 mssql 数据库。

<?php
function InsertData()
{
    $link = mssql_connect('db','123','test');

    if (!$link || !mssql_select_db('php', $link)) 
        {
        die('Unable to connect or select database!');
        }

    $sql = " INSERT INTO customer ([Name],[Website])VALUES('$txtName','$txtWebsite')";
    $result = mysql_query($sql, $link);
    if(!$result)
        {
        echo mysql_error();
        exit;
        }
    // close the connection
    mysql_free_result($result); 
    mysql_close();
    echo "Data successfully inserted";
}
?>
      <table border="0" cellpadding="0" cellspacing="0" width="100%">                
        <tr>
          <td colspan="3" height="10" valign="top" width="98%"></td>
       </tr> 
       <tr>
         <td width="22%">   &nbsp;Name:</td>
         <td width="60%"><INPUT type="text" name="txtName" id="txtName" Width="200px" MaxLength="30" /> </td>
       </tr>
      <tr>
         <td colspan="3" height="12" valign="top" width="98%"></td>
      </tr> 
      <tr>
         <td width="22%">   &nbsp;Company Website:</td>
         <td width="60%"><INPUT type="text" name="txtWebsite" id="txtWebsite" width="200px" MaxLength="200" /> </td>                 
      </tr>   
      <tr>
         <td > </td>
         <td > <input type="button" value="submit" id="imgBtnSubmit" click="InsertData()"/> </td>
     </tr>
 </table>

I have written above code to insert data into the table and I am calling InsertData function on onClick event of submit button but on clicking button data is not getting inserted into the table. Please anyone tell me where is the problem in this code.

我已经编写了上面的代码来将数据插入表中,并且我在提交按钮的 onClick 事件上调用 InsertData 函数,但是在单击按钮时数据没有被插入到表中。请任何人告诉我这段代码的问题在哪里。

回答by Francois Deschenes

There are a few problems with your code.

您的代码存在一些问题。

  • You're missing the <form>as pointed out by Tudor Constantin.
  • The other problem is that you can't use the onclickevent of an element to trigger PHP code as you're done above. The onclickevent is for JavaScript (or other client side scripting languages like VBScript).
  • Additionally, make sure that you use the functions that start with mssqland not mysqlif you use Microsoft SQL Server. The functions are not interchangeable.
  • 您错过了<form>都铎·康斯坦丁 (Tudor Constantin) 所指出的。
  • 另一个问题是您不能像上面那样使用onclick元素的事件来触发 PHP 代码。该onclick事件适用于 JavaScript(或其他客户端脚本语言,如 VBScript)。
  • 此外,请确保您使用与启动功能mssql,而不是mysql如果您使用Microsoft SQL Server。功能不可互换。

Here's a short example:

这是一个简短的例子:

<?php

// The request method is POST.
if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
  // Connect to the database
  $link = mssql_connect('db','123','test');

  // Do more stuff with the database.
}

?>

<form method="POST" action="/path/to/this/file.php">
  <input type="text" name="example" />
  <input type="submit" value="Send" />
</form>

When you click the "Send" button, the form will be POSTed to /path/to/this/file.php. By checking that the request method is "POST", you can then connect to the database and insert records accordingly.

当您单击“发送”按钮时,表单将被发送到 /path/to/this/file.php。通过检查请求方法是否为“POST”,您可以连接到数据库并相应地插入记录。

Checking for $_SERVER['REQUEST_METHOD']is one of many ways you can do this. You could also check that a value for an particular input was set using if ( ! empty($_REQUEST['input_name']) ) { ... }.

检查$_SERVER['REQUEST_METHOD']是您可以执行此操作的众多方法之一。您还可以检查是否使用 设置了特定输入的值if ( ! empty($_REQUEST['input_name']) ) { ... }

回答by Winfield Trail

As the previous answer states, you don't actually have submission logic. What's at least equally important is that you, by your own admission, do not have a MySQL server.MySQL and MS-SQL are different and not at all equivalent. You can't use PHP MySQL commands or the MySQL extension to talk to MS-SQL.

正如上一个答案所述,您实际上没有提交逻辑。至少同样重要的是,您自己承认,您没有 MySQL 服务器。MySQL 和 MS-SQL 是不同的,根本不等价。您不能使用 PHP MySQL 命令或 MySQL 扩展来与 MS-SQL 对话。

You're using MS-SQL functions here:

您在这里使用 MS-SQL 函数:

 $link = mssql_connect('db','123','test');

    if (!$link || !mssql_select_db('php', $link)) 
        {
        die('Unable to connect or select database!');
        }

and then MySQL here:

然后在这里使用 MySQL:

  $sql = " INSERT INTO customer ([Name],[Website])VALUES('$txtName','$txtWebsite')";
    $result = mysql_query($sql, $link);
    if(!$result)
        {
        echo mysql_error();
        exit;
        }
    // close the connection
    mysql_free_result($result); 
    mysql_close();
    echo "Data successfully inserted";

...and, as yet another answer states, you're trying to use Javascript to call a PHP function.

...而且,正如另一个答案所述,您正在尝试使用 Javascript 来调用 PHP 函数。

You therefore have twothree problems - well, technically one problem. I suggest you read a FAQ on MS-SQL in PHP at the very least, and ideally complete Javascript and PHP tutorials. There is no way that we can provide an answer that you can use short of writing your program for you, as you - and I swear I'm not being unpleasant here, I know you're doing your best - just don't have the knowhow to put it together yet. Google is your friend here. Good luck.

因此,您有两个三个问题 - 好吧,技术上是一个问题。我建议您至少阅读有关 PHP 中 MS-SQL 的常见问题解答,最好阅读完整的 Javascript 和 PHP 教程。除了为您编写程序之外,我们无法提供您可以使用的答案,因为您 - 我发誓我不会在这里感到不快,我知道您正在尽力而为 - 只是没有把它放在一起的诀窍。谷歌是你的朋友。祝你好运。

回答by Tom Gillard

As many have already mentioned there are a few errors in your code. My solution to your question offers a different approach.

正如许多人已经提到的那样,您的代码中存在一些错误。我对您问题的解决方案提供了一种不同的方法。

Rather than calling the InsertData() method you can do something else in the one php document.

您可以在一个 php 文档中执行其他操作,而不是调用 InsertData() 方法。

This is done by using an if/else statement, assigning 'submit' to the name value of the submit button as well as the special PHP variable $_SERVER['PHP_SELF'].

这是通过使用 if/else 语句完成的,将“提交”分配给提交按钮的名称值以及特殊的 PHP 变量 $_SERVER['PHP_SELF']。

First, the server checks if the form has been submitted.
When the page is first loaded this will return false and the form is displayed for them to fill out

首先,服务器检查表单是否已提交。
当页面第一次加载时,这将返回 false 并显示表单供他们填写

When the user clicks the submit button the form reloads the page and runs the PHP script again. This time the if statement returns true as the form HAS been submitted so it executes the part of the script that inserts the data in MSSQL and displays the successful message.

当用户单击提交按钮时,表单会重新加载页面并再次运行 PHP 脚本。这次 if 语句返回 true,因为表单已提交,因此它执行将数据插入 MSSQL 的脚本部分并显示成功消息。

Check out the code below:

看看下面的代码:

<?php
if (isset($_POST['submit'])){
    //connect to the database 
    $link = mssql_connect('db','123','test');    
    //display error if database cannot be accessed 
    if (!$link || !mssql_select_db('php', $link)) 
    {
        die('Unable to connect or select database!');
    }
    //assign form input to variables
    $txtName = $_POST['txtName'];
    $txtWebsite = $_POST['txtWebsite'];
    //SQL query to insert variables above into table
    $sql = " INSERT INTO customer ([Name],[Website])VALUES('$txtName','$txtWebsite')";
    $result = mssql_query($sql, $link);
    //if the query cant be executed
    if(!$result)
    {
        echo mssql_error();
        exit;
    }
    // close the connection
    mssql_free_result($result); 
    mssql_close();
    echo "Data successfully inserted";
}
else { ?>
    <form name="input" action="$_SERVER['PHP_SELF']" method="POST">
        <table border="0" cellpadding="0" cellspacing="0" width="100%">                
            <tr>
                <td colspan="3" height="10" valign="top" width="98%"></td>
            </tr> 
            <tr>
                <td width="22%">Name:</td>
                <td width="60%"><INPUT type="text" name="txtName" id="txtName" Width="200px" MaxLength="30" /> </td>
           </tr>
           <tr>
                <td>Company Website:</td>
                <td><INPUT type="text" name="txtWebsite" id="txtWebsite" width="200px" MaxLength="200" /></td>                 
           </tr>   
           <tr>
                <td><input type="button" name="submit" value="submit" /></td>
           </tr>
        </table>
    </form>
<?php } ?>

Give that a try. There's some great PHP tutorials that go over the fundamentals here: http://devzone.zend.com/article/627

试一试吧。这里有一些很棒的 PHP 教程,它们涵盖了基础知识:http: //devzone.zend.com/article/627

Hope that all helped.

希望对大家有所帮助。

回答by Tudor Constantin

It looks like you don't have a <form>in your page - the data is not getting to your server.

看起来<form>您的页面中没有 - 数据未到达您的服务器。

Also, you are not reading the input anywhere - how do you fill your $txtNameand $txtWebsitewith meaningful values?

此外,您没有在任何地方读取输入 - 您如何用有意义的值填充您的$txtName$txtWebsite

Also, InsertDatais a PHP function, which is executed on the server side- your HTML part is interpreted on the client side(in the browser). You can't call that function there.

此外,InsertData还有一个 PHP 函数,它在服务器端执行- 您的 HTML 部分在客户端(在浏览器中)进行解释。你不能在那里调用那个函数。

Try with this:

试试这个:

<?php
function InsertData()
{
    $link = mssql_connect('db','123','test');

if (!$link || !mssql_select_db('php', $link)) 
{
    die('Unable to connect or select database!');
}
$txtName = $_REQUEST['txtName'];
$txtWebsite = $_REQUEST['txtWebsite'];

$sql = " INSERT INTO customer ([Name],[Website])VALUES('$txtName','$txtWebsite')";
$result = mssql_query($sql, $link);
if(!$result)
{
echo mssql_error();
exit;
}
// close the connection
mssql_free_result($result); 
mssql_close();
echo "Data successfully inserted";
}

if ($_REQUEST['txtName'] > ''){
 InsertData();
}
?>
<form name="input" action="this_file_name.php" method="get">
      <table border="0" cellpadding="0" cellspacing="0" width="100%">                
        <tr>
          <td colspan="3" height="10" valign="top" width="98%"></td>
       </tr> 
       <tr>
         <td width="22%">   &nbsp;Name:</td>
         <td width="60%"><INPUT type="text" name="txtName" id="txtName" Width="200px" MaxLength="30" /> </td>
       </tr>
      <tr>
         <td colspan="3" height="12" valign="top" width="98%"></td>
      </tr> 
      <tr>
         <td width="22%">   &nbsp;Company Website:</td>
         <td width="60%"><INPUT type="text" name="txtWebsite" id="txtWebsite" width="200px" MaxLength="200" /> </td>                 
      </tr>   
      <tr>
         <td > </td>
         <td > <input type="button" value="submit" id="imgBtnSubmit" /> </td>
     </tr>
 </table>
</form>