简体   繁体   中英

How to pass a variable between php scripts using a database

I have 1 HTML document (it is .php, but I'll refer to it as HTML doc) with 3 different fill-in-forms which each has their own PHP script for inserting the data into a database. Each form has its own script and its own table in the database.

I need an ID or username I can give the user on the first form's submission, and then store the ID/username variable and insert it into form 2 and in form 3. So what I need is to have a variable pass from one script to two other scripts.

I tried giving a ID/username in the first script, then in the second script I just collect it via SQL from the table. It doesn't seem to work.

Script 1: $personID = 'a1';

Script 2: $today = date("Y/m/d"); $personID = mysql_query("SELECT personID FROM reviewpi WHERE date >= '$today' "); $today = date("Y/m/d"); $personID = mysql_query("SELECT personID FROM reviewpi WHERE date >= '$today' ");

Please help?

Your query tries to get the ID , based on today's date.

That is not a good approach at all, what if you had multiple persons that day?

Since you are just trying to carry the id over from page to page, a session would be the right tool.

Set the session:

session_start(); 
$_SESSION['personID'] = 'a1';

Get the session:

session_start(); 
$personID = $_SESSION['personID'];

If you find your self needing to get the data of that person.

Simply retrieve the ID and query your DB again.

SELECT * 
FROM reviewpi 
WHERE personID = ?


Please note:

  • You need to stop using mysql, it's deprecated
  • Use mysqli or PDO(recommended)
  • Use prepared statement to avoid SQL injection attacks

For those who would like to know how I did it, here is what I did.

In the first scripts I added

session_start(); $_SESSION['personID'] = 'a1b2c3';

and in the 2nd and 3rd script I added

session_start(); $personID = $_SESSION['personID'];

then in my SQL insert statement on each script page (even script1)

$mysqli->query("INSERT into reviewdc ( personID ) VALUES ( '{$_SESSION['personID']}' )" );

My question was probably a stupid and answered question for some of you, but I couldn't find any research on how exactly to do it, and I tried most of the solutions given on other posts, none of them worked.

Thanks for those who helped.

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