如何返回我在同一个查询中创建的或以前创建的记录

kkbh8khc  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(241)

如何返回在同一查询中创建的记录。
我试过了 $row[Password] 但它不起作用。请帮忙

$sql = "SELECT COUNT(*) FROM characters WHERE GUID=:GUID";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':GUID', $_GET['GUID'], PDO::PARAM_INT);
    $stmt->bindColumn(4, $charactername);
$stmt->execute();
$res = $stmt->fetchColumn();
if($res == 1) {
    echo "Already created";
}

if(!$res){
        $sql = "INSERT INTO characters (GUID,Charactername,Password) VALUES (:GUID,:Charactername,FLOOR( 1000 + ( RAND( ) *8999 ) ))";
        $stmt= $pdo->prepare($sql);
        $stmt->bindParam(':GUID', $_GET['GUID'], PDO::PARAM_INT);
        $stmt->bindParam(':Charactername', $_GET['Charactername'], PDO::PARAM_INT);                 
        $stmt->execute();
        echo " THIS password created with FLOOR";
}
edqdpe6u

edqdpe6u1#

您可以通过返回最后插入的id $id = $stmt->lastInsertId(); 然后对返回的id执行选择。

hgb9j2n6

hgb9j2n62#

如果需要获取随机生成的密码,可以使用多个查询:

<?php

$_GET['GUID'] = 1;
$_GET['Charactername'] = 'test';
$sql = "SET @password := FLOOR( 1000 + ( RAND( ) *8999 ));
        INSERT INTO characters (GUID,Charactername,Password) VALUES (:GUID,:Charactername,@password);
        SELECT @password as Password";

$stmt= $pdo->prepare($sql);
$stmt->bindParam(':GUID', $_GET['GUID'], PDO::PARAM_INT);
$stmt->bindParam(':Charactername', $_GET['Charactername'], PDO::PARAM_STR);                 
if ($stmt->execute()) {
    do {
        if ($rowset = $stmt->fetch(PDO::FETCH_ASSOC)) {
            echo " THIS password created with FLOOR: " . $rowset['Password'];
        }
    } while ($stmt->nextRowset());
}

如果要插入上一条语句中的所有值,还可以使用last\u insert\u id():

$sql = "INSERT INTO characters (GUID,Charactername,Password) VALUES (:GUID,:Charactername,FLOOR( 1000 + ( RAND( ) *8999 ) ));
        SELECT * FROM characters WHERE id = LAST_INSERT_ID()";

$stmt= $pdo->prepare($sql);
$stmt->bindParam(':GUID', $_GET['GUID'], PDO::PARAM_INT);
$stmt->bindParam(':Charactername', $_GET['Charactername'], PDO::PARAM_STR);                 
if ($stmt->execute()) {
    do {
        if ($rowset = $stmt->fetch(PDO::FETCH_ASSOC)) {
            echo " THIS password created with FLOOR: " . $rowset['Password'];
        }
    } while ($stmt->nextRowset());
}
pcww981p

pcww981p3#

使用 $stmt->lastInsertId(); 之后 $stmt->execute(); 获取插入的记录id,然后进行另一个查询以选择该记录。

相关问题