i want to insert timer time in my database.i have created a timer class which is increasing in miniutes and seconds (in a dynamic text field).i have a home_button i want that when i click home_button timer time would be inserted into time column of scoreu table.all code is working fine.column is updating but time is not showing up in database table please help me to solve this..here is my as3 code
var myCount:Number = 00;
var seconds:Number = 00;
var minutes:Number = 0;
var myTime:Timer = new Timer(1000,myCount);
myTime.addEventListener(TimerEvent.TIMER, startCount);
my_time.text = "";
myTime.start();
function startCount(event:TimerEvent):void
{
seconds +=1;
if (seconds > 60)
{
seconds =00;
minutes +=1;
}
my_time.text = minutes+":"+(seconds >= 10 ? seconds : "0"+seconds);
}
var variables:URLVariables = new URLVariables();
variables.time1 = my_time.text;
home_Btn.buttonMode = true;
home_Btn.addEventListener(MouseEvent.CLICK, indexBtn_click1);
function indexBtn_click1(event:MouseEvent):void
{
myTime.stop();
var request:URLRequest = new URLRequest('http://localhost/timesend.php');
request.method = URLRequestMethod.POST;
request.data = variables;
var loader:URLLoader = new URLLoader(request);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(request);
loader.addEventListener(Event.COMPLETE, dataOnLoad);
}
function dataOnLoad(event:Event)
{
var variables:URLVariables = URLVariables(event.target.data);
trace(variables.result); // gives : System Updated
}
here is timesend.php
<?php
// data.php
include('connect1.php');
// if we are here, that's mean that we are already connected to mysql server
// and we don't need to do another connection
$etime = $_POST['time1'];
// $link is the same connection created in your connect.php script
if (mysqli_query($link, "INSERT INTO scoreu (user) VALUES('$etime')")) {
echo 'result=System Updated';
} else {
echo 'result=error';
}
mysqli_close($link);
?>
there was a problem in table field type declaration ..i declared it as varchar..but now i have fixed the type as TEXT..now it is working perfect..
Related
I am creating CSV from fetching data from MySQL data base. there are around 18000 rows and 8 columns but it show me Page unresponsive error and show me kill page or wait:
I've used following code.
function report_print()
{
date = time();
$myFile = "report_$date.csv";
$this->load->library('parser');
$stringData = $this->input->post('data');
$fileArray = $this->getdata($stringData);
$this->generateconvert_to_csv($fileArray, $myFile, ',');
die;
}
I have also tried to create CSV with jQuery with following code but it shows me error for " Network fail".
jQuery.fn.tableToCSV = function() {
var clean_text = function(text){
text = text.replace(/"/g, '""');
return '"'+text+'"';
};
$(this).each(function(){
var table = $(this);
var caption = $(this).find('caption').text();
var title = [];
var rows = [];
$(this).find('tr').each(function(){
var data = [];
$(this).find('th').each(function(){
var text = clean_text($(this).text());
title.push(text);
});
$(this).find('td').each(function(){
var text = clean_text($(this).text());
data.push(text);
});
data = data.join(",");
rows.push(data);
});
title = title.join(",");
rows = rows.join("\n");
var csv = title + rows;
var uri = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
var download_link = document.createElement('a');
download_link.href = uri;
var ts = new Date().getTime();
if(caption==""){
download_link.download = ts+".csv";
} else {
download_link.download = caption+"-"+ts+".csv";
}
document.body.appendChild(download_link);
download_link.click();
document.body.removeChild(download_link);
});
};
Anyone's Help will be appreciated for how to create a CSV with this much record without any issue ?
I've got this code that retrieve data from my SQL Data Base into my AS3 code.
My table (data base) has this rows : "id", "title", "price", "information", "mail".
In my AS3 code I loaded "title".
Php Code :
header('Content-type: application/json');
$ts = gmdate("D, d M Y H:i:s") . " GMT";
header("Expires: $ts");
header("Last-Modified: $ts");
header("Pragma: no-cache");
header("Cache-Control: no-cache, must-revalidate");
$num = mysql_numrows($sql_result);
$phptheTitle = "";
$obj = array();
while ($row = mysql_fetch_array($sql_result)) {
$theTitle = $row["theTitle"];
$phptheTitle = $phptheTitle.' </br> '.$theTitle;
$datas = array();
$datas['theTitle'] = $row["theTitle"];
$datas['prix'] = $row["prix"];
$obj[] = $datas;
}
echo json_encode( array('products' => $obj) );
mysql_free_result($sql_result);
mysql_close($connection);
?>
AS3 code :
function categorieSelected(evt:Event):void {
var urlReq:URLRequest = new URLRequest ("http://www.mywebsite.com/find_annonces.php");
urlReq.method = URLRequestMethod.POST;
var urlVars:URLVariables = new URLVariables();
urlReq.data = urlVars;
trace("typeSelected");
urlVars.categorie = evt.target.value;
trace(urlVars.categorie);
varLoader2.load(urlReq);
var loader:URLLoader = new URLLoader (urlReq);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(urlReq);
trace(urlReq);
loader.addEventListener(Event.COMPLETE, loadComplete);
}
function loadComplete(evt:Event):void {
trace("loadComplete");
var myResult:String = evt.target.data;
trace(myResult);
output_txt.htmlText = myResult;
var datas :Object = JSON.parse( myResult );
var products :Array = datas && datas.products ? datas.products : [];
var len:int = products.length;
for( var i:int = 0; i<len; ++i ){
trace( products[i].title, products[i].price );
}
}
So my output_txt is displaying all items in the row "title".
Now, is it possible to create a link for each title(in AS3) ?
In order to display "price", "information", "mail" when we click on the title(each title has their own "price", "information" and "mail", contain in my database).
Exemple :
The AS3 code displays "Computer". When I click on "ipod Touch" it displays "price", "information" and "mail" that is contains in my database.
Here's a short video of what I'd like to do : http://sendvid.com/whdm4sjf
EDIT
So with the help of Aaron, the code works a little bit better.
In my AS3, the user can choose a "categorie" in order to displays all the titles contains in the categorie.
For that I've put this $categorie = $_POST['categorie']; in PHP
And this code in AS3
var loader5:URLLoader = new URLLoader();
var varLoader2:URLLoader = new URLLoader;
varLoader2.dataFormat=URLLoaderDataFormat.VARIABLES;
varLoader2.addEventListener(Event.COMPLETE,completeHandler2);
function categorieSelected(evt:Event):void {
var urlReq:URLRequest = new URLRequest ("http://www.brousse-en-folie.com/sondage/convertXML.php");
urlReq.method = URLRequestMethod.POST;
var urlVars:URLVariables = new URLVariables();
urlReq.data = urlVars;
trace("typeSelected");
urlVars.categorie = evt.target.value;
varLoader2.load(urlReq);
loader5.load(new URLRequest("http://www.brousse-en-folie.com/sondage/convertXML.php"));
loader5.addEventListener(Event.COMPLETE, complete);
}
But it seems that with the JSON loading, there is a conflict and I've got this error with the function categorieSelected
Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
Here's a short video of the problem : http://sendvid.com/18rr26rb
Here's a rough idea of what I would do:
Return all your data as XML or JSON. For example you can use PHP json_encode to return the SQL results as JSON.
Load the JSON into AS3 using URLLoader and JSON.parse.
Now you have an Array of data you can iterate over and display list items.
Add a click handler to each display list item that will hide the list, and show a detailed view.
You can accomplish this many ways, here's one simple example:
PHP
$products = array();
while ($row = mysql_fetch_array($sql_result)) {
$products[] = array(
"title" => $row["theTitle"],
"price" => $row["thePrice"]
);
}
echo json_encode($products);
Which should output valid JSON like this:
[
{
"title": "Product 1",
"price": 100
},
{
"title": "Product 2",
"price": 200
},
{
"title": "Product 3",
"price": 300
}
]
AS3
Load the JSON and render it out:
var products:Array;
var list:Sprite = new Sprite();
addChild(list);
var details:TextField = new TextField();
addChild(details);
var loader:URLLoader = new URLLoader();
loader.load(new URLRequest("products.php"));
loader.addEventListener(Event.COMPLETE, complete);
function complete(e:Event):void {
products = JSON.parse(loader.data) as Array;
for(var i:int = 0; i < products.length; i++){
createListItem(i, products[i]);
}
showList();
}
function createListItem(index:int, item:Object):void {
var listItem:TextField = new TextField();
listItem.text = item.title;
listItem.y = index * 20;
listItem.addEventListener(MouseEvent.CLICK, function(e:MouseEvent):void {
showDetails(item);
});
list.addChild(listItem);
}
function showList():void {
details.visible = false;
list.visible = true;
}
function showDetails(item:Object):void {
list.visible = false;
details.visible = true;
details.text = "Price: " + item.price + "\nInformation: " + item.information + "\nMail: " + item.mail;
}
This is just a rough start to give you an idea.
i want to update my database table newlessontime by posting a value from as3.but query is not working ...but when i give $etime = 4 in php code then database is updating lesson1 column but but when it comes for post method, value is not inserting into lesson1 column why is this happening? stdroll column value was inserted already i want to update lesson1 in same row of the table
here is my php file
// lesson1t.php
include('connect.php');
$etime = $_POST['time1'];
//$etime = 4;
if (mysqli_query($link, "UPDATE newlessontime set lesson1=$etime WHERE stdroll=123")) {
echo 'result=System Updated';
} else {
echo 'result=error';
}
mysqli_close($link);
?>
here is the fla file
home_Btn.buttonMode = true;
home_Btn.addEventListener(MouseEvent.CLICK, indexBtn_click1);
function indexBtn_click1(event:MouseEvent):void
{
myTime.stop();
variables.time1 = my_time.text ;
var request:URLRequest = new URLRequest('http://localhost/lesson1t.php');
request.method = URLRequestMethod.POST;
request.data = variables;
var loader:URLLoader = new URLLoader(request);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(request);
loader.addEventListener(Event.COMPLETE, dataOnLoadl);
function dataOnLoadl(event:Event)
{
var variables:URLVariables = URLVariables(event.target.data);
trace(variables.result); // gives : System Updated
}
gotoAndPlay("manu");
SoundMixer.stopAll();
}
Maybe you problem is that you do not defined variable.time1 as a var in as3.
Try this...
home_Btn.buttonMode = true;
home_Btn.addEventListener(MouseEvent.CLICK, indexBtn_click1);
function indexBtn_click1(event:MouseEvent):void
{
myTime.stop();
var request:URLRequest = new URLRequest('http://localhost/lesson1t.php');
request.method = URLRequestMethod.POST;
//You should define what is variables...
var variables:URLVariables = new URLVariables(); //this you forgot!
variables.time1 = my_time.text ;
request.data = variables;
var loader:URLLoader = new URLLoader(request);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(request);
loader.addEventListener(Event.COMPLETE, dataOnLoadl);
function dataOnLoadl(event:Event)
{
var variables:URLVariables = URLVariables(event.target.data);
trace(variables.result); // gives : System Updated
}
gotoAndPlay("manu");
SoundMixer.stopAll();
}
Try this and tell us what happen...
I forgot to give quote around $etime.
It should be '$etime' ..Now its working
I have this code on .fla file
fm_button.visible = false;
var menu_label:Array = new Array("Introduction", "Products", "Services",
"Testimonials", "Our Company", "Contact Us");
var total:Number = menu_label.length;
var i:Number = 0;
var page:Number;
var main_menu:MovieClip = new MovieClip();
stage.addChild(main_menu);
for (i = 0; i < total; i++)
{
var btn = new flashmo_button();
btn.name = "btn" + i;
btn.x = fm_button.x;
btn.y = fm_button.y + i * ( fm_button.height + 10 );
btn.buttonMode = true;
btn.item_no = i;
btn.flashmo_click_area.addEventListener( Event.ENTER_FRAME, btn_enter );
var each_substring:Array = menu_label[i].split("|");
btn.flashmo_button_label.fm_label.text = each_substring[0];
btn.item_url = each_substring[1];
main_menu.addChild(btn);
}
function btn_over(e:MouseEvent):void
{
e.target.parent.over = true;
}
function btn_out(e:MouseEvent):void
{
e.target.parent.over = false;
}
What i want is to get this values:
("Introduction", "Products", "Services", "Testimonials", "Our
Company", "Contact Us");
from a text or php file named menu.php or menu.txt
Is this possible?
Why you need read from .php file?
Is this client-server communication?
In that case, when .fla file loads by client browser over http(s) you should do something like this:
menu.php (for example put this file to document root folder):
<?php $menu = array('Elem1', 'Elem2');
echo json_encode($menu); ?>
.fla:
var sendData:URLVariables = new URLVariables();
var request:URLRequest = new URLRequest('/menu.php');
request.method = URLRequestMethod.GET;
var loader:URLLoader = new URLLoader(request);
loader.addEventListener(Event.COMPLETE, onCompleted);
So, your .fla are doing query to server and get's list of categories (onCompleted method receive data).
If this is not server-client communication, you should use other file format, because .php is not a data storage )
I'm creating flash game. Here is timer, which counts how long player playing. When "Game is over" counter stops. And I need to write this time to database. My counter format is MM:SS, so I don't know how to do It.
Here is my code to send data from game to php:
var urlReq:URLRequest = new URLRequest ("band.php");
// Set the method to POST
urlReq.method = URLRequestMethod.POST;
// Define the variables to post
var urlVars:URLVariables = new URLVariables();
urlVars.time = timer.currentCount;
urlVars.userName = "myUserName";
// Add the variables to the URLRequest
urlReq.data = urlVars;
// Add the URLRequest data to a new Loader
var loader:URLLoader = new URLLoader (urlReq);
// Set a listener function to run when completed
loader.addEventListener(Event.COMPLETE, onLoginComplete);
// Set the loader format to variables and post to the PHP
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(urlReq);
So i send my time variable to php.
Here is php code to get time:
<?php
$time = $_POST['time'];
$username = $_POST['userName'];
$con=mysqli_connect("localhost","my_db","pass","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO eurokos (time, userName)
VALUES ('$time', '$username')");
$query = "INSERT INTO eurokos VALUES" . "('$time', '$username')";
echo "success=true";
?>
So username sucessfully insterting to database, that means everything is finy with sending variables to php, but time always "0" value, so that means something wrong with timer.
My timer looks like:
function showTimePassed(startTime:int):String {
var leadingZeroMS:String = ""; //how many leading 0's to put in front of the miliseconds
var leadingZeroS:String = ""; //how many leading 0's to put in front of the seconds
var leadingZeroM:String = "";
var time = getTimer() - startTime; //this gets the amount of miliseconds elapsed
var miliseconds = (time % 1000); // modulus (%) gives you the remainder after dividing,
if (miliseconds < 10) { //if less than two digits, add a leading 0
leadingZeroMS = "0";
}
var seconds = Math.floor((time / 1000) % 60); //this gets the amount of seconds
if (seconds < 10) { //if seconds are less than two digits, add the leading zero
leadingZeroS = "0";
}
var minutes = Math.floor((time / (60 * 1000) ) );
if (minutes < 10) { //if seconds are less than two digits, add the leading zero
leadingZeroM = "0";
}
//60 seconds times 1000 miliseocnds gets the minutes
return leadingZeroM + minutes + ":" + leadingZeroS + seconds ;
}
I don't know whats wrong, why time not inserting to database. Could you help me? Thanks.
UPDATE
<?php
$time = $_POST['time'];
$username = $_POST['userName'];
session_start();
$name = $_SESSION['vardas'];
$times = gmdate('H:m:s', $time);
$con=mysqli_connect("localhost","padekime_db","pass","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "INSERT INTO eurokos VALUES" . "('$times', '$username')";
echo "success=true";
if ($stmt = $mysqli->prepare("INSERT into eurokos (time, userName) VALUE (?,?) ")) {
$stmt->bind_param("i", $time);
$stmt->bind_param("s", $name);
$stmt->execute();
}
?>
UPDATE 2
function startMemoryGame():void
{
addChild(CardContainer);
timer = new Timer(1000); //create a new timer that ticks every second.
timer.addEventListener(TimerEvent.TIMER, tick, false, 0, true); //listen for the timer tick
timer.addEventListener(TimerEvent.TIMER, resetTimer);
txtTime = new TextField();
var format:TextFormat = new TextFormat();
format.font = "Verdana";
format.color = "#E50041";
format.size = 22;
txtTime.border = true;
txtTime.borderColor = 0xFFFFFF;
//format.bold = true;
//txtTime.x = 250;
txtTime.width/2;
var stageCenter_x:Number = stage.stageWidth/2;
var stageCenter_y:Number = stage.stageHeight/2;
var textCenter_x:Number = txtTime.width/2;
var textCenter_y:Number = txtTime.height/2;
txtTime.x = stageCenter_x - textCenter_x;
txtTime.y = 55;
txtTime.autoSize = TextFieldAutoSize.CENTER;
txtTime.defaultTextFormat = format;
message_txt.autoSize = TextFieldAutoSize.CENTER;
message_txt.defaultTextFormat = format;
txtTime.text = setNull(0);
addChild(txtTime);
tmpTime = getTimer();
timer.start();
}
private function tick(e:Event):void {
txtTime.text = showTimePassed(tmpTime);
}
function setNull(startTime:int):String {
return "00:00";
}
function showTimePassed(startTime:int):String {
var leadingZeroMS:String = ""; //how many leading 0's to put in front of the miliseconds
var leadingZeroS:String = ""; //how many leading 0's to put in front of the seconds
var leadingZeroM:String = "";
var time = getTimer() - startTime; //this gets the amount of miliseconds elapsed
var miliseconds = (time % 1000); // modulus (%) gives you the remainder after dividing,
if (miliseconds < 10) { //if less than two digits, add a leading 0
leadingZeroMS = "0";
}
var seconds = Math.floor((time / 1000) % 60); //this gets the amount of seconds
if (seconds < 10) { //if seconds are less than two digits, add the leading zero
leadingZeroS = "0";
}
var minutes = Math.floor((time / (60 * 1000) ) );
if (minutes < 10) { //if seconds are less than two digits, add the leading zero
leadingZeroM = "0";
}
//60 seconds times 1000 miliseocnds gets the minutes
return leadingZeroM + minutes + ":" + leadingZeroS + seconds ;
}
function getTimePassed(startTime:int):Number {
return (getTimer() - startTime) /1000;
}
Here send variable to php:
var urlReq:URLRequest = new URLRequest ("band.php");
// Set the method to POST
urlReq.method = URLRequestMethod.POST;
// Define the variables to post
var urlVars:URLVariables = new URLVariables();
urlVars.userName = 'myUsername';
urlVars.time = getTimePassed(startTime); // HERE I GET ERROR
// Add the variables to the URLRequest
urlReq.data = urlVars;
// Add the URLRequest data to a new Loader
var loader:URLLoader = new URLLoader (urlReq);
// Set a listener function to run when completed
loader.addEventListener(Event.COMPLETE, onLoginComplete);
// Set the loader format to variables and post to the PHP
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(urlReq);
}
The value of time in mysql is always 0 because MySql receive the time as string "MM:SS" and the data type of the field time is INT.
You have 2 solutions : converts MM:SS to number of seconds on the PHP side before the insert query or send the total of seconds from the flash side (better from my pov).
Update : get the elapsed time directly from timer instance
[...]
urlVars.time = timer.currentCount; // time elapsed in seconds
On the PHP side, use prepared statements :
Update : full script to save time / username in DB
[...]
$time = $_POST['time'];
$username = $_POST['userName'];
$mysqli = new mysqli("localhost","padekime_db","pass","my_db");
if ($stmt = $mysqli->prepare("INSERT into eurokos (time, userName) VALUES (?,?) ")) {
$stmt->bind_param('is',$time,$username);
$stmt->execute();
if ($stmt->error != '') {
echo ' error:'.$stmt->error;
} else {
echo 'success';
}
$stmt->close();
} else {
echo 'error:'.$mysqli->error;
}
If you trace the value of loader.data in the onLoginComplete handler, you should see "success" or "error:the error description"
http://www.php.net/manual/en/mysqli-stmt.prepare.php