开发者

Select Max inside a mysql Insert Query

Max(sequence) + 1 (based on my knowledge) should be returning the highest sequence with $_GET['business_id'] in the database + 1 - existing values in the database are 0, 1, and 3 - so max(sequence)+1 should be 4 - so something must be wrong with the line of code. Any ideas?

$insertQuery = "
    INSERT INTO owner_business_media 
        (business_id, sequence, type, filename, title, secret)
    VALUES (
        '".$_GET[businessid]."', 
        '(SELECT MAX(sequence)+1 FROM owner_business_media WHERE business_id=".$_GET['businessid'].")', 
        '$type', 
        '$fullf开发者_Go百科ile', 
        '$filename', 
        '1')
";


Remove single quotes that surround the inner SELECT and instead of the regular INSERT go with INSERT ... SELECT:

$insertQuery = "
    INSERT INTO owner_business_media
        (business_id, sequence, type, filename, title, secret)
    SELECT
        '".intval($_GET['businessid'])."',
        (SELECT MAX(obm.sequence)+1 FROM owner_business_media obm WHERE obm.business_id=".intval($_GET['businessid']).") AS next,
        '$type', 
        '$fullfile', 
        '$filename', 
        '1'
";

Also, never embed a GET variable directly without validating or sanitizing it's contents (see intval($_GET['businessid'])). Otherwise the code gets exposed to SQL injection.


Almost the same as the other answer, yet not completely the same:

$insertQuery = "
    INSERT INTO owner_business_media
        (business_id, sequence, type, filename, title, secret)
    SELECT
        '".intval($_GET['businessid'])."',
        MAX(sequence)+1 AS next,
        '$type', 
        '$fullfile', 
        '$filename', 
        '1'
    FROM owner_business_media
    WHERE business_id=".intval($_GET['businessid']);

Maybe it would be safer to use IFNULL with sequence (in case the table is empty), like this:

        MAX(IFNULL(sequence, 0))+1 AS next
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜