T2theC
T2theC

Reputation: 540

PHP/MySQL update table rows from JSON array

I'm learning PHP and Laravel has spoilt me. I have a project that isn't using Laravel and my basics are pretty lost.

I am grabbing a JSON array from a webpage and want to update each affected row. For the life of me, I can't understand why this isn't working (The JSON file is definitely being pick up):

$conn = new mysqli($env_db['hostname'], $env_db['username'], $env_db['password'], $env_db['database']);

// check connection
if (mysqli_connect_errno()) {
    exit('Connect failed: '. mysqli_connect_error());
}

// exp_matrix_data = matrix table
// col_id_24 = sku code
// col_id_26 = stock

foreach(json_decode($file, true) as $item)
{
    $stock = $item['Stock'];
    $sku = $item['SKU'];

    $query = "UPDATE exp_matrix_data SET col_id_26=? WHERE col_id_24=?";
    $statement = $conn->prepare($query);

    //bind parameters for markers, where (s = string, i = integer, d = double,  b = blob)
    $results =  $statement->bind_param('ss', $stock, $sku);
}

example json

[
    {
        Series: "01000",
        SKU: "01000-1116",
        Stock: "98",
        id: 0
    },
    {
        Series: "01000",
        SKU: "01000-1132",
        Stock: "0",
        id: 1
    },
    {
        Series: "01000",
        SKU: "01000-116",
        Stock: "1000",
        id: 2
    }
]

Any pointers as to why this isn't working properly? No rows are being updated.

Thanks for taking the time to help this newbie!

Upvotes: 0

Views: 2178

Answers (2)

Avinash Babu
Avinash Babu

Reputation: 6252

You need to execute the query after you passed it ..Fir fecthing the results you need to execute your query..It can be done by

$result = $statement->execute();

Upvotes: 1

TED
TED

Reputation: 1839

After bind the params you have to execute your query and then only you get the result.

$result = $statement->execute();

Upvotes: 1

Related Questions