Jump to content

Recommended Posts

Posted

Alguem me pode dar uma vista de olhos e ver qual o problema aqui?

insert into modem(port,server,peername,secret,cidname,cidnumber,countrycode,areacode,faxnumber,localidentifier) 
				 values(
(4570 + (select id from modem order by id desc limit 1)),'$txtServer','$txtPeername','$txtSecret','$txtCidname','$txtCidnumber','$txtCountrycode','$txtAreacode','$txtFaxnumber','$txtLocalidentifier')

Basicamente quero inserir dados e no fim dizer o id que foi inserido, esse mesmo id está como auto-incremento + 1.

Peguei recentemente em bd Mysql por isso ando um bocado a deriva... estou a vir de SqlServer da microgaitas.

Obrigado

Posted

Penso que existe um equivalente @@IDENTITY,penso que será  LAST_INSERT_ID()

Aqui há coisa de 2 anos fazia umas malhas de croché, depois fartei-me e fui para informática!

Posted

o problema está em:

select id from modem order by id desc limit 1

quando faço esta SP ele da-me bem o ultimo id criado, mas introduzindo para o somar a 4570 n dá...

Obrigado pelo LAST_INSERT_ID() mas pelos vistos só funciona usando por exemplo:

INSERT INTO foo (auto,text)
    VALUES(NULL,'text');
INSERT INTO foo2 (id,text)
    VALUES(LAST_INSERT_ID(),'text');

Se definires dentro da msm SP ele funciona, se for numa nova pelos vistos nao... :|

Alguem tem mais alguma sujestão?

Obrigado

Posted

estás a usar o mysql ? tens o mysql_insert_id()

If you insert a record into a table that contains an AUTO_INCREMENT column, you can obtain the value stored into that column by calling the mysql_insert_id() function.

When a new AUTO_INCREMENT value has been generated, you can also obtain it by executing a SELECT LAST_INSERT_ID() statement with mysql_query() and retrieving the value from the result set returned by the statement.

For LAST_INSERT_ID(), the most recently generated ID is maintained in the server on a per-connection basis. It is not changed by another client. It is not even changed if you update another AUTO_INCREMENT column with a non-magic value (that is, a value that is not NULL and not 0).

Exemplo :

if ((result = mysql_store_result(&mysql)) == 0 &&
    mysql_field_count(&mysql) == 0 &&
    mysql_insert_id(&mysql) != 0)
{
    used_id = mysql_insert_id(&mysql);
}

ver mais : http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

Posted

yah, n sei se percebeste mas eu n estou bem com dúvidas de php... até por isso msm puz isto na secção de mysql...

o que eu quero introduzir:

VALUES(
(4570 + (SELECT id FROM modem ORDER BY id DESC LIMIT 1)),'ola','xau','coiso','whatever','blablabla','olarila','cumcatano','vaibuscala','oleole')

apenas tenho problema no facto de não conseguir somar 4570 + (valor do ultimo id criado).

Cumprimentos

Posted

E provavelmente dá um erro ao tentares fazer essa soma não? Qual?

Aqui há coisa de 2 anos fazia umas malhas de croché, depois fartei-me e fui para informática!

Posted

ok, ja ultrapassei a primeira etapa:

select @port := id from modem order by id desc limit 1;
set @port = @port + 4570;
insert into modem(port,server,peername,secret,cidname,cidnumber,countrycode,areacode,faxnumber,localidentifier) 
values(@port,'$txtServer','$txtPeername','$txtSecret','$txtCidname','$txtCidnumber','$txtCountrycode','$txtAreacode','$txtFaxnumber','$txtLocalidentifier')

Agora tenho outro problema, quando o id não existe obviamente retorna null e da-me erro no " set @port = @port + 4570;".

Tenho que fazer um if statment para testar se o valor é null ou não.

select @port := id from modem order by id desc limit 1;
if (@port = null) then set @port = 4570;
else set @port = @port + 4570;
end if

Mas n dá...

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'if (@port = null) then set @port = 4570' at line 1

Cumprimentos

Posted

tks seesharptec mas n deu... tive o dia todo nisto ja me tou a passar...  ?

SELECT @port := id FROM modem ORDER BY id DESC LIMIT 1;
IF ISNULL(@port)
THEN SET @port = 4570;
ELSE SET @port = @port + 4570;
INSERT INTO modem(port,server,peername,secret,cidname,cidnumber,countrycode,areacode,faxnumber,localidentifier) 
VALUES(@port,'$txtServer','$txtPeername','$txtSecret','$txtCidname','$txtCidnumber','$txtCountrycode','$txtAreacode','$txtFaxnumber','$txtLocalidentifier')

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF ISNULL(@port)

THEN SET @port = 4570' at line 1

Posted

Bem, resolvi o assunto com má programação, chamo o ultimo id para o código php, faço lá o teste e devolvo o valor no insert, n posso estar a perder mais tempo com isto.

Entretanto se alguem conseguir usar o IS NULL ou o ISNULL() num IF que avise ok?

Agradeço a ajuda.

Cumps

Posted

Alguem me pode dar uma vista de olhos e ver qual o problema aqui?

insert into modem(port,server,peername,secret,cidname,cidnumber,countrycode,areacode,faxnumber,localidentifier) 
				 values(
(4570 + (select id from modem order by id desc limit 1)),'$txtServer','$txtPeername','$txtSecret','$txtCidname','$txtCidnumber','$txtCountrycode','$txtAreacode','$txtFaxnumber','$txtLocalidentifier')

Basicamente quero inserir dados e no fim dizer o id que foi inserido, esse mesmo id está como auto-incremento + 1.

Peguei recentemente em bd Mysql por isso ando um bocado a deriva... estou a vir de SqlServer da microgaitas.

Obrigado

A melhor opção é usar um campo auto incrementavel. Embora o problema já esteja resolvido, deixo aqui uma das soluções mais comuns para este tipo de problema:

mas se não queres, ou não podes, faz assim:

insert into modem (port, server, peername, secret, cidname, cidnumber, countrycode, areacode, faxnumber, localidentifier) 
values(
((select max(id) + 4570 + 1 from modem) ,'$txtServer', '$txtPeername', '$txtSecret', '$txtCidname', '$txtCidnumber', '$txtCountrycode', '$txtAreacode', '$txtFaxnumber', '$txtLocalidentifier')

É de referir que em ambientes concorrentes esta abordagem tem um ponto de falha, o

select max(id) + 4570 +1 from modem

pode ser executado em paralelo e apenas uma das chamadas vai funcionar correctamente.

Outra solução é guardar os ids numa tabela própria, embora o problema da concorrência se mantenha.

Para evitar o problema da concorrência, há que colocar a operação numa transacção.

10 REM Generation 48K!
20 INPUT "URL:", A$
30 IF A$(1 TO 4) = "HTTP" THEN PRINT "400 Bad Request": GOTO 50
40 PRINT "404 Not Found"
50 PRINT "./M6 @ Portugal a Programar."

 

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.