doucan2102 2013-04-19 22:23
浏览 37
已采纳

Android和MySQL:获取mysql_insert_id()并在Android Activity中检索它

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

  • 写回答

1条回答 默认 最新

  • drpzr64329 2013-04-19 23:33
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问