Unable to successfully add data into an SQL database using PHP

I'm encountering an issue while attempting to insert data into the 'products' table within my SQL server. Despite my efforts, the table remains empty and I'm unsure about what's causing this problem.

Here's a snippet of my code:

<?php
/* Defining the server and connection attributes. */
$serverName = "DBIT-NB1415546\SQLEXPRESS(SQL Server 1)"; // Replace with your own SQL Server name 
$connectionInfo = array( "Databases"=>"CA1_OLTP");

/* Connecting using Windows Authentication. */
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
     echo "Unable to connect.</br>";
     die( print_r( sqlsrv_errors(), true));
}

// Retrieving JSON data from cloud DB
$json = file_get_contents("http://bi.edisonsiow.com/ay1516s2/ca1/getProducts.php");
$jsonObject = json_decode($json);

// Iterating through each record in JSON object to create corresponding entries in employees table
// inside MS SQL Server DB
foreach ($jsonObject as $key => $item ){ 
    $sql = "INSERT INTO products(productCode, productName,".
            "productLine,productScale,productVendor,".
            "productDescription,quantityInStock,buyPrice,MSRP)".
            "VALUES(?,?,?,?,?,?,?,?,?)";

    $param = array(&$item->productCode, &$item->productName, &$item->productLine, &$item->productScale, 
                   &$item->productVendor, &$item->productDescription, &$item->quantityInStock, &$item->buyPrice,
                   &$item->MSRP);

    $stmt = sqlsrv_prepare($conn, $sql, $param);

    if( sqlsrv_execute($stmt) === false ) {
        $errors = sqlsrv_errors();
        if($errors[0]['code']==2627) {
          die("Employee already exist in employeeDIM. No duplication is allowed.");
        }  
    } 
}
echo "<h3>Records Created..</h3>";

?>

Answer №1

I believe the issue might be related to the naming of the $serverName instance. It's possible that the server name should not include parentheses. To verify the server name instance, please refer to this helpful link:

Connecting to SQL Server Express - What is my server name?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having Difficulty Converting JavaScript Objects/JSON into PHP Arrays

This particular inquiry has no relation to the previously mentioned identical answer/question... In JavaScript, I am dealing with a substantial list of over 1,000 items displayed in this format... var plugins = [ { name: "Roundabout - Interac ...

PHP array containing images with redirection

There is a file called foo.txt that contains the locations of various pictures. http://foo/bar1.png http://foo/bar2.png http://foo/bar3.png When displaying these pictures using an array, some are missing and the server redirects to the same 404 image for ...

Using AJAX to delete items from the personalized shopping cart on your WooCommerce website

I am encountering an issue with removing products from the cart. Although my code successfully removes the product in ajax, it fails to refresh the cart. Here is the code snippet I am working with: add_filter('woocommerce_add_to_cart_fragments', ...

What are the appropriate SOAP_ACTION, METHOD_NAME, NAMESPACE, and URL for the Android Client to communicate with the web service?

Suppose there is a Web service available at this URL: (written in PHP) with the following WSDL: <?xml version="1.0" encoding="UTF-8"?> <definitions xmlns="http://schemas.xmlsoap.org/wsdl/" name="webservice_help" targetNamespace="http://www.help. ...

The Remote_Host index is not visible

We have encountered an issue on our suse11 apache2.2 server when trying to retrieve the REMOTE_HOST information, resulting in an error message stating "index not found" shown below: REMOTE_HOST : Notice: Undefined index: REMOTE_HOST in /media/nss/VOL1/htd ...

php Use cURL and the DOM to extract content with specified CSS styling

Unclear in the title, I want to copy all content from a specific div on an existing webpage (not owned by me). The code successfully extracts the content. Extractor code: // Get Data $curl_handle=curl_init(); curl_setopt($c ...

Retrieving data dynamically from a database using PHP

Having a simple issue. I need to retrieve data from a database as an array without knowing the indexes. I want to dynamically fetch the data - let's say I want to retrieve two columns named "name" and "lastname" from the database, but display it using ...

The Symfony Progress Bar is undergoing a transformation as it transitions onto fresh lines

When using the Symfony Console progress bar, I noticed that it is not advancing on the same line but instead creating a new line for each step of the process. 1/2 [==============>-------------] 50% ! [NOTE] No changes made to Categories/CategoriesSc ...

Delete a Woocommerce item from the shopping cart using ajax/fetch technology

My issue lies with the removal of products from the cart in Woocommerce, specifically involving WC_Cart::remove_cart_item. The error messages I am encountering are: POST http://localhost:3000/esport/wp-admin/admin-ajax.php [HTTP/1.1 500 Internal Server Err ...

Retrieve the query result using MYSQLI in an Ajax request and display it in an HTML document

When making an Ajax call in an HTML file to retrieve multiple rows of data from a database query, I am struggling to display the result back in the HTML file. index.html: <!DOCTYPE html> <html> <head> <script src="https://ajax.go ...

Generating a dropdown menu populated by a linked table in Yii framework

I am currently working with two tables: product and product_type which are connected to the models Product and Product_type respectively: product : product_id, product_type_id, name, etc... product_type : product_type_id, name, desc, etc... Both tables a ...

The user repository class acting as both a user provider and utilizing dependency injection

I've been following a helpful tutorial on implementing API keys for user authentication in my application. In order to provide the necessary user data during pre-authentication, I am using my user repository class. This class was built following anot ...

What is the best approach to updating multiple rows instead of just the first row using the update button located on both sides using PHP and AJAX?

Starting fresh, so I might sound like a beginner with this question. How can I make use of the update button to update specific rows instead of just the top row? Every time I try to update, it only works for the top row. Here's the code snippet from ...

Using PHP to output HTML tags as text

How can I display an HTML tag as text on screen, rather than in code format? I want readers to be able to easily read the tag itself. What is considered the best practice for achieving this? print htmlspecialchars('<meta name="copyright" conten ...

The functionality of making Slim POST requests is currently not functioning as expected within the Ionic

An issue is arising with my app that makes calls to a REST API using POST and GET methods. The app I'm developing with Ionic works perfectly when emulated using the command: ionic serve --lab However, when running the app on an actual device, calls ...

Encountered an issue while trying to establish a connection with the Stripe API in a Laravel project:

When trying to integrate the Stripe API into my Laravel project, I encountered an error message stating: Unexpected error communicating with Stripe. If this problem persists, let us know at <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data ...

Using a left join table in MySQL to incorporate conditions

Displayed in the image is my Quiz table. Additionally, there is a quiz result history table shownhttps://i.stack.imgur.com/L5nBW.png To combine information from these two tables, I have written a left join query as follows: select q.* , c.name ...

reCAPTCHA v3 - Alert: There are no existing reCAPTCHA clients available

After coming across a similar issue on Stack Overflow (link to the question here), I attempted to implement reCAPTCHA on my website to combat spam emails received through the form. Despite following Google's instructions, I encountered an error that p ...

An unclosed quotation mark was detected following the character string in Node.js with sequelize

Whenever I input a sentence containing single quotes, an error occurs due to Sequelize interpreting it as the closing string. How can I resolve this issue? I attempted using the sqlstring module without success. (I am aware that doubling up the single qu ...

Managing DateTime data type between C# and PHP using SOAP web services

In my work, I handle web services implemented in C# and PHP on the client side. When using SOAP __getTypes, it indicates that one of the expected parameters should be a dateTime birthDate. I attempted to send the parameter in various formats, such as $da ...