Reputation: 2475
(1)I’d like to make this file receive $_POST[‘message’]
, and insert into db.
(2)I’d like to make this file output db data on JSON.
But nothing is output even though some data stored in db.
I have this code.
MySQL
CREATE DATABASE chat;
CREATE TABLE posts(id INTEGER PRIMARY KEY AUTOINCREMENT, message TEXT);
index.php
mb_language("uni");
mb_internal_encoding("utf-8");
mb_http_input("auto");
mb_http_output("utf-8");
$link = mysql_connect('localhost', 'root', 'root');
if ($link) {
die('cannot connect:'.mysql_error());
}
mysql_select_db("chat", $link);
if ($SERVER['REQUEST_METHOD'] == 'POST') {
$message = $_POST['message'];
mysql_query("INSERT INTO posts (message) VALUES ('$message')");
}
$query = mysql_query('SELECT * FROM posts ORDER BY id DESC');
$posts = array();
while ($row = mysql_fetch_object($query)) {
$posts[] = array(
'message' = $row -> message
);
}
header('Content-Type:application/json');
echo json_encode($posts);
?>
How do I fix it to output JSON?
Upvotes: 0
Views: 73
Reputation: 111
replace:
'message' = $row -> message
'message' => $row -> message
But also , you should use
SELECT * FROM posts
WHERE id
= mysql_insert_id()
Upvotes: 1