如何使用php向数据库中插入数据

发布于 2024-11-19 16:56:25 字数 1753 浏览 0 评论 0原文

我刚刚开始使用 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>

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

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
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%">    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%">    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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

俯瞰星空 2024-11-26 16:56:25

您的代码存在一些问题。

  • 正如 Tudor Constantin 指出的那样,您缺少
  • 另一个问题是您无法像上面那样使用元素的 onclick 事件来触发 PHP 代码。 onclick 事件适用于 JavaScript(或其他客户端脚本语言,如 VBScript)。
  • 此外,如果您使用 Microsoft SQL Server,请确保使用以 mssql 开头的函数,而不是 mysql 开头的函数。这些功能不可互换。

这是一个简短的示例:

<?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>

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

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

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 onclick event of an element to trigger PHP code as you're done above. The onclick event is for JavaScript (or other client side scripting languages like VBScript).
  • Additionally, make sure that you use the functions that start with mssql and not mysql if you use Microsoft SQL Server. The functions are not interchangeable.

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.

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']) ) { ... }.

闻呓 2024-11-26 16:56:25

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

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

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

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

然后在这里使用 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";

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

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

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.

You're using MS-SQL functions here:

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

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

and then MySQL here:

  $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.

You therefore have two three 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.

溺孤伤于心 2024-11-26 16:56:25

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

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

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

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

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

查看下面的代码:

<?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 } ?>

尝试一下。这里有一些很棒的 PHP 教程,介绍了基础知识:
http://devzone.zend.com/article/627

希望一切有所帮助。

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.

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'].

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

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.

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

Hope that all helped.

最舍不得你 2024-11-26 16:56:25

您的页面中似乎没有

- 数据未到达您的服务器。

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

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

尝试用这个:

<?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%">    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%">    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>

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

Also, you are not reading the input anywhere - how do you fill your $txtName and $txtWebsite with meaningful values?

Also, InsertData is 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.

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%">    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%">    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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文