Ver Mensaje Individual
  #1 (permalink)  
Antiguo 12/01/2010, 00:32
expecimen
 
Fecha de Ingreso: octubre-2006
Ubicación: Ciudad Ojeda, Venezuela
Mensajes: 123
Antigüedad: 17 años, 7 meses
Puntos: 0
obtener el ultimo ID insertado en una tabla MySQL (RESUELTO)

Hola de nuevo la presente es pasa saber si alguien me podría ayudar ya que estoy haciendo un formulario de registro en php y mysql, todo funciona muy bien pero necesito que este al final en la pagina de resultado del registro este me diga en que puesto (ID) quedo el registrado, este formulario de registro es para hacer un sistema de registro de vehículos aquí les dejo los códigos que por cierto funciona muy bien y para los que quieran usarlo puede hacerlo:

Tabla:

Código:
CREATE TABLE `vehiculo` (
`id` int(11) unsigned NOT NULL auto_increment,
`patente` varchar(100) default NULL,
`firstname` varchar(100) default NULL,
`cedularif` varchar(100) default NULL,
`tipov` varchar(100) default NULL,
`placa` varchar(10) default NULL,
`observacion` varchar(100) default NULL,
`calculado` varchar(100) default NULL,
`ceducalcu` varchar(100) default NULL,
`revisado` varchar(100) default NULL,
`fecha` date NOT NULL, 
  PRIMARY KEY  (`id`),
  UNIQUE KEY `placa` (`placa`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Pagina PHP que genera el registro:

Código PHP:
<?php
    
//Start session
    
session_start();
    
    
//Include database connection details
    
require_once('config.php');
    
    
//Array to store validation errors
    
$errmsg_arr = array();
    
    
//Validation error flag
    
$errflag false;
    
    
//Connect to mysql server
    
$link mysql_connect(DB_HOSTDB_USERDB_PASSWORD);
    if(!
$link) {
        die(
'Failed to connect to server: ' mysql_error());
    }
    
    
//Select database
    
$db mysql_select_db(DB_DATABASE);
    if(!
$db) {
        die(
"Unable to select database");
    }
    
    
//Function to sanitize values received from the form. Prevents SQL injection
    
function clean($str) {
        
$str = @trim($str);
        if(
get_magic_quotes_gpc()) {
            
$str stripslashes($str);
        }
        return 
mysql_real_escape_string($str);
    }
    
    
//Sanitize the POST values
    
$fname clean($_POST['fname']);
    
$cedularif clean($_POST['cedularif']);
    
$tipov clean($_POST['tipov']);
    
$placa clean($_POST['placa']);
    
$calculado clean($_POST['calculado']);
    
$ceducalcu clean($_POST['ceducalcu']);
    
$observacion clean($_POST['observacion']);

    
    
//Input Validations
    
if($fname == '') {
        
$errmsg_arr[] = 'Contribuyente';
        
$errflag true;
    }
        if(
$cedularif == '') {
        
$errmsg_arr[] = 'Cedula o Rif';
        
$errflag true;
    }
        if(
$tipov == '') {
        
$errmsg_arr[] = 'Tipo de Vehiculo';
        
$errflag true;
    }
        if(
$placa == '') {
        
$errmsg_arr[] = 'Placa';
        
$errflag true;
    }
    
    
    
//Check for duplicate login ID
    
if($placa != '') {
        
$qry "SELECT * FROM vehiculo WHERE placa='$placa'";
        
$result mysql_query($qry);
        if(
$result) {
            if(
mysql_num_rows($result) > 0) {
                
$errmsg_arr[] = '<b>Placa ya registrada</b>';
                
$errflag true;
            }
            @
mysql_free_result($result);
        }
        else {
            die(
"Query failed01");
        }
    }
    
    
//If there are input validations, redirect back to the registration form
    
if($errflag) {
        
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
        
session_write_close();
        
header("location: register-form.php");
        exit();
    }

    
//Create INSERT query
    
$qry "INSERT INTO vehiculo(firstname, cedularif, tipov, placa, observacion, calculado, ceducalcu, fecha) VALUES('$fname','$cedularif','$tipov','$placa','$observacion','$calculado','$ceducalcu','".date("Y-m-d")."')";
    
$result = @mysql_query($qry);
    
    
//Check whether the query was successful or not
    
if($result) {
        
header("location: register-success.php");
        exit();
    }else {
        die(
"Query failed02");
    }
?>
Pagina de resultado que dice que el registro se efectuo

Código PHP:
<?php
    session_start
();
?>
<head>

</head>

<body topmargin="30" bottommargin="0" text="#000000" link="#FFFFFF" vlink="#FFFFFF">

<div align="center">
    <table border="0" width="50%" id="table1" cellspacing="1" cellpadding="0" bgcolor="#FFFFFF">
        <tr>
            <td align="center">
            <table border="0" width="100%" id="table1" cellpadding="0" height="456" cellspacing="0">
                <tr>
                    <td align="center" height="19">
                    <table border="0" cellpadding="0" cellspacing="0" width="844" id="table2">
                        <tr>
                            <td valign="top">
                            <table border="0" width="100%" id="table5" cellspacing="0" cellpadding="0" height="363">
                                <tr>
                                    <td height="19">
                            &nbsp;</td>
                                </tr>
                                <tr>
                                    <td height="180">
                                    <font color="#696969" face="Tahoma" size="2">
                                    <b><font size="1">
                                    <table border="0" width="900" id="table6" cellpadding="2">
                                        <tr>
                                            <td height="47" align="center" valign="bottom">
                                            <p align="center"><b>
                                            REGISTRO REALIZADO.</b></td>
                                        </tr>
                                        <tr>
                                            <td height="49">
                                            <p align="center">
                                            &nbsp;ingrese 
                                            a su cuenta haciendo 
                                            <font color="#696969" face="Tahoma">
                                            <b>
                                            <span style="text-decoration: none">
                                            <a href="register-form.php">
                                            <font color="#000000">Clic Aquí.</font></a></span></b></font></td>
                                        </tr>
                                    </font>
                                        <tr>
                                            <td valign="bottom" align="center">
                                        <font face="Tahoma" style="font-size: 8pt"></font></td>
                                        </tr>
                                    </table>
                                    </b></font></td>
                                </tr>
                                <tr>
                                    <td height="120">&nbsp;</td>
                                </tr>
                                <tr>
                                    <td height="44" align="justify" valign="top">
                                    <p align="justify" style="margin-left: 6px; margin-right: 6px">
                                    <b>
                                    <font color="#666666" size="1" face="Arial">
                                    Todo los datos son totalmente confidencial, 
                                    según lo establecido en los artículos 06, 11, 
                                    12 y 22 de la Ley Especial Contra Delitos Informáticos 
                                    de Venezuela</font></b></p>
                                    </td>
                                </tr>
                            </table>
                            </td>
                        </tr>
                        </table>
                    </td>
                </tr>
                <tr>
                    <td align="center">
            <table border="0" width="100%" id="table7" cellpadding="0" cellspacing="0">
                <tr>
                    <td align="center" bgcolor="#164818" width="606">
                    <p align="justify" style="margin-left: 6px">
                    <font face="Arial" size="1" color="#9A9A9A"><strong>TSU Darwin 
                    Mavares<span lang="es-mx">.</span></strong></font><font color="#9A9A9A"><b><font face="Arial" size="1"><br>
                    Copyright © 2009. </font></b><font face="Arial" size="1">Todos 
                    los derechos reservados.<strong><br>
                    <span lang="es-mx">Sitio web solo para uso informativos. Producción 
                    Nacional Independiente.</span></strong></font></font><font face="Arial" size="1" color="#9A9A9A"><strong><span lang="es-mx"><br>
                    Rif: V-14511134-6</span></strong></font></p>
                    </td>
                    <td align="center" width="239" bgcolor="#64B837" height="87">&nbsp;</td>
                </tr>
            </table>
                    </td>
                </tr>
            </table>
            </td>
        </tr>
        </table>
</div>

</body>

</html>
En si lo que quiero que la pagina de resultado me diga "USTED A QUEDADO REGISTRADO CON EL N° XX" donde XX seria el ID en donde a quedado registrado en la BD mysql
Espero me ayuden

SOLUCION:

en la pagina de registro coloquen la variable $last_id = mysql_insert_id(); como se ve a continuacion

Código PHP:
$qry "INSERT INTO vehiculo(firstname, cedularif, tipov, placa, observacion, calculado, ceducalcu, fecha) VALUES('$fname','$cedularif','$tipov','$placa','$observacion','$calculado','$ceducalcu','".date("Y-m-d")."')";
$result = @mysql_query($qry); 
$last_id mysql_insert_id(); 
y luego coloque en la parte en donde quieran que se vean el resultado en la pagina
Código:
<?php echo "USTED A QUEDADO REGISTRADO CON EL N° " . $last_id;?>

Última edición por expecimen; 12/01/2010 a las 21:27