douwen1937 2013-06-07 07:04
浏览 89
已采纳

插入时获取MySQL ID

I'm trying to get the row ID after the slug (ex. post 1 returns "/bligpost.php?id=1"). Instead, it returns no ID. Where am I doing it wrong? (I have included my other attempts in comments.)

mysql_connect("$hosty","$uname","$paswd");
@mysql_select_db($dbnme) or die( "Unable to select database");

$name=$_POST['Title'];
$slug="blogpost.php?id=";
$auth=$_POST['Author'];
$date=$_POST['Date'];
$cont=$_POST['Content'];

//$query = ("INSERT INTO Blogs (Name, URL, Content, Author, Date) VALUES ('$name', '$slug', '$cont', '$auth', '$date')");
mysql_query("INSERT INTO Blogs (id, Name, URL, Content, Author, Date) VALUES (NULL, '$name', '$slug', '$cont', '$auth', '$date')");
//$pind = mysql_query("SELECT LAST_INSERT_ID()");
mysql_query("UPDATE Blogs SET URL=blogpost.php?id=`id` WHIERE id=LAST_INSERT_ID()");
//mysql_query("UPDATE Blogs SET URL=blogpost.php?id=".$pind." WHERE Content=".$cont);
mysql_close();
  • 写回答

4条回答 默认 最新

  • dongmiao520892 2013-06-07 07:26
    关注

    What you're actually doing wrong in the commented line when assigning to $pind is you expect the mysql_query to return your new id, but what it actually returns is a resource from which you must get the id using mysql_fetch_row or any similar function from the mysql_fetch_ family.

    As for the uncommented row with WHIERE id=LAST_INSERT_ID(), it would probably work, but you're not concatenating the prefix string with your id. You should do it like this:

    mysql_query("UPDATE blogs SET url = CONCAT('blogpost.php?id=', id) WHERE id = LAST_INSERT_ID()");
    

    On the other hand I don't approve of your design of holding your urls in the database when you already have everything you need in the database (i.e. the id), so you should just prepend the "blogpost.php?id=" to the id you get when selecting that row and you're all set, this url of yours is completely unnecessary.

    Oh and people are correct when they say this is deprecated, but it seems you're still learning so this is probably a little easier to grasp than the mysqli approach so you can stick with it for now and move up to mysqli once you're comfortable.

    Hope that helps. Good luck.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 vc6.0中想运行代码的时候总是提示无法打开文件是怎么回事
  • ¥25 关于##爬虫##的问题,如何解决?:
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题