I'm trying to update a flash movie quiz that records names and question answers - I did not write the original application. The quiz works, except that it replaces the name with null when recording data. All the other records work fine. I have deleted out the res2 - res12 just to shorten it up, they all work well.
Im using Flash Pro CS6
The code is in AS3
Thanks in advance for any light you can shed on this.
From Name input page of the quiz. participname is the text field input:
stop();
btn1.addEventListener(MouseEvent.MOUSE_UP,function():void {
var Name:String=participname.text.toString();
gotoAndPlay(3);
});
From the last page of the quiz
sendData();
function sendData(){
var messages:URLRequest = new URLRequest("./insertresult.php")
messages.method = URLRequestMethod.POST
var posts:URLVariables = new URLVariables()
posts.Name = Name
posts.DateCurrent = dtFormatted
posts.Res01 = res01
messages.data = posts
trace(posts);
var loader:URLLoader = new URLLoader()
loader.dataFormat = URLLoaderDataFormat.TEXT
// loader.addEventListener(Event.COMPLETE, dataOnLoad)
loader.load(messages)
trace(messages);
From the insertresult.php:
<?php
//Capture data from $_POST array
$name = $_POST['Name'];
$date = $_POST['DateCurrent'];
$res1 = $_POST['Res01'];
/* if(!$name ) {
echo "no input using default values <br>";
$name = 'deleteme';
}*/
$connect = mysql_connect("mydatabase");
mysql_select_db ("PAlogindatabase", $connect);
$result = mysql_query("INSERT into rhymeoddity1 (name,date,res1) values ('$name','$date','$res1')");
if($result) echo "writing=Ok&";
else echo "writing=Error";
?>
Can you check that the actionscript is actually reading and setting the Name properly before posting the data?
I sorted out the problem, i believe that this bit of the code was hiding away the var myname
stop();
btn1.addEventListener(MouseEvent.MOUSE_UP,function():void {
var myname:String=participname.text.toString();
gotoAndPlay(3);
}
);
i have replaced this with this and it is working fine now.
stop();
var myname:String = "";
btn1.addEventListener(MouseEvent.MOUSE_UP,function():void {
myname = participname.text;
gotoAndPlay(3);
}
);
If someone can explain what the difference is so i can understand
Related
I am currently working on some php code using redbeanphp that should store data into database tables using four different R::store functions, but only the first two work, and I don't know why the other two aren't working because I made no spelling mistakes and if I try to do it with R::storeAll it also only works for the first two objects.
My code:
require "rb.php";
R::setup('mysql:host=localhost;dbname=building_framework', 'root', '');
// Books table
$books1 = R::dispense('books');
$books1->title = "Wonders of the world";
$books1->author_id = "1";
$books1->publisher_id = "1";
$books2 = R::dispense('books');
$books2->title = "Math for dummy's";
$books2->author_id = "1";
$books2->publisher_id = "1";
// Author table
$author = R::dispense('author');
$author->id = "1";
$author->author = "Francesco Boccia";
// Publisher table
$publisher = R::dispense('publisher');
$publisher->id = "1";
$publisher->publisher = "Metro Books";
$store1 = R::store($books1);
$store2 = R::store($books2);
$store3 = R::store($author);
$store4 = R::store($publisher);
echo $store1;
echo $store2;
echo $store3;
echo $store4;
When I execute it, all the tables are getting made, but only in the books table, data is stored and not in the other two. Can someone please help me fixing this?
I know my mistake. I added an id for author and for publisher but the id gets added by redbean itself, so there was no need for that.
Im trying to populate the textboxes of a CRUD with the information obtained from a query. I use a stored procedure which already works.
I mainly want to give an ID, click search and populate the rest of the texboxes with the clients rest of information. The rest of the buttons already work so I think my problem is located in this section of code:
if(isset($_POST['btnBuscar']))
{
$opc = "buscar";
$idcliente = ($_POST['txtIdCliente']);
$nombre = ($_POST['txtNombre']);
$apaterno = ($_POST['txtApPat']);
$amaterno = ($_POST['txtApMat']);
$tel = ($_POST['txtTel']);
$email = ($_POST['txtEmail']);
$fecalta = ($_POST['txtFechaAlta']);
$query = "CALL sp_clientes('$opc',$idcliente,'$nombre','$apaterno','$amaterno',$tel,'$email','$fecalta')";
if(mysqli_query($con,$query)){
header("location:Clientes.php?searched=1");
this next part where I have doubts
($_POST['txtIdCliente']) = $reg['IdCliente'];
($_POST['txtNombre'])= $reg['Nombre'];
($_POST['txtApPat']) = $reg['APaterno'];
($_POST['txtApMat']) = $reg['ApMaterno'];
($_POST['txtTel']) = $reg['Telefono'];
($_POST['txtEmail']) = $reg['Email'];
($_POST['txtFechaAlta']) = $reg['FecAlta'];
}
Here is the example. you can achieve more by appending HTML in PHP
echo '<input type="text" style="background-color:blue" id="'.$_POST['txtNombre'].'" name="content'.$_POST['txtNombre'].'" value="'.$_POST['txtNombre'].'"></input>';
I am running a POST + json code to collect data from database, all results come with only one value (this is correct), however there is only one column which should show more than one value but shows only the first one. What I need to change in my code to get this list instead of the first row result?
I've run one MYSQL query linking three databases those share the same id PCRNo, the first two databases tPCR and tcomplement should only have one result and the third one should receive more results due to we can have more lines with the same id.
This is my JavaScript
<script>
$(document).ready(function(){
$('#table').on('click', '.fetch_data', function(){
var pcr_number = $(this).attr('id');
$.ajax({
url:'fetch.php',
method:'post',
data:{pcr_number:pcr_number},
dataType:"json",
success:function(data){
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
$('#description').val(data.Name);
$('#Comments').val(data.Comments);
$('#originator').val(data.Creator);
$('#change_type').val(data.Category);
$('#product_type').val(data.Product);
$('#req_dept').val(data.Department);
$('#flow').val(data.Flow_Start_Date);
$('#own').val(data.Owning_Site);
$('#impacted').val(data.Impacted_Site);
$('#approval').val(data.Meeting_Status);
$('#review').val(data.Review_Date);
$('#cat').val(data.Cat);
$('#cost').val(data.Cost);
$('#labor').val(data.Labour);
$('#volume').val(data.Volume);
$('#request').val(data.Request);
$('#justification').val(data.Justification);
$('#PCNlist').val(data.PCNNo);
$('#monitor').val(data.Monitor);
$('#env').val(data.Environment);
$('#trial').val(data.Trial);
$('#resp').val(data.Responsible);
$('#deadline').val(data.Deadline);
$('#dataModal').modal('show');
}
});
});
$(document).on('click', '#update', function(){
var pcr_number = document.getElementById("PCR").value;
var Comments= document.getElementById("Comments").value;
var approval= document.getElementById("approval").value;
var review= document.getElementById("review").value;
var cat= document.getElementById("cat").value;
var monitor= document.getElementById("monitor").value;
var env= document.getElementById("env").value;
var trial= document.getElementById("trial").value;
var resp= document.getElementById("resp").value;
var deadline= document.getElementById("deadline").value;
var PCC = document.getElementById("PCC").value;
$.ajax({
url:"edit.php",
method:"POST",
data:{pcr_number:pcr_number, Comments:Comments, PCC:PCC, approval:approval, review:review, cat:cat, monitor:monitor, env:env, trial:trial, resp:resp, deadline:deadline},
dataType:"text",
success:function(data)
{
alert('PCR Information Updated');
}
});
});
});
</script>
this is my fetch.php
<?php
$SelectedPCRNo = $_POST['pcr_number'];
if(isset($_POST['pcr_number']))
{
$output = '';
$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "change_management";
$dbConnected = #mysqli_connect($hostname, $username, $password);
$dbSelected = #mysqli_select_db($databaseName,$dbConnected);
$dbSuccess = true;
if ($dbConnected) {
if ($dbSelected) {
echo "DB connection FAILED<br /><br />";
$dbSuccess = false;
}
} else {
echo "MySQL connection FAILED<br /><br />";
$dbSuccess = false;
}
$sql = mysqli_query($dbConnected, "SELECT * FROM change_management.tPCR INNER JOIN change_management.tcomplement ON change_management.tPCR.PCRNo = change_management.tcomplement.PCRNo INNER JOIN change_management.tPCN ON change_management.tPCR.PCRNo = change_management.tPCN.PCRNo WHERE tPCR.PCRNo = '".$_POST['pcr_number']."'");
$row = mysqli_fetch_array($sql);
echo json_encode($row);
}
?>
I have no problems with the results and the table is filled OK, only the #PCNlist should be filled with the values of all rows it is related and now just is just coming one value, the first row only. Is there any way to bring the whole PCNlist only changing some code at the fetch.php?
If I understood you correctly, the table tPCN can contain multiple rows associated with each PCR number. And you want to fetch all these rows and return them in your JSON.
If you want to achieve that, but also make sure the other two tables only return one row, then I think simply you should remove the JOIN to tPCN in your first query, and then create a second query to fetch the tPCN rows specifically.
$output = [];
$stmt = $dbConnected->prepare("SELECT * FROM change_management.tPCR INNER JOIN change_management.tcomplement ON change_management.tPCR.PCRNo = change_management.tcomplement.PCRNo WHERE tPCR.PCRNo = ?");
$stmt->bind_param('s', $_POST['pcr_number']);
$stmt->execute();
$result = $stmt->get_result();
//select a single row from the result and assign it as the output variable
if ($row = $result->fetch_assoc()) {
$output = $row;
}
$stmt2 = $dbConnected->prepare("SELECT * FROM change_management.tPCN WHERE PCRNo = ?");
$stmt2->bind_param('s', $_POST['pcr_number']);
$stmt2->execute();
$result2 = $stmt2->get_result();
$output["tPCN"] = array(); //create a new property to put the tPCN rows in
//loop through all the tPCN rows and append them to the output
while ($row2 = $result2->fetch_assoc()) {
$output["tPCN"][] = $row2;
}
echo json_encode($output);
This will produce some JSON with this kind of structure:
{
"PCRNo": "ABC",
"CreationDate": "2019-08-07",
"Name": "A N Other",
//...and all your other properties, until the new one:
"tPCN": [
{
"SomeProperty": "SomeValue",
"SomeOtherProperty": "SomeOtherValue",
},
{
"SomeProperty": "SomeSecondValue",
"SomeOtherProperty": "SomeOtherSecondValue",
}
]
}
You will then need to amend your JavaScript code to be able to deal with the new structure. Since I don't know exactly which fields come from the tPCN table, I can't give you an example for that, but hopefully it's clear that you will need to loop through the array and output the same HTML for each entry you find.
N.B. As you can see I re-wrote the query code to use prepared statements and parameterised queries, so you can see how to write your code in a secure way in future.
P.S. You have a lot of code there in the "success" function just to set the values of individual fields. You might want to consider using a simple JS templating engine to make this less verbose and cumbersome, and generate the HTML you need with the values automatically added into it in the right place. But that's a separate issue, just for the maintainability of your code
I've added this code into my ajax function to bring only what I needed and it works + what #ADyson has posted.
var PCN = data.tPCN;
var i;
var PCNList = '';
for (i = 0; i < PCN.length; i++){
var PCNList = PCNList + PCN[i]['PCNNo'] + ' - ' + PCN[i]['Stage'];
}
$('#PCNlist').val(PCNList);
So I have implemented a google maps, using javascript to plot a polygon. I use getBounds to get the latLongs. Then I call a database (postcodes), which contains each lat long for each postcode in the UK.
This query looks like:
SELECT * FROM `postcode`.`postcodeGoogle` WHERE (`lat` BETWEEN '$lat1' AND '$lat2')
AND (`long` BETWEEN '$long1' AND '$long2')
Which is fine, returns the right data.
I then have a second database, address_list, which contains every address in the UK (at the moment it only contains Kettering area, so 12,000 rows). I do a while loop on the first query and then on each loop run this query:
SELECT * FROM `digital_hub`.`address_list` WHERE `postcode`='".$row['postcode']."'
Then I add the latlong of the postcode to a variable:
$resultE = $resultE."(".$row['lat'].", ".$row['long'].") || ";
This then gets echoed out at the end of the loops.
This page is called via jQuery:
$.get("php/properties.php?bounds="+bounds, function(data){
var theLatLongs = data.split(" || ");
totalcount = 0;
for(x in theLatLongs){
var theLatLong = "";
var latLong = theLatLongs[x].substr(1);
var latLong = latLong.slice(0, -1);
var theLatLong = latLong.split(", ");
var thelat = theLatLong[0];
var thelong = theLatLong[1];
totalcount = totalcount+1;
}
$('#totalcount').html('<h6><span>'+totalcount+'</span> Households found</h6>Filtered by location');
});
It all works fine (I think). It's just incredibly slow. I know facebook have much better resources, but there create advert filterer is amazingly quick. I will also be implementing further filters. I tried a join but the time difference didn't seem to massive. Sometimes it doesn't even return results at all and crashes my mysql service...
there are 3 sources that can slow the code: mysql, php, js.
the first thing I would do is run the sql (the join version), in a tool like toad or do a php file that outputs the raw result. You can add console.time/console.timeEnd to js, and mictrotime in php.
another "fast and dirty" check is to past "your_server"/php/properties.php?bounds=YourBounds,
and check the result. it will give you some indication.
If you are certain it's sql, try to index digital_hub.address_list.postcodes, postcode.postcodeGoogle.lat, and postcode.postcodeGoogle.long.
Then, in your php "raw" script (or your sql tool), try to call the query with less column,
or even with "select count(*)". If the "select count(*)" is way faster, that means that the returning value is slowing the system. This is typical of empty (non null) date fields by example.
But they key is simple, time the different parts of the process to isolate the bottleneck.
console.time('load');
$.get("php/properties.php?bounds="+bounds, function(data){
console.timeEnd('load');
console.time('parse');
var theLatLongs = data.split(" || ");
totalcount = 0;
for(x in theLatLong ){
var theLatLong = "";
var latLong = theLatLongs[x].substr(1);
var latLong = latLong.slice(0, -1);
var theLatLong = latLong.split(", ");
var thelat = theLatLong[0];
var thelong = theLatLong[1];
totalcount = totalcount+1;
}
console.timeEnd('parse');
console.time('display');
$('#totalcount').html('<h6><span>'+totalcount+'</span> Households found</h6>Filtered by location');
console.timeEnd('display');
});
on a side note, you might consider json data. (and review your use of thelatlong js var, but I guess you are debugging)
in php:
while ($row = msqlqresult) {
$resultArray[] = $row;
}
$resultJson = json_encode($resultArray);
in js:
console.time('load');
$.getJSON("php/properties.php", {bounds: bounds}, function(data){
console.timeEnd('load');
console.time('parse');
totalcount = 0;
for(var x in data){
var thelat = theLatLong[x].lat;
var thelong = theLatLong[x].long;
totalcount = totalcount+1;
}
console.timeEnd('parse');
console.time('display');
$('#totalcount').html('<h6><span>'+totalcount+'</span> Households found</h6>Filtered by location');
console.timeEnd('display');
});
I have a 3 step chained-select sequence, game -> battle -> winning side , which pulls all data from a MySQL database.
After some wandering on the internet, I found a compact jQuery script that performs wonderfully. However, I am at a loss as to how to allow for existing data: <option selected="selected"></option> using this script.
chained select javascript:
<script>
var ajax = new Array();
function getScenNumList(sel)
{
var game = sel.options[sel.selectedIndex].value;
document.getElementById('scenarioNumber').options.length = 0; // Empty scenario number select box
if(game.length>0){
var index = ajax.length;
ajax[index] = new sack();
ajax[index].requestFile = 'js/getPlayData.php?gameName='+game; // Specifying which file to get
ajax[index].onCompletion = function(){ createScenarioNumbers(index) }; // Specify function that will be executed after file has been found
ajax[index].runAJAX(); // Execute AJAX function
}
}
function createScenarioNumbers(index)
{
var obj = document.getElementById('scenarioNumber');
eval(ajax[index].response); // Executing the response from Ajax as Javascript code
}
function getNations(sel)
{
var scenNum = sel.options[sel.selectedIndex].value;
document.getElementById('victor').options.length = 0; // Empty nation select box
if(scenNum.length>0){
var index = ajax.length;
ajax[index] = new sack();
ajax[index].requestFile = 'js/getPlayData.php?scenID='+scenNum; // Specifying which file to get
ajax[index].onCompletion = function(){ createNations(index) }; // Specify function that will be executed after file has been found
ajax[index].runAJAX(); // Execute AJAX function
}
}
function createNations(index)
{
var obj = document.getElementById('victor');
eval(ajax[index].response); // Executing the response from Ajax as Javascript code
}
</script>
excerpt from the PHP database retrieval script (getPlayData.php):
$gameName = mysql_real_escape_string($_GET['gameName']);
$q = "SELECT a, b, c FROM table WHERE game='$gameName' ORDER BY num ASC";
$r = mysql_query($q);
echo "obj.options[obj.options.length] = new Option('#','');\n";
while ($row = mysql_fetch_row($r)) {
$string = mysql_real_escape_string(($row[0].' - '.$row[1])); // needed so quotes ' " don't break the javascript
echo "obj.options[obj.options.length] = new Option('$string','$row[2]');\n";
}
echoing the obj.options is the stock method this script was using. It seems ugly to me, but I don't know any javascript so I didn't want to fiddle with it.
The HTML is simple enough, just a table with a few empty <select> objects with IDs matching those in the javascript and onchange="getXXX(this)" calls.
My question is this: Everything works great for new records, but I'm at a loss as to how I can alter this to support marking one option from each select as selected, assuming I have that data in hand (ex: a user is editing an existing record) ?
Many thanks!
You can see this tutorial for creating an option that is selected as default. http://www.javascriptkit.com/javatutors/selectcontent.shtml One parameter in the option constructor dictate that whether the option is selected or not.
In the PHP file you will edit as follow:
$gameName = mysql_real_escape_string($_GET['gameName']);
$q = "SELECT a, b, c FROM table WHERE game='$gameName' ORDER BY num ASC";
$r = mysql_query($q);
echo "obj.options[obj.options.length] = new Option('#','');\n";
while ($row = mysql_fetch_row($r)) {
$string = mysql_real_escape_string(($row[0].' - '.$row[1])); // needed so quotes ' " don't break the javascript
if ($string ......)
echo "obj.options[obj.options.length] = new Option('$string','$row[2]', false, true);\n";
else
......
}