Want to send in State, City, County variables from Flash to PHP page:
function retrieve() {
var scriptRequest:URLRequest = new URLRequest("http://localhost:8080/GSM/KJVold.php");
var scriptLoader:URLLoader = new URLLoader();
var scriptVars:URLVariables = new URLVariables();
scriptLoader.addEventListener(Event.COMPLETE, handleLoadSuccessful);
scriptLoader.addEventListener(IOErrorEvent.IO_ERROR, handleLoadError);
scriptVars.State = this.whichState;
scriptVars.City = this.whichCity;
scriptVars.County = this.whichCounty;
scriptRequest.method = URLRequestMethod.POST;
scriptRequest.data = scriptVars;
scriptLoader.load(scriptRequest);
function handleLoadSuccessful($evt:Event):void
{
MovieClip(parent).info_txt.text = scriptRequest;
}
My PHP page reads:
//connection to database stuff
$result = mysql_query("SELECT info FROM kjvold WHERE State='$State' AND City='$City' AND
County='$County'");
while($row = mysql_fetch_array($result))
{
print "info = " . $row['info'];
}
When I trace actionscipt variables I see named pairs going to page. When I hard code PHP page I can see the right output, but when trying to use variables to PHP in the text box I get object URLRequest not the County info I'm seeking. It sure would help if someone can help me with this. Thanks in advance, Annie.
I've never used ActionScript before but in your PHP script instead of
$County
$State
$City
I'm quite sure you need to use
$_POST["County"]
$_POST["State"]
$_POST["City"]
Also it might be an idea to escape your SQL query from injections or other invalid inputs by wrapping the variable in a mysql_real_escape_string() function
Ie:
$_POST["County"]
Becomes:
mysql_real_escape_string($_POST["County"])
Related
I integrated a PHP file in my Wordpress installation with a plugin. I have found out, how I am able to send several variables and posting them to a MySQL database, but I am confused, how to manipulate my data like this:
$web = "http://internal.weddingcenter.at/wp-content/themes/twentytwelve/orders.php";
a href="<? echo ''.$web.'?contact='.$daten[id].'' ?>">Rechnung</a>
if ($contact) {
$datum = date('Y-m-d', $date);
$sql_update = "Update wccrm_orders set contacted_date = $datum where id = $contact";
$result = mysql_query($sql_update, $db);
}
I never jump into the if-clause.
How can this be solved?
It has to be :
if($_GET['contact'])
...
OR You cant try :
$contact = $_GET['contact'];
if($_GET['contact'])
...
To add to Kunal Gupta I can see more problems...
if ($_GET['contact']) {
//Forgot to mention SQL injection prevention...
//Try preg_replace or mysqli_real_escape_string()
$datum = preg_replace('[0-9 \/]', '', date('Y-m-d',$date)); //I think that will work
//OR
$test = date('Y-m-d', $date);
$datum = mysqli_real_escape_string($test); //Should also work...
//You must always place PHP variables in inverted commas
$sql_update = "UPDATE wccrm_orders SET contacted_date='$datum' WHERE id='$contact'";
//use MySQLi... It's quicker. Use the variables this way around
$result = mysqli_query($db, $sql_update);
}
There are still quite a few problems with the code but without fully understanding what data is coming from the previous page or what you intend to do with the data I can only help so much.
Here is my problem
I looked through Stak overflow and other websites but can't find an answer that solves my actual problem...
I call a php file from an AJAX request, my php file gets data from my db.
I'm making a pdo statement to get data from my db :
//initialize vars such as $db ...
$get = $db->prepare("SELECT * FROM myTable WHERE myTable_id=1");
$get->execute();
echo json_encode($get->fetchAll(PDO::FETCH_ASSOC));
//COLUMNS IN MY TABLE ARE ID, NAME, PHONE, INFO
so that object is returned to my ajax query
BUT I don't know how to fetch this object into my ajax/jquery statement to use its data...
Response from console :
[Object{id="1",name="myname",phone="8888888",info="information"}]
code...
success : function(response){
var id = '';
var name = '';
var phone = '';
var info = '';
}
please tell me how to parse, i tried json.parse(response), but can't display any data from this...
thanx
Do it like this
success : function(response){
var data = JSON.parse(response);
var id = data.id;
var name = data.name;
var phone = data.phone;
var info = data.info;
}
That should do the trick.
I am getting an error when trying to pass a variable from AJAX to PHP for a MySQL query. I have tried hardcoding to make sure that the query works and it does, but when I try to dynamically pass the variable it is telling me the following "Error: Unknown column '$searchid' in 'where clause'". I am trying to send the value of a dropdown box to ajax to pull back data from a MySQL database. The returned data will then be put into 2 text boxes to be edited. Note: I am trying not to use the jQuery framework for this so I can get a better understanding of what the AJAX is actually doing.
AJAX code
function ajax_post(){
var request = new XMLHttpRequest();
var id = document.getElementById("editorginfo").value;
request.open("POST", "parse.php", true);
request.setRequestHeader("Content-Type", "x-www-form-urlencoded");
request.onreadystatechange = function () {
if(request.readyState == 4 && request.status == 200) {
var return_data = request.responseText;
alert (return_data);
document.getElementById("orgeditname").value = return_data;
document.getElementById("orgeditphone").value = return_data;
}
}
request.send("id="+id);
}
PHP Parse code
<?php
include_once('../php_includes/db_connect.php');
$searchid = $_POST['id'];
$sql = 'SELECT * FROM orginfo WHERE id = $searchid';
$user_query = mysqli_query($db_connect, $sql) or die("Error: ".mysqli_error($db_connect));
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$orgid = $row["id"];
$orgname = $row["orgname"];
$orgphone = $row["orgphone"];
echo $orgname, $orgphone;
}
?>
It's been a while since I have had time to work with code so I believe everything I used is still relevant. Also I know I havent put any sanitizing in yet, I wanted to make sure I can get the function working first, and I am the only one with access currently.
Thanks in advance for any help.
To solve your immediate issue, you'll want to change this:
$sql = 'SELECT * FROM orginfo WHERE id = $searchid';
Into this:
$sql = "SELECT * FROM orginfo WHERE id = $searchid";
Since your string is in single quotes, it is literally passing the string '$searchid' into the query rather than the value of $searchid.
Hi guys I´m new at stackoverflow and also new at Jquery
Well hope I can make myself understandable. Here is what I want: I have made a query to my MySQL db, using a class with PHP
public function User($id) {
$this->connect_db_web($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='".$id."'");
while ($values = mysql_fetch_array($sql)) {
$arr[]=array(
'id'=>$values['idUsers'],
'name'=>$values['name'],
'name2'=>$values['name2'],
'lname'=>$values['lname'],
'lname2'=>$values['lname2'],
'email'=>$values['email'],
'phone'=>$values['phone'],
'address'=>$values['address'],
'bday'=>$values['bday'],
'password'=>$values['password']
);
}
echo '{"user":'.json_encode($arr).'}';
}
Then I have a php code where I call this function
$name = $user->User($id);
I think this works ok (if I´m wrong please help). Now what I´m really trying to do is getting the values from the JSON array into specific divs, example:
$.getJSON("user.php",function(data){
$.each(data.user, function(i,user){
name = user.name;
$(name).appendTo('#getname');
});
});
And inside my HML i Have a <p id="getname"></p>wich is the tag I want the value to be displayed
But no value is displayed, why?, what am I doing wrong?
Thanks for the help I apreciate it
Your JSON is malformed. You are appending a bunch of objects {.1.}{.2.}{.3.}. Instead, try {"users":[{.1.},{.2.},{.3.}]}.
In PHP you'll do something like this (note that I've changed the response type to JSON-P rather than JSON by adding a callback parameter):
public function User($id) {
$users = array();
$this->connect_db_web($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='".$id."'");
while ($values = mysql_fetch_array($sql)) {
$users[] = array(
'id'=>$values['idUsers'],
'name'=>$values['name']
// etc.
);
}
$obj['users'] = $users;
$callback = (empty($_GET["callback"])) ? 'callback' : $_GET["callback"];
echo $callback . '(' . json_encode($obj) . ');';
}
Then you'll be able to do:
$.getJSON("user.php?callback=",function(data){
$.each(data.users, function(i,user){
$('#getname').append(user.name);
});
});
probably safer to do like this:
echo json_encode(array("user" => $arr));
on the other end you would receive an object which, I would suggest iterating like this:
var k;
for (k in data.user){
$("#getname").append($("<span></span>").html(data.user[k].name));
}
Given that you are fetching information for one user only, following I would suggest
$id = (int) $_GET["id"]; // or wherever you get it from.
if ($r = $db->mysql_fetch_assoc()){
$response = array(
"name" => $r["name"];
);
echo json_encode($response);
} else {
echo json_encode(array("error" => "Could not get name for user " . $id));
}
Then, on front-end, all you need to do is:
if (typeof(data.name) != "undefined"){
$("#getname").html(data.name);
} else if (typeof(data.error) != "undefined"){
$("#getname").html(data.error); //or handle otherwise
}
You've misinterpreted your JSON structure. You're appending your DB rows to an array, and embedding that inside an object. If you'd do a console.log(user) inside your .getJSON call, you'd see you'll have to do:
user[0].name
instead. As well, your code assumes that the user ID exists, and returns data regardless of how many, or how few, rows there actually are in the result set. At minimum your JS code code should check users.length to see if there ARE are any rows to begin with. Beyond that, unless you're doing it in another section of code somewhere, that $id value is probably coming from the web page, which means your query is vulnerable to SQL injection attacks.
OK got it,
was a php code error and JSON structre as marc said, here I´m gonna post what finally I had
PHP Class
public function User() {
$users = array();
$this->connect($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='1'");
$values = mysql_fetch_array($sql);
$users[] = array(
'id'=>$values['id'],
'name'=>$values['name'],
'name2'=>$values['name2'],
'lname'=>$values['lname'],
...//rest of values
);
echo json_encode($users);
}
PHP module to get class
include"class.php";
$user = new Users();
$user->User();
Now how did I got the values using JQuery
$.getJSON('user.php', function(data){
$('wherever_you_want_to_point_at').text(data[0].name);
});
Hope it helps someone,
Thanks again guys, very very helpful
Take care you all
I am having some problem here. I am trying to develop a flash database manager for my company, and I already have the insert and "search" functions working okay. The problem comes up when trying to get the UPDATE working. Ill post both codes here:
PHP (UPDATED)
<?php
//connect to the local MySQL
$connect=mysql_connect("localhost", "****", "****");
//select your database
mysql_select_db("****");
//Variables
$ID=$_POST[IDPost];
$Nome=$_POST[Nome];
$Tipo=$_POST[Tipo];
$Empresa=$_POST[Empresa];
$Morada=$_POST[Morada];
$CodPostal=$_POST[CodPostal];
$Email=$_POST[Email];
$Contacto1=$_POST[Contacto1];
$Contacto2=$_POST[Contacto2];
$DataNascimento=$_POST[DataNascimento];
$Profissao=$_POST[Profissao];
$Notas1=$_POST[Notas1];
$Notas2=$_POST[Notas2];
//query the database
$query="
UPDATE
GestaoClientes
SET
Nome = '$Nome',
Tipo = '$Tipo',
Empresa = '$Empresa',
Morada = '$Morada',
CodPostal = '$CodPostal',
Email = '$Email',
Contacto1 = '$Contacto1',
Contacto2 = '$Contacto2',
DataNascimento = '$DataNascimento',
Profissao = '$Profissao',
Notas1 = '$Notas1',
Notas2 = '$Notas2'
WHERE
ID = '$ID'";
$result=mysql_query($query);
if (!mysql_query($query,$connect))
{
die('Error: ' . mysql_error());
echo "Result=NotOk";
}else{
echo "Result=Ok";
}
mysql_close($connect);
?>
Flash
public function editInfo(MouseEvent):void
{
var request:URLRequest = new URLRequest ("link.php");
request.method = URLRequestMethod.POST;
trace("called");
var variables:URLVariables = new URLVariables();
variables.IDPost = NField.text;
variables.Nome = NomeField.text;
variables.Email = NomeField.text;
variables.Morada = MoradaField.text;
variables.CodPostal = CodPostalField.text;
variables.Tipo = TipoField.text;
variables.Empresa = EmpresaField.text;
variables.Profissao = ProfissaoField.text
variables.DataNascimento = DataNascimentoField.text;
variables.Notas1 = Notas1Field.text;
variables.Notas2 = Notas2Field.text;
request.data = variables;
var loader:URLLoader = new URLLoader (request);
loader.addEventListener(Event.COMPLETE, onComplete);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(request);
function onComplete(e:Event):void
{
trace("ok");
}
}
When I try going to the php in the browser if just gives me the error:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Nome' = '', 'Tipo' = '', 'Empresa' = '', 'Morada' = '', 'CodPostal' = '', 'Emai' at line 4
This although is probably normal, since Im not passing any "POST" variables through the browser.
The flash doesent return any errors when trying this code, so I assume the connection itself is okay, but it doesent do the update either. Is there something wrong with this code? Thanks.
UPDATE: I now changed my code, and it does not show the syntax error, but still doesent update within the flash. Any ideias why? :/ thanks
You need to use backticks instead of single quotes for column names:
`Nome`
this is the reason for the syntax error. It is also possible to use no quotes at all.
Also, your code is vulnerable to SQL injection. Read up on the issue, it's essential for security.
To fix the vulnerability at hand, do the following on every variable:
$Nome = mysql_real_escape_string($_POST["Nome"]);
and then insert the escaped variable:
SET `Nome` = '$Nome',
I suggest you take a close look at escaping your external input! Inserting variables directly into your query exposes you to injection, which is an enormous security issue. (read this).
the problem you have is that you use single quotes around the field names, this is incorrect.
MySQL uses backticks ( ` ), but I do not recommend using those since they limit portability to other sql applications.
Remove the single quotes around the column names. Backticks (`) are allowed, single quotes (') are not.
I hope you realize that if your code really looks like above you have a massive security hole in your application, as anyone can execute arbitrary sql code.