First experiment with DataBase with haXe/PHP
For this tutorial I've created a DataBase in my localhost. I've a table named "users" in wich i've 5 fields :
- ID
- name
- age
- located
We're going to learn to connect to this database and to make some sql requests and to display them.
package;
import php.db.Connection;
import php.db.ResultSet;
import php.db.Mysql;
import php.Lib;
import Std;
class Main
{
public var cnx:Connection;
static function main()
{
new Main();
}
public function new()
{
/* Use Mysql class to connect to your Data base
the connect() method needs host , port, user, pass, socket and database value
*/
cnx = Mysql.connect( {
host : 'localhost',
port : null,
user : 'root',
pass : 'my_pass_word',
socket : null,
database : 'DBTest'
});
/*=============================*/
/* Our SQL request
the request() method returns a ResultSet
If you need to get it into a dynamic object use next() method*/
var sql = "SELECT * FROM `users` where id=2";
var result = cnx.request(sql).next();
Lib.print( result.name+
"<hr/>"+result.age+
"<br/>"+result.located);
/*==============================*/
/*
However if you want to get results into a List
use results() method
*/
/*===============================*/
var results = cnx.request(sql).results();
for(r in results)
{
Lib.print('<br/>'+r.name);
}
/*=================================*/
/*
do stuff as you want using our Connection object
cnx.request(sql_request)
*/
/*================================*/
sql = "INSERT INTO users (name, age, located) VALUES ('PLIIP', 81, 'Frugubruk')";
cnx.request(sql);
/*================================*/
/*===============================*/
sql = "UPDATE users SET name='PLOOO', age=45, located='PLOOOP' WHERE id=173";
cnx.request(sql);
/*===============================*/
/*And so on...*/
/*
Don't forget to close connection
*/
cnx.close();
}
}
Page(s) :
1
Contact
Follow me