插入行时在MySQL自动增量主键字段中放入什么?

时间:2016-04-04 19:15:35

标签: php mysql mysqli binding

我是PHP的新手,我在设置代码以自动增加SQL ID时遇到了一些麻烦。我知道我尝试的方法并不是一个非常好的方法,并且知道竞争条件的风险等。这将是暂时的,直到我正确地对其余的代码进行排序。

有人可以告诉我这里我做错了什么吗?或者帮我获得有效的代码?

我的班级:

<?php

    $user = 'root';
    $pass = '';
    $db = 'testuser';

    $con=mysqli_connect('localhost', $user, $pass, $db) or die('Unable to connect');

    $data = json_decode(trim(key($_POST), '[]'), true);

    $email = $data['email'];
    $name = $data['name'];
    $shortDes = $data['shortDes'];
    $longDes = $data['longDes'];
    $max = mysqli_prepare($con, 'SELECT MAX(society_id) FROM society');
    $society_id = $max + 1;

    $statement = mysqli_prepare($con, 'INSERT INTO society(society_id, name, email, short_des, long_des) VALUES (?, ?, ?, ?, ?)');
    mysqli_stmt_bind_param($statement, 'issss', $societyId, $name, $email, $shortDes, $longDes);
    mysqli_stmt_execute($statement);
    mysqli_stmt_store_result($statement);
    mysqli_stmt_close($statement);

    mysqli_close($con);
?>

关注以下代码段:

$max = mysqli_prepare($con, 'SELECT MAX(society_id) FROM society');
        $society_id = $max + 1;

        $statement = mysqli_prepare($con, 'INSERT INTO society(society_id, name, email, short_des, long_des) VALUES (?, ?, ?, ?, ?)');
        mysqli_stmt_bind_param($statement, 'issss', $societyId, $name, $email, $shortDes, $longDes);

1 个答案:

答案 0 :(得分:0)

只需要完全删除自动增量字段的值。