1

My PHP Code:

<?php
$host = ""; $db_name = ""; $username = ""; $password = "";

try {
    $conn = new PDO("mysql:host=".$host.";dbname=".$db_name, $username, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

$json = file_get_contents('');
$obj = json_decode($json, TRUE);

$stmt = $conn->prepare("INSERT INTO item_details (item_id,value,circulation) VALUES (:item_id,:value,:circulation");

foreach($obj['items'] as $key => $index) {
    $item_id = $key;
    $value = $index['value'];
    $circulation = $index['circulation'];

    $stmt->bindparam(":item_id", $item_id);
    $stmt->bindparam(":value", $value);
    $stmt->bindparam(":circulation", $circulation); 
    $stmt->execute();
}
?>

Problem:

I've tested via echoing the data to the page within my loop and the data is being retrieved, however no information is being submitted to my database.

Questions:

  1. How can I improve upon my script to add relevant debugging lines to find the cause?
  2. Is it obvious why my script does not work? If so, could you please explain this however my above question will aid my learning curve with future development!
Tyler
  • 854
  • 1
  • 10
  • 26

2 Answers2

1

Catalin Minovici is correct about bindParam however PDO errors are not always thrown exceptions that can be caught, so a try/catch is only helpful here if you are going to check the PDO errors, and throw your own exception.

You have missed a parenthesis in your query preparation.

// missing paren...........................................................................................here: v
$stmt = $conn->prepare("INSERT INTO item_details (item_id,value,circulation) VALUES (:item_id,:value,:circulation)");

See the documentation for reading PDO query errors after your execute() on php.net

Additionally it is better to combine all of the results into a single insert operation, rather than executing a new insert on each iteration of the loop.

NeoVance
  • 404
  • 2
  • 9
0

You forgot closing bracket in values: prepare("INSERT INTO item_details (item_id,value,circulation) VALUES (:item_id,:value,:circulation)");

Devansh Jani
  • 57
  • 1
  • 10