Skip to content

Commit eb4f12d

Browse files
committed
Initial code commit
1 parent 98da99d commit eb4f12d

File tree

3 files changed

+73
-0
lines changed

3 files changed

+73
-0
lines changed

dbquery.m

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
function data = dbquery( query )
2+
%DBQUERY returns results from database
3+
4+
% THIS SHOULD ONLY BE USED ON A LOCAL MACHINE
5+
hostname='localhost:3306'; % hostname of the sql database
6+
username='root'; % the database username
7+
password=''; % the database password
8+
dbname='mydatabase'; % the database name
9+
url='http://localhost/sql_to_json.php'; % url to the php script
10+
11+
jsondata = webread(url,'hostname',hostname, ...
12+
'username',username, ...
13+
'password',password,'dbname',dbname, ...
14+
'querystr',query);
15+
16+
if jsondata{1} == 1 % check for success flag
17+
data = jsondata{2};
18+
else
19+
% relay errors encountered by php script to user
20+
bEx = MException('DBQUERY:DatabaseError','Database error occured');
21+
cEx = MException('DBQUERY:DatabaseErrorCause',jsondata{2});
22+
throw(addCause(bEx, cEx))
23+
end
24+
end

exampleuse.m

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
2+
data = dbquery('SELECT * FROM `mytable`')
3+
4+
plot([data.id])

sql_to_json.php

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<?php
2+
3+
$hostname = $_GET['hostname'];
4+
$username = $_GET['username'];
5+
$password = $_GET['password'];
6+
$querystr = $_GET['querystr'];
7+
$dbname = $_GET['dbname'];
8+
9+
// reference: https://phpdelusions.net/pdo
10+
11+
// for development:
12+
ini_set('display_errors', 1);
13+
14+
// set up PDO
15+
$dsn = "mysql:host=$hostname;dbname=$dbname;charset=utf8";
16+
$opt = [
17+
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
18+
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
19+
PDO::ATTR_EMULATE_PREPARES => false,
20+
];
21+
22+
$success = false;
23+
24+
try {
25+
$pdo = new PDO($dsn, $username, $password, $opt);
26+
$data = $pdo->query($querystr)->fetchAll();
27+
$success = true;
28+
} catch (PDOException $e) {
29+
$data = $e->getMessage();
30+
}
31+
32+
$data = [$success, $data];
33+
34+
//echo '<pre>';
35+
//var_dump($data);
36+
37+
// headers for not caching the results
38+
header('Cache-Control: no-cache, must-revalidate');
39+
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
40+
41+
// headers to indicate JSON result
42+
header('Content-type: application/json');
43+
44+
// return RESTful json
45+
echo json_encode($data);

0 commit comments

Comments
 (0)