Hi how to write php code for this, I have file contain list of data for example
AA123_jane_G-1
AA456_oshi_K-3
AA789_pritt_P-4
I read my file using
function myfile(){
while (($data = fgetcsv($handle, 1000, "_")) !== FALSE) {
..................
........
.......
//get $student_id, $name, $class,
}
I need to get username and password using student_id from file
function getusernameandpassword($student_id){
........
.......
$result = mysql_query("SELECT student_id, username, password FROM account WHERE student_id= '".$student_id."'");
........
//get $username and $password from other remote server
....... }
after execute the both function, I want to gather all the information of that student and insert to DB
function insertDB(){
........
.......
mysql_query("INSERT INTO user_info
(student_id, username, password, name, class) VALUES ($student_id,$username,$password,$name,$class)")
........
.......
//insert all the paramater get from both function for each student to localhost DB}
My question, how I write this function in 1 script using php. How to return value and how to get the value to be input for other function
to use a function's variable outside of the function, you either return the variable and assign it to another variable, or set the desired variable as global
inside the function, for example:
function test(){
global $variable;
}
and then you can use it any where inside the script.
First off stop using the deprecated mysql functions you should be using PDO. Also back tick your field/columns/tables to avoid any clash with reserve words
If I understood you should be able to do this in a single SQL statement like
'INSERT INTO `user_info`(`student_id`, `username`, `password`, `name`, `class`)
SELECT `student_id`, `username`, `password`, '.$name.','.$class.' FROM `account` WHERE `student_id`= '.$student_id.')'
See here for more info on the INSERT...SELECT syntax
By selecting variables (ie name and class) passed into the query string you can also insert the info not available in the account table (which I guess you are getting from the text file)
You could use arrays
function getusernameandpassword($student_id) {
....
return array('username' => $username, 'password' => $password);
}
function insertDB($infos){
....
mysql_query("INSERT INTO user_info (student_id, username, password, name, class) VALUES ($student_id, {$infos['username']}, {$infos['password']}, $name, $class)");
....
}
Or you could use objects
function getusernameandpassword($student_id) {
....
return (object)array('username' => $username, 'password' => $password);
}
function insertDB($infos){
....
mysql_query("INSERT INTO user_info (student_id, username, password, name, class) VALUES ($student_id, {$infos->username}, {$infos->password}, $name, $class)");
....
}
@mike-miller is right, stop using the deprecated mysql functions