开发者

How to insert data in database using php

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('Un开发者_如何学JAVAable 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.


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


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.


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.


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%">   &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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜