0

I have a function in PHP mySQL that inserts records into a database. It take in an array of decoded JSON data, a field name, a connection and a DB name. It then builds a SQL statement and inserts the records one by one, or at least thats what I think it should do. I run everything, make the connection, database and table but when it gets to this function, it fails. I feel it has to do with my INSERT statement but I am not sure how to fix it. Any help would be greatly appreciated.

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>";
}
3
  • 1
    You're using $records when you create your INSERT, before you define it. Commented Aug 19, 2015 at 17:07
  • I think the query string must be in the foreach block. Commented Aug 19, 2015 at 17:08
  • 1
    put your insert in the loop. Commented Aug 19, 2015 at 17:10

1 Answer 1

1

It just looks like that your query string is displaced there. Just try this:

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

    foreach ($array as $records)
    {
        $sql_insert = "INSERT INTO `tbl_articles` (`" . $fieldname . "`) VALUES ('" . $records . "')";
        if(mysqli_query($conn, $sql_insert))
        {
            echo "Records Inserted.";
        }
        else 
        {
            die('Error : ' . mysqli_error($conn) . "<br>");
        }
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

That worked but it still does not insert anything into the database... the table it built with the correct fields but no records are inserted... why would this be?
What are the queries (from echo)? Do you can execute them manually via phpMyAdmin or something like this?
I just had that in there to debug. I forgot to take it out.
@Thomas: Yes, but if it does not work, you have to debug it ;-)
Yeah I am trying. I tried putting that same echo statement inside the foreach loop but it doesn't output anything. Its as if the insert function is never being run. Yet I call it twice in my index file.

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.