用PHP插入后获取UUID()

时间:2018-12-09 14:03:51

标签: php mysql mariadb uuid

我正在尝试获取刚刚插入的UUID。

这在phpMyAdmin中有效。但是会在PHP中引发错误。

$insert = $conn->query(" 

    SET @usr_uuid = uuidToBin(UUID());

    INSERT INTO `users` (`users`.`usr_uuid`) VALUES ( @usr_uuid );

    SELECT HEX(@usr_uuid) AS usr_uuid;
");

但是我收到此错误:

[errno] => 1064
[sqlstate] => 42000
[error] => You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INSERT INTO `users` (`users`.`usr_uuid`) VALUES ( @u' at line 3

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:-1)

您有两种选择。

首先,正在使用事务。例如:

       <variable
                name="loginpageevent"
                type=".............model.LogInPageClick"/>

    add this ->android:onClick="@{(view)->loginpageevent.backbuttoncalled()}"

    <ImageView
                    android:layout_width="25dp"
                    android:layout_height="wrap_content"
                    android:src="@drawable/back_button"
                    android:onClick="@{(view)->loginpageevent.backbuttoncalled()}"
                     />

then in activity class 

 LogInPageClick  logInPageClick=new LogInPageClick(this);

then in Model class, how to call onbackpressed or finish();

public class LogInPageClick {
    private Context context;


   public LogInPageClick(Context context) {
        this.context = context;

    }
 public void backbuttoncalled() {
        Activity activity = (Activity) context;
        activity.onBackPressed();
    }
}

仅当您使用mysqli和innodb存储引擎时,此选项才有效。

第二个选项,执行两个查询:

$conn->begin_transaction();
$insert = $conn->query("SET @usr_uuid = uuidToBin(UUID());";
$insert = $conn->query("INSERT INTO `users` (`users`.`usr_uuid`) VALUES ( @usr_uuid );";
$insert = $conn->query("SELECT HEX(@usr_uuid) AS usr_uuid;";
$conn->commit();

此选项可能会导致您在执行新插入操作时遇到问题。但是,如果表用户具有ID,则可以按照@ user3783243的建议使用mysql-insert-id()。