Connection with a MySQL DataBase

Hello, I’m new to Unity and I need help to realise a little script which can communicate with a mysql database. I have create 2 scripts PHP and JavaScript. The PHP work, I have the good string in my variable $fin. But I don’t in using it in my JavaScript code. If someone can help me to fix my code, it will be great ! :mrgreen:

PHP :

<?php
//défintion paramètres connexion BDD
$bdd="localhost";
$login="root";
$bddname="essai";


//connexion à la BDD
$db=mysql_connect($bdd,$login);
//test conexion
if ( ! $db )
	print("erreur");
//connecte à la base
mysql_select_db($bddname);

//requete BDD
$name="immeuble";
$table="essai_table";
$req="SELECT description FROM essai_table where nom='immeuble'";
$res=mysql_query($req,$db);
$row = mysql_fetch_row($res);
mysql_close($db);

//traitement
$fin=$row[0];
echo $fin;
/**
 *
 *
 * @version $Id$
 * @copyright 2013
 */


?>

JS :

//INFO BULLE

var afficher : boolean = false;
//récupération champ description
var res= "http://localhost/searchname.php?";
var description=WWW(res).text;

function OnGUI() {

		
	//style label
	var bulle=new GUIStyle();
	bulle.normal.textColor=Color.red;
	bulle.fontSize=15;
	bulle.fontStyle= FontStyle.Bold;
	bulle.border.right=1;
	
	var bulle2=new GUIStyle();
	bulle2.normal.textColor=Color.red;
	bulle2.fontSize=15;
	bulle2.fontStyle= FontStyle.Italic;
	bulle2.border.right=1;
	
	var info= "Immeuble" ;
	var e : Event = Event.current;
	
	if (afficher == true) {
		GUI.Label (Rect (e.mousePosition.x+20, e.mousePosition.y+20, 300, 100), info, bulle );
		GUI.Label (Rect (e.mousePosition.x+40, e.mousePosition.y+40, 300, 100), description, bulle2 );
		}
}

function OnMouseOver () {
afficher = true;
}

function OnMouseExit () {
afficher = false;
}

Check your ‘description’ variable via Debug.Log - is it OK?

My variable seems empty…
But I have the following Exception when I run my Project : “UnityException: WWW is not ready downloading yet
UnityEngine.WWW.get_text () (at C:/BuildAgent/work/14194e8ce88cdf47/Runtime/ExportGenerated/Editor/Utils.cs:87)
bdd_description…ctor () (at Assets/Standard Assets/bdd_description.js:6)”

ArgumentException: InitWWW can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don’t use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
UnityEngine.WWW…ctor (System.String url) (at C:/BuildAgent/work/14194e8ce88cdf47/Runtime/ExportGenerated/Editor/Utils.cs:28)
bdd_description…ctor () (at Assets/bdd_description.js:7)

OK, just look at the docs: Unity - Scripting API: WWW.text

The request is not just simply done in one call. You have to wait for it to execute. You can do it 2 ways:

  • periodically check isDone property. Not in “for” loop, but in Update or OnGUI method.
  • use coroutine and yield the WWW object (check example in the docs)