简体   繁体   中英

Obtain value of previously executed prepared statement in php

I have used a prepared statement to set a variable as follows:

$CPI = $cxn->prepare('SET @CPI = ?');
$CPI->bind_param('d', $_POST['CPI_Esc']);
$CPI->execute();

I would now like to access the value of @CPI in later php script without using $_POST['CPI_Esc']. I have tried the following as it makes sense in terms of MySQL:

$Check = "SELECT @CPI";
$Check = mysqli_query($cxn, $CPI);
echo $Check . " CPI value";

I am pretty sure the mysqli_query() is the wrong function to use here - I am not sure which to use or whether I am approaching this the wrong way. I just want to create a variable in php that I can use later based on the value of my previously executed prepared statement. Any thoughts?

I just want to create a variable in php that I can use later

Each PHP run is a separate process which has its own variable scope not shared among other processes. To store a value to be accessed from different runs you'll need some external storage. Here are some:

  • A table in a database, such as MySQL or MongoDB or whatever.
  • A file on disk.
  • APC cache.
  • Memcache or Redis.

If both runs share a session id (for example, you access them from the browser by refreshing the same page or by navigating your site) then you can take advantage of PHP's built-in session storage and $_SESSION variable. Please read further: http://php.net/manual/en/book.session.php as your mileage may vary.

UPD. A very brief introduction to how you use session variables to access data between different requests to the same page.

  1. Put this on top of your php script:

     session_start(); 
  2. Store the value under some key with a usual array assignment:

     $_SESSION['CPI'] = $_POST['CPI_Esc']; 
  3. Access it later with a usual array dereference:

     echo "CPI value: {$_SESSION['CPI']}\\n"; 

Under usual circumstances* this should work for you.

* Usual circumstances include: unchanged php configuration; sufficient permissions for php process to write to the sessions directory; your browser accepts cookies.

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