I have a MySQL database and I access it through PHP script. The issue I have is that the variables returned from PHP are always the same.
First time I run the code (add/remove records in the database) every thing is correct, but if I'm running it again (add/remove) PHP reports back to AS3 the same records as before. running the php directly in the browser returns are correct.
hope someone can help me... I'm getting crazy!
here are my codes:
AS3
function sendSqlData(event:Event):void
{
playlistDateString = "&playlistDateString="+playlistDate.getFullYear().toString()+monthDigit+playlistDate.getMonth().toString()+dayDigit+playlistDate.getDate().toString();
playlistSongNr = "&playlistSongNr="+ song;
songTime ="&songTime="+ Math.floor(channel.position);
var phpUrl:String = "send_data.php";
var phpUrlRequest:URLRequest = new URLRequest(phpUrl+parseMe+playlistDateString+playlistSongNr+songTime);
scriptLoader = new URLLoader();
scriptLoader.addEventListener(Event.COMPLETE, sendSqlDataComplete);
scriptLoader.load(phpUrlRequest);
}
function getSqlData(event:Event):void
{
var phpUrl:String = "get_data.php";
var phpUrlRequest:URLRequest = new URLRequest(phpUrl+parseMe);
// phpUrlRequest.method = URLRequestMethod.POST;
scriptLoader = new URLLoader();
// scriptLoader.dataFormat = URLLoaderDataFormat.TEXT;
scriptLoader.addEventListener(Event.COMPLETE, getSqlDataComplete);
scriptLoader.load(phpUrlRequest);
}
function sendSqlDataComplete(event:Event):void
{
scriptLoader.removeEventListener(Event.COMPLETE, sendSqlDataComplete);
var phpVars:URLVariables = new URLVariables();
phpVars.decode(event.target.data);
getSqlData(event);
}
function getSqlDataComplete(event:Event):void
{
scriptLoader.removeEventListener(Event.COMPLETE, getSqlDataComplete);
var phpVars:URLVariables = new URLVariables();
phpVars.decode(event.target.data);
var phpString = event.target.data.toString();
var patterns:Array = ["id\\d{0,5}=\\d{0,5}", "playlistDate\\d{0,5}=\\d{0,8}", "playlistSongNr\\d{0,5}=\\d", "songTime\\d{0,5}=\\d{0,7}"];
for (var j:int = 0; j < 4; j++)
{
var pattern:RegExp = new RegExp(patterns[j],"g");
var tempStrings:Array = phpString.match(pattern);
for (i = 0; i < Number(phpVars.records); i++)
{
switch (j)
{
case 0:
ids[i] = Number(tempStrings[i].substring( tempStrings[i].indexOf("=")+1 ));
break;
case 1:
playlistDates[i] = Number(tempStrings[i].substring( tempStrings[i].indexOf("=")+1 ));
break;
case 2:
playlistSongNrs[i] = Number(tempStrings[i].substring( tempStrings[i].indexOf("=")+1 ));
break;
case 3:
songTimes[i] = Number(tempStrings[i].substring( tempStrings[i].indexOf("=")+1 ));
break;
}
}
tempStrings = null;
}
fillDataGrid(Number(phpVars.records));
}
PHP: send_data.php
<?php
include_once ('connect.php');
$playlistDateString = trim($_GET['playlistDateString']);
$playlistSongNr = trim($_GET['playlistSongNr']);
$songTime = trim($_GET['songTime']);
if($connection)
{
$status .= ("connect=ok&");
//Select database
mysql_select_db($dbname, $connection);
$sql="INSERT INTO $tablename1 (ID, playlistDate, playlistSongNr, songTime, comment) VALUES ('', '$playlistDateString', '$playlistSongNr', '$songTime', 'comment');";
$status .= ("sql=".$sql."&");
// Execute query
if (mysql_query($sql,$connection) )
{
$status .= ("query=ok");
}
else
{
$status .= ("query=error:".mysql_error());
}
}
else
{
$status = ("connect=error: ".mysql_error());
}
echo $status;
mysql_close($connection);
?>
PHP get_data.php
<?php
include_once ('connect.php');
if($connection)
{
$status .= ("connect=ok");
//Select database
mysql_select_db($dbname, $connection);
//Execute query
$query = mysql_query("SELECT * FROM $tablename1");
if ($query)
{
$result = "records=".(mysql_num_rows($query));
$i = 0;
while ($row = mysql_fetch_array($query))
{
$result .= "&id".$i."=".($row["ID"]);
$result .= "&playlistDate".$i."=".($row["playlistDate"]);
$result .= "&playlistSongNr".$i."=".($row["playlistSongNr"]);
$result .= "&songTime".$i."=".($row["songTime"]);
$result .= "&comment".$i."='".($row["comment"])."'";
$i++;
}
$status .= ("&receive=ok");
echo $result."&";
}
else
{
$status .= ("&receive=error");
}
}
else
{
$status .= ("connect=error:".mysql_error());
}
echo $status;
mysql_close($connection);
?>
It seems that your response is being cached when you call it from ActionScript. You can add a microtime value to the end of the URL (which will prevent caching).
var phpUrl:String = "get_data.php?" + new Date().getTime();
Related
I am stumbling into the following issue.. I am trying to retrieve some information from my DB using Ajax, however, my query is failing for some reason, when trying to debug it by analyzing the information within the mysqli_object, all the properties are null:
I printed the contents of the object of the console:
affected_rows:null
client_info:null
client_version:null
connect_errno:null
connect_error:null
errno:null
error:null
error_list:null
field_count:null
host_info:null
info:null
insert_id:null
protocol_version:null
server_info:null
server_version:null
sqlstate:null
stat:null
thread_id:null
warning_count:null
Why can this happen?
Here's my Ajax call:
$('#npClientName').keyup(function(){
var txt = $(this).val();
if (txt == "") {
$('#npClientList').fadeOut();
return false;
}
$.ajax({
method: 'POST',
url: '/fitcoControl/Resources/PHP/Clientes/fetchPopupClientList.php',
data:{txt: txt},
success: function(result){
rsp = JSON.parse(result);
console.log(rsp);
if (rsp.code != "1") {
$('#npClientList').html("<p>Hubo un error al cargar la lista de clientes...</p>");
console.warn("Error en el query: " + rsp.response);
} else {
$('#npClientList').html(rsp.response);
}
$('#npClientList').fadeIn();
clientSelector();
},
error: function(exception){
console.error(exception);
}
});
});
And here's my PHP code:
$root = $_SERVER['DOCUMENT_ROOT'];
$data = array(
'code'=>"",
'response'=>""
);
$txt = "'%" . $_POST['txt'] . "%'";
require $root . "/fitcoControl/Resources/PHP/DataBases/Conexion.php";
$query = "SELECT * FROM ct_cliente";
$stmt = $conn->prepare($query);
//$stmt->bind_param('s', $txt);
$stmt->execute();
$resultados = $stmt->get_result();
$num_rows = $stmt->num_rows;
if (false) {
$data['code'] = 2;
//$data['response'] = $num_rows;
} else {
$data['code'] = 1;
$data['system'] = $conn;
while ($a = mysqli_fetch_assoc($resultados)) {
$idCliente = $a['pk_cliente'];
$nc = $a['nombreCliente'];
$data['response'] .= "<p client-id='$idCliente'>$nc</p>";
}
}
$json = json_encode($data);
echo $json;
Ideas?
I have trouble to edit data in my database (MySQL).
I try to edit data with Flash (.swf)
Here is the flow of my program
Data -> Edit data with flash -> Data updated
My PHP script
<?php
mysql_pconnect ("localhost", "root", "");
mysql_select_db ("adaptasi");
$qResult = mysql_query ('UPDATE materi
SET isi = "????"
WHERE id = 1');
$rString ="";
echo "edit=".$rString;
?>
and my Actionscript for flash
var result:LoadVars = new LoadVars();
var edit:LoadVars = new LoadVars();
var filepath:String;
result.onLoad = function(success:Boolean) {
if (success) {
text_morfologi.text = result.result;
trace("success");
} else {
trace('error...');
}
};
filepath = "http://localhost/adaptasi/";
result.sendAndLoad(filepath + "morfologi.php", result, "GET");
btnedit.setStyle("fontSize", 22);
btnsave.setStyle("fontSize", 22);
btnedit.visible = true;
btnedit.onRelease = function() {
text_morfologi.type = "input";
btnedit.visible = false;
btnsave.visible = true;
}
btnsave.onRelease = function() {
edit.onLoad = function(success:Boolean){
if (success) {
text_morfologi.text = edit.edit;
trace("success");
} else {
trace('error...');
}
};
filepath = "http://localhost/adaptasi/";
edit.sendAndLoad(filepath + "editmorfologi.php", edit, "GET");
btnedit.visible = true;
btnsave.visible = false;
output.text = "data berhasil diubah...";
}
I can execute that script from flash. But I don't know what should I insert into SET in SQL Update...
I have created a code that allows you to search videos from the database. But everytime I write the video I want to search, in console, error appears... I really dont know why it doesnt print the result...
Could you help me?
I need help real fast
AJAX
$(document).ready(function($) {
var Search = function(title){ return $.post( "./include/php/busqueda_videos.php", { "title" : title }); }
$("#input_search").on('keyup', function(event) {
var output = "";
$(".videos_container").html("");
event.preventDefault();
var input = $("#input_search").val();
Search(input).done(function(response) {
if(response.success) {
$.each(response.videos, function(key, value) { var output = "<div class='video_main_container'><div class='video_container'><div class='video_thumb'><a data-id='"+value['id']+"'><img src='"+value['image']+"' alt='' /></a></div><div class='video_info'><p class='title'>"+value['title']+"</p><p class='usuario'>"+value['user']+"</p></div></div></div>"; });
$(".videos_container").html(output);
} else {
console.log("Error");
}
}).fail(function(jqXHR, textStatus, errorThrown) { console.log("Hubo un error"); });
});
});
PHP
<?php
if(isset($_POST['title'])) {
get_infvideo($_POST['title']);
} else {
$message = sprintf("No valid");
header($_SERVER['SERVER_PROTOCOL'] . ' ' . $message, true, 403);
}
function get_infvideo($title) {
$dsn = "mysql:host=localhost;dbname=tapehd;charset=utf8";
$usuario = "root";
$contraseƱa = "";
$conexion = new PDO($dsn, $usuario, $contraseƱa);
$resultado = null;
$jsondata = array();
$videos = array();
$text ="";
if($title!="") {
$title= explode(" ", $title);
for($i=0; $i<count($title);$i++) {
if($text!="") {
$text .= " AND (title LIKE '%".$title[$i]."%' or user LIKE '%".$title[$i]."%')";
} else {
$text .= " (titulo LIKE '%".$titulo[$i]."%' or user LIKE '%".$title[$i]."%')";
}
}
}
if($conexion){
$sql = "SELECT * FROM video WHERE ".$text;
if($resultado = $conexion->query($sql)) {
while($fila = $resultado->fetch()) {
$fila['id'] = $fila['id'];
$fila['user'] = $fila['user'];
$fila['image'] = $fila['image'];
$jsondata['success'] = true;
array_push($videos, $fila);
$jsondata['videos'] = $videos;
}
} else {
$jsondata['success'] = false;
$jsondata['message'] = $sql;
}
}
header('Content-type: application/json; charset=utf-8');
echo json_encode($jsondata, JSON_FORCE_OBJECT);
}
exit();
?>
The idea is to print the video (with his id, image, user, title) that you have searched...
I am having an issue with my AJAX and MySQL/PHP script.
The first file below, is my javascript file I use to test accessing my server. This file works as far as I know and have tested.
Game = function() {};
var timer;
Game.EncodeURI = function (text) {
return encodeURIComponent(text);
}
Game.DecodeURI = function (text) {
return decodeURIComponent(text);
}
Game.AlterDiv = function(div,data) {
if (Game.ID(div)) {
Game.ID(div).innerHTML = data;
}
}
Game.ID = function(value) {
return document.getElementById(value);
}
Game.ServerRequest = function (url, data) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
data = xmlhttp.responseText.split("|");
for (i = 0; i < data.length; i++){
var one = Game.DecodeURI(data[parseInt(i)]);
var two = Game.DecodeURI(data[parseInt(i) + 1]);
var three = Game.DecodeURI(data[parseInt(i) + 2]);
var four = Game.DecodeURI(data[parseInt(i) + 3]);
var five = Game.DecodeURI(data[parseInt(i) + 4]);
}
} else {
return false;
}
}
if (!data) {
data = "";
}
data = data.replace(/: /gi, "=");
data = data.replace(/:/gi, "=");
data = data.replace(/, /gi, "&");
data = data.replace(/,/gi, "&");
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data);
}
Game.Action = function (id, seconds) {
clearTimeout(timer);
if (id) {
if (!seconds) {
Game.AlterDiv('message', 'You begin working.');
Game.ServerRequest("action.php", "id: " + id);
} else {
Game.AlterDiv('message', 'You begin working.');
Game.ID('timer').innerHTML = seconds;
if (seconds >= 2) {
seconds -= 1;
Game.ID('timer').innerHTML = seconds;
timer = setTimeout(function(){
Game.Action(id, seconds);
},1000);
} else {
Game.ID('timer').innerHTML = "Finished";
Game.ServerRequest("action.php", "id: " + id + ", x: x"); // Request it, then POST "x" to say timer has counted down.
}
}
} else {
alert("There was an error with your request.\n Please try again.");
}
}
This second file is a basic PHP web page that I use to test the said function.
<html>
<head>
<title>Test</title>
</head>
<body>
<span onClick="Game.Action('1','5');">Start Work</span><br /><br />
<div id="message"></div>
<div id="timer"></div>
</body>
</html>
<script type="text/javascript" src="game.js?<?php echo time(); ?>"></script><!-- the time() stops it cache-ing -->
This third file is my PHP/MYSQL file that I use to connect to the database.
<?php
$mysqli = new mysqli_connect("127.0.0.1", "root", "", "gurstang");
$id = $_POST['id'];
if(isset($_POST['x'])) {
$x = true;
}else{
$x = false;
}
$userid = 1;
$query = "SELECT * FROM `action_info` WHERE `actionid` = '$id'";
if($result = $mysqli->query($query)){
while ($row = $result->fetch_assoc()) {
$action_name = $row['name'];
$basetimer = $row['time'];
$gaineditem = $row['itemid'];
}
$result->free();
}
$query = "SELECT `item`,`plural` FROM `items` WHERE `itemid` = '$gaineditem' LIMIT 0,1";
if($result = $mysqli->query($query)){
while($row = $result->fetch_assoc()){
$gained_item = $row['item'];
$gained_plural = $row['plural'];
}
$result->free();
}
if($x == false){
echo "Action|$id|"5"";
$message = "You have begun working.";
echo "AlterDiv|message|$message";
}
if($x == true){
echo "Action|$id|"5"";
$itemnumber = mt_rand(1,2);
$gainedmessage = "You have gained $itemnumner $gained_item.";
echo "AlterDiv|message|$gainedmessage";
$query = "SELECT `count` FROM inventory WHERE userid = '$userid' AND itemid = '$gaineditem' LIMIT 0,1";
if($result = $mysqli->query($query)){
while($row = $result->fetch_assoc()){
$count = $row['count'];
$add = $count + $itemnumber;
$updatequery = "UPDATE `inventory` SET `count` = '$add' WHERE `userid` = '$userid' AND `itemid` = '$gaineditem'";
$mysqli->query($updatequery);
}
}
else{
$insertquery = "INSERT INTO `inventory` (`userid`, `itemid` ,`count`) VALUES ('$userid', '$gaineditem', '1')";
$mysqli->query($insertquery);
}
}
?>
Those are all 3 of the file currently to run my script. I have an onclick event in the php webpage, and it sends the values to my Javascript function of Game.Action. After testing I have concluded or at least assume that my Javascript function for Game.Action works. After testing my Game.ServerRequest function, I have concluded that there is a change somewhere happening. Although, when I check my server to see if the updates actually happened, nothing happens. It doesn't update the timer div or the message div properly.
So basically my question is, is my issue with PHP/MYSQL or AJAX?
Thanks for your help.
I have a problem with a website which I never had before on other sites, it's probably something simple, but can't seem to get it. Please see and advise.
<!--All Header Elements-->
<?php
$pageName = "Easy-Quote";
$siteName = "Bloemendal";
include("../Includes/header_non_index.inc");
include("../Includes/function12.inc");
?> <?php error_reporting (E_ALL ^ E_NOTICE); ?>
<!--All Header Elements-->
<body>
<script type="text/javascript">
var total = 0;
var allVenues = "";
var allVenuePricing = "";
var allTents = "";
var allTentPricing = "";
var allDFPricing = "";
var allMenus = "";
var allMenuPricing = "";
var allSF = "";
var venueName = "";
var venuePrice = 0;
var tentName = "";
var tentPrice = 0;
var DF = "";
var DFPrice = 0;
var menuName = "";
var menuPrice = 0;
var serviceFee = 0;
var getGuests = null;
var totalField = null;
var venueField = null;
var tentField = null;
var DFField = null;
var menuField = null;
//Get Fields
function getFields()
{
getGuests = document.getElementById('Guests');
totalField = document.getElementById('TotalField');
depositField = document.getElementById('DepositField');
venueField = document.getElementById('getValue');
tentField = document.getElementById('getTent');
DFField = document.getElementById('getDF');
menuField = document.getElementById('getMenu');
serviceField = document.getElementById('getServiceCharge');
}
function convertAllArrays()
{
<?php
$allVenues=getVenues();
$allVenuePricing=getVenuePricing();
$allTents=getTents();
$allTentPricing=getTentPricing();
$allDFPricing=getDFPricing();
$allMenus=getMenus();
$allMenuPricing=getMenuPricing();
$allSF=getServiceFee();
//##################Declaring All Arrays###########################\\
echo "allVenues = ". json_encode($allVenues) . ";\n"; //All the Venue Names
echo "allVenuePricing = ". json_encode($allVenuePricing) . ";\n"; //All the Venue Pricing
echo "allTents = ". json_encode($allTents) . ";\n"; //All the Tent Names
echo "allTentPricing = ". json_encode($allTentPricing) . ";\n"; //All the Tent Pricing
echo "allDFPricing = ". json_encode($allDFPricing) . ";\n"; //All the Dance Floors
echo "allMenus = ". json_encode($allMenus) . ";\n"; //All the Menu Names
echo "allMenuPricing = ". json_encode($allMenuPricing) . ";\n"; //All the Menu Pricing
echo "allSF = ". json_encode($allSF) . ";\n"; //All the Service Fees
?>
}
function activeControl()
{
//Check Venue Field
if(getGuests.value > 0)
{
venueField.disabled = false;
}else{
venueField.options[0].selected = true;
venuePrice = 0;
venueName = "";
venueField.disabled = true;
}
//Check Tent Field
if(venueField.selectedIndex == 1)
{
tentField.disabled = false;
}else{
tentPrice = 0;
tentName = "";
tentField.options[1].selected = true;
tentField.disabled = true;
}
//Check Menu Field
if(venueField.selectedIndex > 0)
{
menuField.disabled = false;
}else{
menuPrice = 0;
menuName = "";
menuField.options[0].selected = true;
menuField.disabled = true;
}
//Check Dance Floor Field
if(venueField.selectedIndex == 1)
{
DFField.disabled = false;
}else{
DFField.checked = false;
DF = "No";
DFPrice = 0;
DFField.disabled = true;
}
updateTotal();
}
function updateTotal()
{
//Get Venue Details
var getSelectedVenue = venueField.selectedIndex;
if(getSelectedVenue > 0)
{
venueName = allVenues[getSelectedVenue];
venuePrice = allVenuePricing[getSelectedVenue]
}
//Get Tent Details
var getSelectedTent = tentField.selectedIndex;
if(getSelectedTent > 1)
{
tentName = allTents[getSelectedTent-1];
tentPrice = allTentPricing[getSelectedTent-1]
}else if(getSelectedTent == 1)
{
tentName = "";
tentPrice = 0;
}
//Get DF Details
if(DFField.checked)
{
DF = "Yes";
DFPrice = allDFPricing[1];
}else
{
DF = "No";
DFPrice = 0;
}
//Get Menu Details
var getSelectedMenu = menuField.selectedIndex;
if(getSelectedMenu > 0)
{
menuName = allMenus[getSelectedMenu];
menuPrice = allMenuPricing[getSelectedMenu]
}
//Get Service Fee Details
var getSelectedSF =serviceField.selectedIndex;
if(getSelectedSF > 0)
{
serviceFee = allSF[getSelectedSF];
}
venuePrice = parseFloat(venuePrice,10);
tentPrice = parseFloat(tentPrice,10);
DFPrice = parseFloat(DFPrice,10);
menuPrice = parseFloat(menuPrice,10);
serviceFee = parseFloat(serviceFee,10);
//Update Total Field
total = venuePrice + tentPrice +DFPrice + (menuPrice*getGuests.value);
total = total + (total*serviceFee);
totalField.value = "R"+total;
//Update Deposit Fee
depositField.value = "R"+(total*0.3);
}
</script>
<!--Global Elements-->
That is the first 196 lines of the site. Offline it loads, but when uploaded to the webserver, it only uploads up to:
function convertAllArrays()
{
PS: I know that calling php variables in javascript is not ideal, but it should suffice for my purpose.
!!EDIT!!
Website Link: http://bloemendal.co.za/Easy-Quote/
!!EDIT!!
The first few line of code in the function12.inc include. the getVenues() etc functions are declared in this include:
<?php
//############################Venues###############################\\
function getVenues()
{
include("../Includes/db_bloem_01_logon.inc");
$cxn = mysqli_connect($host,$user,$passwd,$dbname);
$query = "SELECT VenueName FROM venues WHERE ID < 5";
$results = mysqli_query($cxn, $query) or die ("Could't execute query");
$allVenues= array();
$counter = 1;
while($row = mysqli_fetch_assoc($results))
{
extract ($row);
$allVenues[$counter] = "$VenueName";
$counter++;
}
return $allVenues;
}
function getVenuePricing()
{
include("../Includes/db_bloem_01_logon.inc");
$cxn = mysqli_connect($host,$user,$passwd,$dbname);
$query = "SELECT Price FROM venues WHERE ID < 5";
$results = mysqli_query($cxn, $query) or die ("Could't execute query");
$allVenuePricing= array();
$counter = 1;
while($row = mysqli_fetch_assoc($results))
{
extract ($row);
$allVenuePricing[$counter] = "$Price";
$counter++;
}
return $allVenuePricing;
}
When you have php in a script and the php throws an error the error prints in the script tag, so it's not going to show up on your browser. Chances are there's a problem with the php inside your javascript. Move the php outside the script tag to make sure that it runs without error.
your code
$allVenues=getVenues();
you can't assing a value to a php variable as a return of a JavaScript function
When the PHP interpreter read your code and build up the web page to be served take the value of $allVenues and put it into the page. Let say that variable is null: your line of code, served to the browser will be
null=getVenues();
the function
mysqli_fetch_assoc
doesn't exists (as far as I know)
there is a
mysql_fetch_assoc
no my-sql-improved
(but is deprecated)