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 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c