PHP / SQL检索新插入的行

时间:2013-12-13 23:42:17

标签: php mysql sql insert

我使用PHP将以下数据插入到SQL表中。

    $query1 = 'INSERT INTO log_index_level_1 (LOG_INDEX, LOT_ID, WAFER_ID, MAP_REV, PROBE_DATE) VALUES ("", "' . $LOT_ID . '", "' . $WAFER_ID . '", "' . $MAP_REV. '", ' . "STR_TO_DATE('" . $PROBE_DATE . "', '%m-%d-%Y'" . '))';

    $result1 = mysql_query($query1) 

    echo mysql_result($result1, 0) . "\n;

如何检索刚插入的第一行数据?即我想要echo LOG_INDEX。

上述代码不起作用,因为$result1返回1而不是实际的DATA本身。

2 个答案:

答案 0 :(得分:0)

我没有测试下面的代码。

<?php

  /*
  ........... your connection code ... etc
  .............
  */

  $query1 = 'INSERT INTO log_index_level_1 (LOG_INDEX, LOT_ID, WAFER_ID, MAP_REV, PROBE_DATE) VALUES ("", "' . $LOT_ID . '", "' . $WAFER_ID . '", "' . $MAP_REV. '", ' . "STR_TO_DATE('" . $PROBE_DATE . "', '%m-%d-%Y'" . '))';

  $result1 = mysql_query($query1);

  $query2 = 'select last_insert_id() as lastId';

  $result2 = mysql_query($query2);

  if ($row = mysql_fetch_object($result2)) {

    $lastId = $row->lastId;

    $query3 = "select * from log_index_level_1 aa where aa.LOG_INDEX = ".$lastId;

    $result3 = mysql_query($query3);

    if ($lastRow = mysql_fetch_object($result3)) {
      // do something with $lastRow
      // $lastRow->LOT_ID , $lastRow->WAFER_ID ... etc
    }

    mysql_free_result($result3);
  }

  mysql_free_result($result2);
  mysql_free_result($result1);
?>

答案 1 :(得分:0)

感谢您的灵感。

这是我查找的代码解决了它。

$result_liq = mysql_query("SHOW TABLE STATUS LIKE 'log_index_level_1'");
$row = mysql_fetch_array($result_liq);
$LOG_INDEX = $row['Auto_increment'];