Reputation: 149
I am trying to add some Values to a Database with PHP I send some parametres from a Android Application they also arrive in the right way. I checked it with echo and printed all the Parameteres I send.
id (PRIMARY_KEY, AUTO_INCREMENT)
deviceID (TEXT)
name (TEXT)
latitude (TEXT)
longitude (TEXT)
Thats the Structure and the name of the Database is position
This is my query but it just doesent work.
$deviceID = $_POST['deviceID'];
$name = $_POST['name'];
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
$result = mysql_query("INSERT INTO position(deviceID, name, latitude, longitude) VALUES('$deviceID', '$name', '$latitude', '$longitude')");
Upvotes: 0
Views: 204
Reputation: 5740
Listen, you need to stop using the deprecated mysql_*
functions. They will cause you a lot of headache. I suggest you setup mysql to use PDO
. Here is an example.
Connect to it first and have it throw exceptions for you to handle yourself.
try {
$pdo = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Now run your update.
try {
$stmt = $pdo->prepare('INSERT INTO position VALUES(:deviceId, :name, :latitude, :longitude)');
$stmt->execute(array(
':deviceId' => $deviceID,
':name' => $name,
':latitude' => $latitude,
':longitude' => $longitude
));
// Affected Rows?
echo $stmt->rowCount(); // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
// Per your question to json_encode
After you call the execute()
statement the same way (but with a SELECT
) you will just need to do this.
$results = $stmt->fetchAll(PDO::FETCH_ASSOC); // This will be an array
$json_results = json_encode($results);
Later down the line if you want to get it as an object (which I prefer to work with)
$results = $stmt->fetchAll(PDO::FETCH_OBJ);
Also if you want to get a single result, use fetch()
$result = $stmt->fetch(PDO::FETCH_ASSOC);
Upvotes: 0
Reputation: 3338
http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_position
Position
is a function name in MySQL: you should escape it using backticks (`), and you need to add a space between position
and the parentheses.
$result = mysql_query("INSERT INTO `position` (deviceID, name, latitude, longitude) VALUES('$deviceID', '$name', '$latitude', '$longitude')");
Upvotes: 2