Hi I have connected a MySQL in a server with and Android application using JSON. I have a table called products where the primary key is and id which is auto_increment. When I insert a new product I would like to get that Id in my android Activity but I don't know how to retrieve it in PHP nor Android. Here is some code: Create Product Script
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {
$name = $_POST['name'];
$price = $_POST['price'];
$description = $_POST['description'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, price, description) VALUES('$name', '$price', '$description')");
Where should I put mysql_insert_id()
?
Finally, how could I get that mysql_insert_id()
in my android activity?
Thanks in advance
Well, this is easy:
// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, price, description) VALUES('$name', '$price', '$description')");
$insertedId = mysql_insert_id();
How do you send this id to your android app? The same way that you send everything else: JSON. I don't know what you usually send to your app, but this can be as easy as
echo json_encode($insertedId);
The usual disclaimer: Do not use the MYSQL extension anymore, it will be removed from PHP in the near future. Use Mysqli (i = improved) instead, or PDO.
Your SQL query is vulnerable to SQL injection attacks! Never ever put data unescaped directly into SQL, either use mysql_real_escape_string()
, or use prepared statements.