Can't update php database with a flash application - php

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.

Related

SQL UPDATE not working

I am trying to update some of the data in a database called customer. This is my code
<?php
Require("dbconnect.php");
$Customer_id = $_POST['Customer_id'];
$Customer_title = $_POST['Customer_title'];
$Customer_forename = $_POST['Customer_forename'];
$Customer_surname = $_POST['Customer_surname'];
$Customer_contact = $_POST['Customer_contact'];
?>
all the variables are holding the correct data as I have test echoed them.
No errors are recieved when I run this code however it is not updating the database either? Can anyone help? Thank in advance!
String constants need single quotes (forename and surname):
$sql = "UPDATE `a6123854_a220559`.`Customer`
SET Customer_forename = '".$Customer_forename."', Customer_surname = '".$Customer_surname."'
WHERE Customer_id = ".$Customer_id."";
Please note that your code may be susceptible to SQL injection.
There is one little thing that will quite possibly fix your problem. It is in the quotation.
$sql = "UPDATE `a6123854_a220559`.`Customer`
SET Customer_forename='".$Customer_forename."',
Customer_surname='".$Customer_surname."'
WHERE Customer_id='".$Customer_id."'";

SQL syntax error edit post

getting :
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 's Creed III', description='The plot is set in a fictional
history of real ' at line 2
when trying to edit posts on a database.
heres my display and edit php:
$result = mysql_query("SELECT * FROM gallery");
while ($row = mysql_fetch_array( $result )){
// while looping thru each record…
// output each field anyway you like
$title = $row['title'] ;
$description = $row['description'];
$year = $row['year'];
$rating = $row['rating'];
$genre = $row['genre'];
$filename = $row['filename'];
$imageid = $row['imageid'];
include '../modules/edit_display.html';
}
// STEP 2: IF Update button is pressed , THEN UPDATE DB with the changes posted
if(isset($_POST['submit'])){
$thisTitle = $_POST['title'];
$thisDescription = $_POST['description'];
$thisYear = $POST['year'];
$thisRating = $POST['rating'];
$thisGenre = $POST['genre'];
$thisNewFilename = basename($_FILES['file']['name']);
$thisOneToEdit = $_POST['imageid'];
$thisfilename = $_POST['filename'];
if ($thisNewFilename == ""){
$thisNewFilename = $thisfilename ;
} else {
uploadImage();
createThumb($thisNewFilename , 120, "../uploads/thumbs120/");
}
$sql = "UPDATE gallery SET
title='$thisTitle',
description='$thisDescription',
year='$thisYear',
rating='$thisRating',
genre='$thisGenre',
filename='$thisNewFilename'
WHERE
imageid= $thisOneToEdit";
$result = mysql_query($sql) or die (mysql_error());
}
You're suffering from an imminent dose of SQL Injection due to using a dangerous user input model.
When you type "Assassin's Creed III" in the title field, that gets placed in single quotes in the UPDATE statement in your code (via the $_POST['title'] variable):
'Assassin's Creed III'
The problem there is that MySQL sees it as 'Assassin', followed by s Creed III'. It doesn't know what to do with the latter.
Of course, this becomes a HUGE problem if someone types in valid SQL at that point, but not what you expected. Have a look at How can I prevent SQL injection in PHP? or any of several other advices on avoiding SQL Injection.
i have seen you are adding ' into database so you need to escape it using addslashes()
addslashes($thisTitle)
You have syntax error here. Use $_POST instead of $POST.
Replace
$thisYear = $POST['year'];
$thisRating = $POST['rating'];
$thisGenre = $POST['genre'];
With
$thisYear = $_POST['year'];
$thisRating = $_POST['rating'];
$thisGenre = $_POST['genre'];
you need to escape your input like
$thisDescription = mysql_real_escape_string($_POST['description']);
do this for all input that contains quotation marks etc..
NOTE: mysql will soon be gone so its advised to write new code using mysqli instead
You have alot of issues in your script.
You're trying to add ' character to database, you need to escape it properly with addslashes.
You're vulnerable to SQL Injection. Escape it properly with mysql_real_escape_string, or even better, use PDO.
Third, it is $_POST, not $POST. You're using it wrong in some areas.
Add quotes to $thisOneToEdit in query.
The error is causing because you're trying to add Assasin's Creed III string to database. The single quote breaks your query and creates a syntax error.
Do a addslashes() on the values that might contain single or double quotes like below before using them in query
$thisTitle = addslashes($_POST['title']);

SQL Table not updating in PHP

I'm trying to create an update function in PHP but the records don't seem to be changing as per the update. I've created a JSON object to hold the values being passed over to this file and according to the Firebug Lite console I've running these values are outputted just fine so it's prob something wrong with the sql side. Can anyone spot a problem? I'd appreciate the help!
<?php
$var1 = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature
$jsonObject = json_decode($_REQUEST['outputJSON']); // Decode JSON object into readable PHP object
$name = $jsonObject->{'name'}; // Get name from object
$desc = $jsonObject->{'desc'}; // Get desc from object
$did = $jsonObject->{'did'};// Get id object
mysql_connect("localhost","root",""); // Conect to mysql, first parameter is location, second is mysql username and a third one is a mysql password
#mysql_select_db("findadeal") or die( "Unable to select database"); // Connect to database called test
$query = "UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}";
$add = mysql_query($query);
$num = mysql_num_rows($add);
if($num != 0) {
echo "true";
} else {
echo "false";
}
?>
I believe you are misusing the curly braces. The single quote should go on the outside of them.:
"UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}"
Becomes
"UPDATE deal SET dname = '{$name}', desc='{$desc}' WHERE dealid = '{$did}'"
On a side note, using any mysql_* functions isn't really good security-wise. I would recommend looking into php's mysqli or pdo extensions.
You need to escape reserved words in MySQL like desc with backticks
UPDATE deal
SET dname = {'$name'}, `desc`= {'$desc'} ....
^----^--------------------------here
you need to use mysql_affected_rows() after update not mysql_num_rows

Wrong mysql query in php file?

I'm trying to insert some data into my mysql database. The connection is working fine but im having a problem with sending the query correctly to the database. Below you can find the code in my php file. I also post what for type of fields they are in the Database.
Fields in the mysql database:
Reservaties_id = int
Materialen_id = int
aantal = int
effectief_gebruikt = tinyint
opmerking = Varchar2
datum_van = date
datum_tot = date
$resID = $_REQUEST['resID'];
$materialen_id = $_REQUEST['materialen_id'];
$aantal = $_REQUEST['aantal'];
$effectief_gebruikt = $_REQUEST['effectief_gebruikt'];
$opmerking = $_REQUEST['opmerking'];
$datum_van = date('YYYY-MM-DD',$_REQUEST['datum_van']);
$datum_tot = date('YYYY-MM-DD',$_REQUEST['datum_tot']);
$string = "INSERT INTO `materialen_per_reservatie`(`reservaties_id`, `materialen_id`, `aantal`, `effectief_gebruikt`, `opmerking`, `datum_van`, `datum_tot`) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', $datum_van, $datum_tot)";
mysql_query($string);
you have to include single quotes for the date fields '$dataum_van'
$string = "INSERT INTO `materialen_per_reservatie`(reservaties_id, materialen_id, aantal, effectief_gebruikt, opmerking, datum_van, datum_tot) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', '$datum_van', '$datum_tot')";
and this is only a example query, while implementing don't forget to sanitize your inputs
Your code has some serious problems that you should fix. For one, it is not doing any error checking, so it's no surprise the query breaks silently when it fails. Check for errors and it will tell you what goes wrong - how to do it is outlined in the manual on mysql_query() or in this reference question.. Example:
$result = mysql_query($string);
// Bail out on error
if (!$result)
{
trigger_error("Database error: ".mysql_error(), E_USER_ERROR);
die();
}
In this specific case, I'm fairly sure it's because you are not putting your values into quotes after the VALUES keyword.
Also, the code you show is vulnerable to SQL injection. You need to escape every value you use like so:
$resID = mysql_real_escape_string($_REQUEST['resID']);
for this to work, you need to put every value in your query into quotes.
try this
$string = "INSERT INTO `materialen_per_reservatie`(`reservaties_id`) VALUES ('".$resID."')";

Actionscript 3 MySQL query using PHP

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"])

Categories