0

I have a table image_tb, which has 3 fields, id,images,link (id is auto auto_increment), this is my insert code:

mysql_query("
insert into image_tb 
(images,link) 
select 
'".(max(id)+1).".jpeg','".$link."' 
from image_tb
");

it return:

Warning: max(): When only one parameter is given, it must be an array

how to modify? thanks.

fish man
  • 2,666
  • 21
  • 54
  • 94

4 Answers4

3

its better you define a function , get the last id by query like this: "select id from image_tb order by id desc limit 0,1" then increase it , its realibe .

msk
  • 63
  • 8
  • I think php has a function which returns the last insert id. – Sentencio Nov 29 '12 at 07:47
  • @Sentencio: mysql makes sure this is the last id OF THE CURRENT CONNECTION, so there will be no problems if you put this statement right after the insert query. No worries about other processes doing inserts.No need to wrap this in a transaction. The mysql manual says: "The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This is the reason you should not use select MAX(ID) – msk Nov 29 '12 at 07:51
3

I think you don't mean to close the string:

select '" ...

should be

select MAX(id) + 1

Otherwise you are using the php function max, and I don't think you intend to do that at all.

By the way, you shouldn't be using mysql_*. Use PDO or mysqli.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
0

do it inside the query,

mysql_query("
insert into image_tb (images,link) 
select CONCAT(COALESCE((SELECT MAX(ID) + 1 FROM image_tb),1), '.jpeg'),'".$link."' 
from image_tb
");

your query is vulnerable with SQL Injection, please read the article below to protect from it

Community
  • 1
  • 1
John Woo
  • 258,903
  • 69
  • 498
  • 492
0

Have you considered something like this?

  1. Insert data with empty filename
  2. Update table where filename is empty, set filename to CONCAT(id, ".jpeg") or something (CONCAT is function used to "add" strings).
Kamil
  • 13,363
  • 24
  • 88
  • 183