简体   繁体   中英

How can I use a result from a SQL-statement in second SQL-statement? | PHP

Hi , to everyone who reads this,
I've trying to read out a UserId from my MySql Database.
I want to use the result in the next SQL statement which should
add the Id into another table. The problem is I've no idea how to do that.

Here I've tried to select the row "UserId" from my accounts table.

Code looks like this:

//first statement
$SqlLookStm = ("SELECT UserId FROM accounts WHERE UserName = ?");
$initLStm = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($initLStm, $SqlLookStm)) {
    header('Location: ../signup.php?error=SqlError');
    exit();

} else {
    mysqli_stmt_bind_param($initLStm, "s", $UserName);
    mysqli_stmt_execute($initLStm);
}

$UserName is a value out of a form.

Now I want to use the userid, which should be the result from the first statement,
in my next SQL statement, which should add the id from the user in the
"account_session" table under the row "account_id" .

Code looks so:

//second statement
$SqlInsertIdStm = ("INSERT INTO account_session (account_id) VALUES (?)");
$initIIStm = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($initIIStm, $SqlInsertIdStm)) {
   header('Location: ../signup.php?error=SqlError');
   exit();

} else {
    mysqli_stmt_bind_param($initIIStm, "s", $id);
    mysqli_stmt_execute($initIIStm);
}

But how can I use the result from statement one so that I can insert it as the
$id string in the second statement?

I've been trying this now for four days... (╯°□°)╯︵ ┻━┻
Thanks to everyone who can help me.

Try to bind the id as an integer like this

mysqli_stmt_bind_param($initIIStm, "d", $UserId);

And then execute the statement (i recomend you to use lower case character for first character of string)

EDIT: when I wrote the comment, I was thinking about the printf() function that needs %d to print decimal values, instead of 'd' use 'i'

MySQL single query answer:

INSERT INTO `account_session` (account_id) SELECT `UserId` FROM `accounts` WHERE `UserName` = ?

To do this with PHP and MySQLi I would recommend using an Object Orientated approach, thus:

$myOwnSql = new mysqli('localhost', 'my_user', 'my_password', 'my_database');
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit;
}
$sql = "INSERT INTO `account_session` (account_id) SELECT `UserId` FROM `accounts` WHERE `UserName` = ?";

/***
 * Prepare the SQL statement
 ***/
$stmt = $myOwnSql->prepare($sql);
$stmt->bind_param('s', $UserName);

/***
 * Execute the prepared statement 
 ***/
$stmt->execute();
if($stmt->affected_rows < 1){
    /***
     * Nothing effected, something went wrong.
     ***/
    error_log("SQL Error: %s.\n", $stmt->error);
    header('Location: ../signup.php?error=SqlError');
    exit;
}
/***
 * close statement and connection 
 ***/
$stmt->close();

How to extract data from the database using MySQLi Object Orientated (OO):

$myOwnSqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit;
}

/***
 * Assume we have this table and it is suitably populated  
 ***/
$query = "SELECT UserId, RealName FROM accounts WHERE UserName = ?";

$stmt = $myOwnSqli->prepare($query);
$stmt->bind_param('s', $UserName);
$stmt->execute();

/***
 * Bind result variables 
 ***/
$stmt->bind_result($userId, $humanName);

/***
 * fetch each found row of bound values 
 ***/
 while ($stmt->fetch()) {
        print "Name: ".$humanName."<BR>";
 }

 /***
  * close statement 
  ***/
 $stmt->close();


/***
 * close DB connection 
 ***/
$myOwnSqli->close();

Read The Manual


To solve your specific issue with the code you have (ie not to rework your current code) please view and show us your error_log file generated by PHP / MySQL.

Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM