VolcovMeter VolcovMeter - 4 months ago 48
MySQL Question

AngularJS, PHP, and MySQL: How to insert variables correctly using PDO?

I'm trying to add data to my database, but don't know how to do this properly with PDO prepare/execute statements.

In my html file, I have this button call:

<form name="addRecord" method="POST">
<button data-ng-click="addNewRecord()" name="add">Add Record</button>
</form>


Which goes to my controller:

app.controller('DateHoursController', function ($scope, $http) {
var date = 456;
var hours = 5;
var minutes = 45;
var cid = 'jk7814982';
var em = 'email@email.com';
var versionN = 0;

$scope.addNewRecord = function () {
var today = Date.now();

$http.post("server/insert.php", { 'id': cid, 'createdon': today, 'email': em, 'date': date, 'hour': hours, 'minute': minutes, 'version': versionN })
.success(function (data, status, headers, config) {
console.log("inserted Successfully");
});
};
});


Which calls my PHP file:

<?php
if(isset($_POST['add']))
{
try {
$db = new PDO('mysql:host=localhost;dbname=myDBNAME;charset=utf8',
'myDBUSER',
'myDBPASS');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $ex) {
echo "did not connect...";
}

$sth = $db->prepare("INSERT INTO my_db_table
(tcode, created_on, email, move_in_date, move_in_hour, move_in_minute, version)
VALUES (?, ?, ?, ?, ?, ?, ?)");

$data = json_decode(file_get_contents("php://input"));
$sth->bindValue(1, $data->id);
$sth->bindValue(2, $data->createdon);
$sth->bindValue(3, $data->email);
$sth->bindValue(4, $data->date);
$sth->bindValue(5, $data->hour);
$sth->bindValue(6, $data->minute);
$sth->bindValue(7, $data->version);

$success = $sth->execute();
Print $success;
}
?>


In the console, I see "inserted Successfully", and checking the browser network, if I click "insert.php" I see status 200, but an empty response.

Am I forgetting something here? I don't understand what's making this fail.

Answer

Do not use mysql_real_escape_string, or any other escaping functions, before binding your values.

Prepare the statement, with placeholders where you are currently inserting your values:

$sth = $db->prepare("INSERT INTO my_db_table 
             (tcode, created_on, email, move_in_date, move_in_hour, move_in_minute, version)
             VALUES (?, ?, ?, ?, ?, ?, ?)");

Bind the values to the prepared statement:

$sth->bindValue(1, $data->id);
$sth->bindValue(2, $data->createdon);
$sth->bindValue(3, $data->email);
$sth->bindValue(4, $data->date);
$sth->bindValue(5, $data->hour);
$sth->bindValue(6, $data->minute);
$sth->bindValue(7, $data->version);

Execute the prepared statement.

$success = $sth->execute();

$success will indicate whether or not the execute was successful.

Comments