Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

PDO()->bindParam method binds the last value to every other parameter [duplicate]

$
0
0

I'm a beginner in PHP.
I have a PHP script that I'm using to add rows into my MySQL database. I'm using PHPMyAdmin and WampServer.

Here's the script of my tables:

CREATE TABLE growth_state(   growth_state_id INT AUTO_INCREMENT,   label VARCHAR(50) NOT NULL,   PRIMARY KEY(growth_state_id));CREATE TABLE plant(   plant_id INT AUTO_INCREMENT,   label VARCHAR(50) NOT NULL,   latitude DECIMAL(16,14) NOT NULL,   longitude DECIMAL(17,14) NOT NULL,   growth_state_id INT NOT NULL,   leaf_amount INT,   PRIMARY KEY (plant_id),   FOREIGN KEY (growth_state_id) REFERENCES growth_state(growth_state_id));

This is how I tell the PHP file to insert the row at the table I specify as well as the data to be inserted http://localhost/php_script?table=plant&data={"label":"something","latitude":20.10892505086746,"longitude":-122.08396146073937,"growth_state_id":0, "leaf_amount":2}

In the PHP script, I get these values:

$table = $_GET['table']; // this gives me 'plant'$data = json_decode($_GET['data']); // this gives me the json_decode result of '{"label":"something","latitude":20.10892505086746,"longitude":-122.08396146073937,"growth_state_id":0, "leaf_amount":2}'

Then I call the following function:
$cnx contains an instance of the PDO class.

send_response is a function that echo a json message for me to read.

function add_model() {    global $cnx, $table, $data;    $request = "insert into $table (label, latitude, longitude, growth_state_id, leaf_amount) values (:label, :latitude, :longitude, :growth_state_id, :leaf_amount)";    try {        $request = $cnx->prepare($request);        foreach ($data as $key => $value) {            $request->bindParam(":$key", $value);        }        $request->execute();    } catch (Exception $e) {        send_response(500, "Invalid request: $request because $e", "");        die();    }    if ($request) {        send_response(200, "Success", $request);    } else {        send_response(400, "Fail", $request);    }}

Note: I tried running this line in the foreach loop to make sure every key had its corresponding value:

echo $key . " = " . $value;

Saw nothing wrong with it, then again this might mean nothing.

Expected result with the previously given URL in the database:

labellatitudelongitudegrowth_state_idleaf_amount
something20.10892505086746-122.0839614607393712

Actual result in the database:

labellatitudelongitudegrowth_state_idleaf_amount
22.000000000000002.0000000000000022

It's as if the leaf_amount value was inserted into each column.

What's wrong with bindParam exactly? At one point it was working fine though.


Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>