I want to update database with flash (text input)
Here is my php code
<?php
mysql_pconnect ("localhost", "root", "");
mysql_select_db ("adaptasi");
$isi = isset($_POST['OutData']);
$query2 = "UPDATE materi SET isi='$isi' WHERE id = 1";
$result2=mysql_query($query2) or die("Query Failed : ".mysql_error());
?>
Here is my Actionscript 2
function SubmitData()
{
trace("Sending");
var OutData = new LoadVars();
text_morfologi.text = OutData.OutData;
filepath = "http://localhost/adaptasi/";
OutData.sendAndLoad(filepath + "editmorfologi.php", OutData, "POST");
}
btnsave.onRelease = function()
{
SubmitData();
btnedit.visible = true;
btnsave.visible = false;
};
But the result isi in database is '1' not the text that I input in the text field.
Thanks
You have some problems in your code :
ActionScript 2 :
To send data using a LoadVars object you have to attache it to that object as its properties, and if you want to receive a response from your server side script, you can use LoadVars.sendAndLoad() but if you want just to send that data without waiting for any response, you can use LoadVars.send().
Supposed that you will use sendAndLoad() function, so you code can be like this :
var url:String = 'http://www.example.com/update.php';
// the LoadVars object that will receive (load) a response from the server
var receiver:LoadVars = new LoadVars();
receiver.onLoad = function(success:Boolean)
{
if (success) {
trace(receiver.response); // gives for example : update successful
} else {
trace('error');
}
}
// the LoadVars object which will send (post) some data to the server
var sender:LoadVars = new LoadVars();
sender.id = txt_id.text;
sender.name = txt_name.text;
sender.sendAndLoad(url, receiver); // we don't set the method to POST because that's its default value
PHP :
As mentioned in many comments, the PHP's isset() function is used to verify if a variable is set and is not NULL and it returns a boolean value ( TRUE of FALSE ) which is when it's casting (converting) to a string will give you 1 for TRUE and `` (empty string) for FALSE.
In your case, and according to you, I think that as the the variable $_POST['OutData'] is apparently set, isset($_POST['OutData']) is true which will set the value of $isi to 1, so you will get :
$query2 = "UPDATE materi SET isi='1' WHERE id = 1";
but according to your posted code, I think that you should get :
$query2 = "UPDATE materi SET isi='' WHERE id = 1";
Returning now to our current example, we will get our two POST variables (id, and name) sent by the AS2 script to update the DB and then return a response if the data has been successfully updated or not :
<?php
if(isset($_POST['id'] && isset($_POST['name']))
{
$id = $_POST['id'];
$name = $_POST['name'];
mysql_pconnect('localhost', 'root', '');
mysql_select_db('my_db');
$query = "UPDATE users SET name = '$name' WHERE id = $id";
$result = mysql_query($query);
if($result){
echo 'response=update successful';
} else {
echo 'response=update failed';
}
}
?>
Of course here I tried just to give you a very simple example of a working code according to your current one. You should know that for your PHP side that the "mysql" extension was deprecated in PHP 5.5.0 and was removed in PHP 7, so you should think to use "mysqli" or "PDO" extensions, for more about that, take a look here, also don't forget to sanitize, validate and escape any user's data, ... and for the ActionScript side, maybe it's the time to start learning ActionScript 3 ...
Hope that can help.
Related
I've been starting to program in PHP, and I want to create a program that allows any visitor to click a button and have it increment a universal counter. Eg, a user clicks the button, the counter increments by 1, and you can refresh the page and that new number will have "stuck".
My thought was to use a database that would hold the current number of "clicks" and display it, then use a client-side JavaScript button to increment the database's value. I am able to access my database and get the current number of clicks held there statically, but I'm at a loss as to having the counter be interactional. I've tried googling around to see how to do this in JavaScript, and the results have been minimal. Are my goals even achievable in JavaScript? Or should I use a different language to connect my server-side ops with my client-side ones?
// connects to the database using hostname, user, pass, db name
$connect = mysqli_connect('HOSTNAME','USER','PASSWORD','epiz_33276135_ducks');
if (!$connect) {
echo 'problem connecting to database';
}
//takes the query
$query = "SELECT Count,ID,AnimalName FROM ducks WHERE ID=1";
//connects result adn records it
$result = mysqli_query( $connect, $query);
$record = mysqli_fetch_assoc( $result);
if (!$result) {
echo 'smthin weird';
}
echo '<h2>'.$record['Count'].'</h2>';
From my understanding, PHP is for server-side operations, and Javascript is for client-side work. Googling hasn't generated any answers, and I haven't been able to find a way that can edit hte
Typically, you'd have your client-side code make a request to a PHP script that increments the count and responds with the new value. You can either use a form which results in a full page load or use an asynchronous request for a more seamless experience.
On the front-end, you'd use something like this
<button id="increment-counter" type="button">Increment Counter</button>
// Add a "click" event listener to the button
document
.getElementById("increment-counter")
.addEventListener("click", async () => {
// Make a PUT request to your PHP
// The `method` probably isn't important but a GET request seemed wrong
const res = await fetch("increment-counter.php", { method: "PUT" });
// Check for any errors
if (!res.ok) {
throw new Error(
`Increment counter failed: ${res.statusText} - ${await res.text()}`
);
}
// now update the current count in-place
document.querySelector("h2").textContent = (await res.json()).Count;
});
On the server-side, something like this (and I'm using PDO because it's more beginner-friendly than MySQLi)
// increment-counter.php
if ($_SERVER['REQUEST_METHOD'] !== 'PUT') {
// Only allow PUT requests
http_response_code(405);
exit;
}
// Connect to your DB
$pdo = new \PDO(
'mysql:host=HOSTNAME;dbname=epiz_33276135_ducks',
'USER',
'PASSWORD',
[
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
]
);
$pdo->beginTransaction(); // atomic updates are important
try {
// Select the current Count
$count = $pdo
->query('SELECT `Count` FROM ducks WHERE ID = 1 FOR UPDATE')
->fetchColumn();
// Update your Count column
$pdo->exec('UPDATE ducks SET `Count` = `Count` + 1 WHERE ID = 1');
$pdo->commit();
// Respond with a JSON object containing the updated count
header('content-type: application/json');
echo json_encode(['Count' => $count + 1]);
exit;
} catch ($err) {
$pdo->rollBack();
throw $err;
}
Learn one language at a time. PHP in this context writes HTML so you simply need to implement a page transition - i.e. fetch new html from the server....
<?php
$connect = mysqli_connect('HOSTNAME','USER','PASSWORD','epiz_33276135_ducks');
if (!$connect) {
echo 'problem connecting to database';
}
//takes the query
$query = "SELECT Count,ID,AnimalName FROM ducks WHERE ID=1";
//connects result adn records it
$result = mysqli_query( $connect, $query);
$record = mysqli_fetch_assoc( $result);
if ($result) {
$query="UPDATE ducks SET `Count`=`Count`+1";
mysqli_query( $connect, $query);
} else {
echo 'smthin weird: ' mysqli_error($result);
}
echo "<h2>$record[Count]</h2>";
echo "<a href='$_SERVER[REQUEST_URI]'>next</a>";
Once you've got this working, have a look at HTML forms.
BTW its bad practice to use reserved words (Count) for attribute names.
I was wondering how to construct the correct syntax for the if-else statement, or if there's something missing in my code.
<?php
include "../dbcon.php";
session_start();
ob_start();
$sql = mysqli_query($con,"SELECT * FROM clientdocuments WHERE docID = $_POST[docID]");
$rows = mysqli_fetch_array($sql, MYSQLI_ASSOC);
//IF CSS input value is filled
if(!empty($_POST)){
$output = '';
$message = '';
$docID = mysqli_real_escape_string($con, $_POST["docID"]);
$docSIG_Contract = mysqli_real_escape_string($con, $_POST["docSIG_Contract"]);
//I don't get what this "if(isset($_POST["docID"])){" purpose (Sorry very new to php)
if(isset($_POST["docID"])){
if (!empty($docID)) {
$query = "UPDATE clientdocuments(docID, docSIG_Contract) VALUES('$docID', '$docSIG_Contract');"; //UPDATE ONCE docID ALREADY EXIST ON THE DATABASE
} else {
$query = "INSERT INTO clientdocuments(docID, docSIG_Contract) VALUES('$docID', '$docSIG_Contract');"; //INSERT IF THE docID doesn't exist yet
}
$str = mysqli_query($con,$query);
if(!$str){
echo 'FAILED';
}
}else{
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
}
}
?>
remove this if statment: if (!empty($docID)) {
Make sure that u send with each post update the "docID" value
if(isset($_POST["docID"])) statement checks to see whether the input with the name docID has a value.
if(!empty($_POST)) I am not sure whether this will work, my guess is that you are trying to check whether the request method is POST (if the save button was clicked). For this I use
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
I would then check to see whether docID has a value ie
(isset($_POST["docID"])) OR (!empty($_POST["docID"]))
Difference between isset and !empty
What's the difference between 'isset()' and '!empty()' in PHP?
If there is a value, $query would be the update statement
If there is no value $query would be the insert statement In this situation don't enter the DocID value (because then it would always be 0 which will also cause errors)
Hope that makes sense!
I am trying to send two variables from an HTML page to a PHP script but the response keeps coming back as text/html. aka, the entire code in the PHP file is being returned to the console.
My jQuery code:
$.get( //call the server
"biography_query.php", //At this url
{
field: "value",
id: decodeURIComponent(id),
name: decodeURIComponent(name)
} //And send this data to it
).done( //And when it's done
function(data)
{
console.log(data);
},"jsonp"
);
PHP code:
header('Content-Type: application/json');
//start session on server to store the users information
session_start();
// establish connection to SQL database
$con = mysqli_connect("localhost","root","","capstone") or die("Error: " . mysqli_error($con));
$id = $_REQUEST['id'];
$name = $_REQUEST['name'];
// build statement to query database and return all characters
$SQL = "SELECT real_name, alternate_identities, aliases, nicknames, place_of_birth, first_appearance FROM `character` WHERE id='$id' AND superhero_name='$name'";
// execute the statement
$sqlReturn = mysqli_query($con, $SQL);
$row = array();
while($r = mysqli_fetch_assoc($sqlReturn)) {
$row['real_name'] = $r['real_name'];
$row['alternate_identities'] = $r['alternate_identities'];
$row['aliases'] = $r['aliases'];
$row['nicknames'] = $r['nicknames'];
$row['place_of_birth'] = $r['place_of_birth'];
$row['first_appearance'] = $r['first_appearance'];
}
echo json_encode($row);
"I am using <? tags"
As per OP's wishes: (to close the question, and for future readers)
If short open tags are not enabled, you will need to either enable them, or change <? to <?php.
Here are a few articles on the subject, on Stack:
How to enable PHP short tags?
Enable PHP short open tags via .htaccess
On PHP.net:
http://php.net/manual/en/ini.core.php
Sorry for the confusing title, wasn't exactly sure how to word it. I've been following a tutorial for an interactive dynamic flash Actionscript 3.0 game which communicates with php and MySQL to remember certain information about each user. It first sends a request tot he php file getsessionvars.php , which returns values that can be used by the flash game to retireve user information. Basically here is all of the important code, starting from the actionscript:
stop();
// Assign a variable name for our URLVariables object
var variables:URLVariables = new URLVariables();
// Build the varSend variable
// Be sure you place the proper location reference to your PHP config file here
var varSend:URLRequest = new URLRequest("getsessionvars.php");
varSend.method = URLRequestMethod.POST;
varSend.data = variables;
// Build the varLoader variable
var varLoader:URLLoader = new URLLoader;
varLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
varLoader.addEventListener(Event.COMPLETE, completeHandler);
variables.myRequest = "bringit";
// Send the data to the php file
varLoader.load(varSend);
// When the data comes back from PHP we access it here
function completeHandler(event:Event):void{
var idVar = event.target.data.id_var;
var userNameVar = event.target.data.uname_var;
var passVar = event.target.data.upass_var;
var resultStatus = event.target.data.my_result;
var coordX=event.target.data.coordx;
var coordY=event.target.data.coordy;
if (resultStatus == "no_session"){
gotoAndStop("no_session");
} else if (resultStatus == "no_exist"){
gotoAndStop("no_exist");
} else if (resultStatus == "all_good"){
userid_txt.text = idVar;
username_txt.text = userNameVar;
password_txt.text = passVar;
gotoAndStop(5);
var other:otherPeople = new otherPeople();
addChild(other);
other.x=coordX;
other.y=coordY;
}
}
Then to getsessionvars.php:
<?php
session_start();
include_once("php_includes/check_login_status.php");
$id = ""; // Initialize $id var
$username = ""; // Initialize $username var
$password = ""; // Initialize $password var
if (isset($_POST['myRequest']) && $_POST['myRequest'] == "bringit"){
$id = preg_replace('#[^0-9]#i', '', $log_id);
$username = preg_replace('#[^a-z0-9]#i', '', $log_username);
$password = preg_replace('#[^a-z0-9]#i', '', $log_password);
// Check database to see if the id is related to this password
include_once("connect.php");
mysql_query("INSERT INTO online ('id','player','xpos','ypos') VALUES('','{$username}','10','30')");
$sql = mysql_query("SELECT * FROM users WHERE id='$id' AND username='$username' LIMIT 1");
$numrows = mysql_num_rows($sql);
$sqla=mysql_query("SELECT * FROM online");
echo "my_result=all_good&id_var=$id&uname_var=$username&upass_var=$password&coordx=30&coordy=50";
}// close inital if condition
?>
My question is: How can i make it so that multiple users can appear on the screen at the same time? As you can notice, I've already attempted to try to store the coordinates of the player when they first log in into a MySQL Database and then was hoping to update that information every time the character moves, but I was wondering if there's a more efficient way of doing this?
Unless your game is slow and turn based, you're heading down the wrong path altogether.
What you need for simultaneous multiplayer games is a socket server, like SmartFox server or ElectroTank Server.
They guys at electro tank put together a very very good book on the topic:
http://www.amazon.com/ActionScript-Multiplayer-Games-Virtual-Worlds/dp/0321643364
You should get the book and give it a read. It covers setting up a server and how to make your flash implementations work well with the server driving the updates.
NOTE: UPDATE - Please Read
Please Read, updated code, much better:
Also, I added an ajax error function and it doesn't call an error, the first time I do it, but the next time it happens, an error occurs, and the third and fourth times, and so on.
I have some code that doesn't seem to be working, and the problem is probably located in the Ajax request or the PHP receiving function, and I don't know what the problem could be.
Here is the important code, ask for any other code that could also be of help to you.
Jquery Ajax request
$(document).ready(function()
{
$("#secretcoin").mouseover(function()
{
$.ajax(
{
type: "POST",
url: "achievements.php",
data: { Home_Coin_Locator: "Yes" },
error: errorAlert
});
});
});
Receiving side, PHP, which takes this info and stores it in a database:
$achieve4 = $_POST["Home_Coin_Locator"];
$astrSQL = "SELECT * FROM Awards_Inv WHERE Username = '$username'";
$rs3 = mysql_query($astrSQL, $connection);
if ($achieve4 == "Yes")
{
while($row3 = mysql_fetch_array($rs3)){
$soar4 = $row3["Home_Coin_Locator"];
if ($soar4 == "Yes")
{
$soa4 = "Yes";
}
else
{
$soa4 = "No";
$awardSTRsql = "UPDATE Awards_Inv SET 'Home_Coin_Locator' = 'Yes' WHERE Username = '$username'";
mysql_query($awardSTRsql, $connection) or die(mysql_error());
$updatestatsSTRsql = "UPDATE User_Info SET `Coins` = Coins + 120, `Skill Points` = Skill Points + 10, `Awards` = Awards + 1 WHERE Username = '$username'";
mysql_query($updatestatsSTRsql, $connection) or die(mysql_error());
}
}
}
else
{
}
Ok, so my code might be weird, but just try to read it and see what the problem is.
I guess any other advice is also accepted, thanks for looking, and I hope you find something!
I added an error callback function and combined 3 mysql queries into 1, but the problem still exists.
Finally, read this code for info about the $connection and $username variables
$connection = mysql_connect("mysql1.000webhost.com", "username hidden", "password hidden") or die (mysql_error ());
mysql_select_db("a7347456_usersdb") or die(mysql_error());
session_start();
$username = $_SESSION["Username"];
Another factoid:
The error is that the info does not get updated to database, as far as I know.
first thing, make sure that you required the config file witch identify the $connection variable. and it will be easier if you describe what the problem exactly is.