0

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

2
  • Oops! PHP is not a natural event driven scripting language. Is that your real code? Commented Jul 12, 2011 at 5:04
  • Is it your real code? You cannot use mssql_connect + mysql_query and expect it to work... It's either a misprint in your question or something really goes wrong (even though mysql and mssql spells similarly, they are different ). Commented Jul 12, 2011 at 5:19

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

@user99: Also keep in mind that the code you've posted is prone to sql injections. One way to avoid that is to use prepared statements/named parameters like you can do with microsoft's PDO_SQLSRV driver, see msdn.microsoft.com/en-us/library/ff628175.aspx
3

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.

Comments

2

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.

Comments

1

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>

6 Comments

Moreover, I don't see whereInsertData is called
InsertData() is called on Submit button onClick event
i think you cant call InsertData() like this
Then how should i call the function
Have you tried the code I have written? Have you read any introduction to a PHP tutorial?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.