Adding PHP MySQL function would allow us to interact with databases and

I am facing an issue with a function that I have written in PHP mySQL to insert records into a database. The function accepts an array of JSON data, a field name, a connection, and a DB name as parameters. It then constructs a SQL statement to insert the records one by one. However, when I execute it, the function fails. I suspect there is an error in my INSERT statement, but I'm unsure how to resolve it. Any assistance on this matter would be highly appreciated.

Here is the function:

function insertRecords($array, $fieldname, $conn, $db_NAME)
{
    mysqli_select_db($conn, $db_NAME);

    $sql_insert = "INSERT INTO `tbl_articles` (`" . $fieldname . "`) VALUES ('" . $records . "')";

    foreach ($array as $records)
    {

        if(mysqli_query($conn, $sql_insert))
        {
            echo "Records Inserted.";
        }
        else 
        {
            die('Error : ' . mysqli_error($conn) . "<br>");
        }
    }
    echo $sql_insert . "<br>";
}

Answer №1

It seems like the issue lies with how your query string is positioned. To resolve this, you can make the following adjustment:

function addEntries($array,$columnName, $connection, $databaseName){
    mysqli_select_db($connection, $databaseName);

    foreach ($array as $entry)
    {
        $sql_query = "INSERT INTO `tbl_entries` (`" . $columnName . "`) VALUES ('" . $entry . "')";
        if(mysqli_query($connection, $sql_query))
        {
            echo "Entry added successfully.";
        }
        else 
        {
            die('Error : ' . mysqli_error($connection) . "<br>");
        }
    }
}

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

Unexpected restarts are occurring in a lengthy PHP script

I have a PHP script that I execute using the $.ajax() Javascript function: $.ajax({ type: "POST", url: "/myscript.php", data: $("#my-form").serialize() }); Details of myscript.php class myclass{ public function __construct(){ $i ...

Navigate through the JSON dataset

I am struggling with looping out JSON-data in an HTML list using PHP. The structure of the JSON data is as follows: { "msg": [ "msg text 1", "msg text 2", "msg text 3", "msg text 4", "msg text 5", "msg text 6" ] } My current P ...

Setting up a Laravel project on a DSO handler server

I am currently working on a Laravel 5.0 project that needs to be tested on servers supporting different PHP handlers such as: 1. suPHP (Single user PHP) 2. FCGI (FastCGI) 3. CGI (Common Gateway Interface) 4. DSO (Dynamic Shared Object) The project ru ...

Troubleshooting an Error with Ajax and PHP JSON Response

Having trouble with my website registration form. Getting 'null' as a response from the server when using json for data exchange. Here is the code: JavaScript code: $("#customer-form").submit(function() { var form_data = { c ...

What is causing the error message stating that the DateTime class object cannot be converted to a string?

I found this code snippet on a programming forum function increaseDate($date_str, ${ $date = new DateTime($date_str); $start_day = $date->format('j'); $date->modify("+{$months} month"); $end_day = $date->format(&apo ...

Using two variables as parameters in an AJAX URL within a Laravel route

Having an issue where my ajax request fails when using two parameters in the url. --- AJAX--- url: "/post/"+post_id+"/"+vote, --- ROUTE --- Route::get('/post/{id}/{up_or_down_vote} However, if I only use one parameter: --- AJAX-- ...

Utilizing Gravity Forms in tandem with the validate function

I am using a multi-page gravity forms setup. I am facing an issue where the code below checks the first page and prevents me from clicking the next button because the field is on the second page and is not being validated correctly. I have attempted using ...

Retrieve a record from a database table that is not found in a separate table

I am looking to retrieve a row from the images table that does not exist in the images_viewed table and both share the same name. Although the code I am currently using works, it is causing my website to perform very slowly. $next = $mysqli->query("SE ...

Guidelines for submitting and displaying content on a single page with jQuery and MySQL

Objective: To develop a Q&A Script using PHP, JavaScript, and jQuery that allows users to post questions and provide answers. Upon submitting a new answer, it should be stored in the database and automatically displayed in the answers section. Challenge: ...

PHP is having trouble updating the database when multiple radio buttons are selected. It appears that only the most recent radio button selected will be updated in the database

In my form, there are 2 numbers and 4 radio buttons for each. Only one option can be selected per number. When the form is submitted, only the database for question 2 will be updated. However, if question 2 is left blank, then question 1's database w ...

Disallow specific sequences of characters

My contact form has been bombarded with spam messages lately. Upon investigation, I have observed a pattern in the content of these messages. The email address field always seems to include the phrase "Staceyrow," while the message field typically contains ...

Activate and deactivate pconnect functionality

Is there a way to determine if the php pconnect is enabled or disabled by checking a configuration variable? Or is there a specific command on the server that can verify this status? Thank you. ...

Sorting one column in datatables.net triggers sorting in another column

Facing a major issue that I'm struggling with. I am using datatable.net to showcase data retrieved from my MySql database. I have followed the API guidelines meticulously in order to sort columns by name in ascending order (and toggle to descending). ...

Error message: The class 'PhpOfficePhpSpreadsheetSpreadsheet' could not be located within the context of Codeigniter

I seem to be having an issue with using phpspreadsheet in codeigniter. Below is the snippet of the code causing the problem: use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; public function modif ...

NodeJS is constantly refreshing the data in the database table

Every day, I use a cron job to scrape data and insert it into a database. However, I'm facing an issue where the database results on the server do not refresh themselves after new data is inserted. I've come across 2 solutions here, but one was ...

What is the reason behind WP AJAX consistently returning a value of 0?

Having trouble retrieving a proper response, as it always returns 0. Here is the JavaScript code in the head section: q = new XMLHttpRequest(); q.open('POST', ajaxUrl); q.onreadystatechange = function () { if (q.readyState === 4) { ...

Unable to retrieve object within an array using PHP

I've been experimenting with different methods to access a property of an object in an array. After receiving data from an API which I store in a variable called $userTokenValid: $userTokenValid = [{"authTokenValid":1}]; I attempt to retrieve the au ...

Storing an empty string in a Laravel database: A step-by-step guide

Below is the code snippet from my controller: public function addEmployer(Request $request) { $validator = UserValidations::validateEmployer($request->all()); if ($validator->fails()) { return response(['status' => false ...

PHP separate and categorize an array

I'm struggling to find a way to modify my array. The original array is as follows... $array = array( array( "fruit" => "pineapple", "id" => "aaa", ), array( "fruit" => "orange", "id" => "aaa", ), array( "fruit" => " ...

JavaScript in Reactjs is throwing an Uncaught TypeError saying that projects.map is not a function. This issue started happening after I made some modifications in

Previously, my code was functioning well with both tables in MySQL having just "id" as the primary key. To add more specificity and introduce a foreign key, I decided to rename the primary keys in the two tables as follows: Bugtracker_table: id --> pro ...