Tuesday, 15 January 2013

mysql - In PHP, how to achieve the same purpose like StringTokenizer in Java? -



mysql - In PHP, how to achieve the same purpose like StringTokenizer in Java? -

say have string 030512 jack 25 male\n030513 david 23 male\n030514 ..., how extract info string 2 dimensional table in php?

in java, can utilize stringtokenizer, like:

stringtokenizer linetokenizer = new stringtokenizer("030512 jack ...", "\n"); list<student> students = new arraylist<student>(); while(linetokenizer.hasmoretokens()) { string line = linetokenizer.nexttoken(); stringtokenizer itemtokenizer = new stringtokenizer(line, " "); string id = itemtokenizer.nexttoken(); string name = itemtokenizer.nexttoken(); string age = itemtokenizer.nexttoken(); string sext = itemtokenizer.nexttoken(); students.add(new student(id, name, age, sex)); }

actually, final goal extracting "table-like" info , store them mysql database.

i not familiar php, show me how in php, or practice implement two-dimensional info insertion mysql database?

not fancy easier understand in sentiment (requires string doesn't end newline though, , info correctly formatted):

$students = array(); //no newline @ end, or you'll have add together check in loop. $str = "030512 jack 25 male\n030513 david 23 male"; foreach(explode("\n", $str) $student_str) { list($id, $name, $age, $sex) = explode(" ", $student_str); array_push($students, array(":id"=>$id,":name"=>$name, ":age"=>$age, ":sex"=>$sex)); } //for db part has been quite absent. $conn = new pdo("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass); $query = "insert students (id, name, age, sex) values (:id, :name, :age, :sex)"; $prepared_query = $conn->prepare($query); foreach($students $student) { $prepared_query->execute($student); }

you of course of study execute queries in first loop instead if thats want.

php mysql stringtokenizer

No comments:

Post a Comment