SQLinfo.ru - Все о MySQL

Форум пользователей MySQL

Задавайте вопросы, мы ответим

Вы не зашли.

#1 27.10.2007 23:55:27

pluto
Участник
Зарегистрирован: 27.10.2007
Сообщений: 7

Простой вопрос... помогите

У меня очень простой вопрос, помогите новичку.

Объясняю сразу на примере.

Есть свойства заказа customs: id_custom, id_client, id_pocket ...  , где номер заказа (auto_increment), номер клиента, номер пакета товаров
И ещё есть свойства пакета pockets: id_book price value id_custom


Как втсавлять записи в таблицы я хорошо знаю, меня беспокоит многопользовательский режим, т.е. надо ли раставлять приоритеты или блокировать таблицы?

Ведь чтобы записать id_cistom в таблицу pockets нужно значть id_custom. Допустим я его вычислю с помощью php функции mysql_insert_id(); - это ведь будет не правильно, т.к. пока я вычисляю id_custom он может быть изменён другим покупателем. Получается надо юзать аргумент mysql_insert_id(); т.е. я записал заказ, результат записи положил в переменную $res и затем юзать его как вргумент mysql_insert_id(); таким образом я точно буду знать id_custom для клиента?

Спасибо

Неактивен

 

#2 28.10.2007 00:19:12

pluto
Участник
Зарегистрирован: 27.10.2007
Сообщений: 7

Re: Простой вопрос... помогите

Если попробывать блокировать вот так:

mysql_query("LOCK TABLES customs WRITE");
mysql_query("SET AUTOCOMMIT = 0");
mysql_query("INSERT INTO customs VALUES (null,id_client,id_pocket)");
define('ID',mysql_query("SELECT LAST_INSERT_ID()"));
mysql_query("COMMIT");
mysql_query("UNLOCK TABLES");

теперь получается я знаю id заказа?

Этот пример я взял с http://www.php.net/manual/en/function.m … ert-id.php

Неактивен

 

#3 28.10.2007 00:24:00

pluto
Участник
Зарегистрирован: 27.10.2007
Сообщений: 7

Re: Простой вопрос... помогите

If you want to use the ID that was generated for one table and insert it into a second table, you can use SQL statements like this:

INSERT INTO foo (auto,text)
    VALUES(NULL,'text');              # generate ID by inserting NULL
INSERT INTO foo2 (id,text)
    VALUES(LAST_INSERT_ID(),'text');  # use ID in second table

...found here:
http://www.mysql.com/doc/en/Getting_unique_ID.html

It works even without inserting the NULL value for some reason wink
The following is great for monitoring:
    $new_id = mysql_insert_id();
    print "New id: $new_id\n";

Hope it helps you all, cheers.
vksgeneric at hotmail dot com
09-Dec-1999 05:14
You can't do an INSERT DELAYED and expect to get anything but zero, for it runs in a separate thread, and mysql_insert_id() is tied to the current thread.
Vlad

Вот это как раз по моей теме, пока ответа не нашёл

Неактивен

 

#4 28.10.2007 00:27:32

pluto
Участник
Зарегистрирован: 27.10.2007
Сообщений: 7

Re: Простой вопрос... помогите

Вот мне кажется это и есть ответ

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). Using LAST_INSERT_ID() and AUTO_INCREMENT columns simultaneously ***from multiple clients is perfectly valid***. Each client will receive the last inserted ID for the last statement that client executed.

Отредактированно pluto (28.10.2007 00:29:44)

Неактивен

 

#5 28.10.2007 00:30:26

rgbeast
Администратор
MySQL Authorized Developer and DBA
Откуда: Москва
Зарегистрирован: 21.01.2007
Сообщений: 3878

Re: Простой вопрос... помогите

Вам не нужно беспокоиться. Вот, что говорит документация:
http://dev.mysql.com/doc/refman/5.0/en/ … rt-id.html
>> The value of mysql_insert_id() is affected only by statements issued within the current client connection. It is not affected by statements issued by other clients.

То есть, mysql_insert_id() будет всегда показывать id вставленный из Вашей сессии, и другие пользователи Вам не помешают.

Неактивен

 

#6 28.10.2007 00:52:46

pluto
Участник
Зарегистрирован: 27.10.2007
Сообщений: 7

Re: Простой вопрос... помогите

Спасибо.

Неактивен

 

Board footer

Работает на PunBB
© Copyright 2002–2008 Rickard Andersson