How can i make a SQL query from actionscript? and render all the results
You have to call a serverside script (for example php) and then retrieve the output of that script
private var _loader:URLLoader;
private var _request:URLRequest;
private function loadData():void {
_loader = new URLLoader();
_request = new URLRequest("path/to/your/phpscript");
_request.method = URLRequestMethod.POST;
_loader.addEventListener(Event.COMPLETE, onLoadData);
_loader.addEventListener(IOErrorEvent.IO_ERROR, onDataFailedToLoad);
_loader.addEventListener(IOErrorEvent.NETWORK_ERROR, onDataFailedToLoad);
_loader.addEventListener(IOErrorEvent.VERIFY_ERROR, onDataFailedToLoad);
_loader.addEventListener(IOErrorEvent.DISK_ERROR, onDataFailedToLoad);
_loader.load(_request);
}
private function onLoadData(e:Event):void {
trace("onLoadData",e.target.data);
}
private function onDataFailedToLoad(e:IOErrorEvent):void {
trace("onDataFailedToLoad:",e.text);
}
an example php script:
<?php
// defining main variables
$dbHost = "localhost";
$dbUser = "root";
$dbPass = "";
$dbName = "test";
$dbTable = "data";
// connecting and selecting database
#mysql_connect($dbHost, $dbUser, $dbPass) or die(mysql_error());
#mysql_select_db($dbName) or die(mysql_error());
// getting data
$data = "";
$res = mysql_query("SELECT * FROM ".$dbTable." ORDER BY id") or die(mysql_error());
while($row = mysql_fetch_object($res)) {
$data .= "nname=".$row->name.", ";
$data .= "city=".$row->city;
}
echo $data;
?>
For a better workflow, I suggest looking into AMF...
Here's a tutorial on AMF
There's no real equivalent to JDBC or ODBC for working in Flex that I'm aware of. Most likely this just wasn't really explored as something to attempt to deliver since Flex/Flash is generally client side and the DB is generally server side (shared). Generally speaking you'd use Java, PHP, C#, ASP .NET, Python, C++, or some other server side program to establish the connection to a DB and run queries. The closest thing to what your question is asking that I've seen is this: http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118676a5497-7fb4.html but only applies to AIR and not for remote SQL connections. I'm not entirely sure how much work is involved in writing up a JDBC like interface/implementation to connect to any given DB I suppose in part it depends on how well documented the DBMS is... either way my guess is it'd be a ton of work.
EDIT
Okay so actually eating my words to some degree, apparently it is somewhat feasible: http://groups.google.com/group/flex_india/browse_thread/thread/d89bb5120fad7369?pli=1
You -really- don't want to do SQL query connections from Flex, especially if the application is distributed to users. Flash/Flex applications can be easily decompiled into readable source code, and if you're SQL connection string is in the source, you're going to have all kinds of security problems. It's a significantly better idea to have Flex use a restful web API to server-side languages like PHP, Python, Perl, or Node to do the SQL data processing for you.
Even if your application is internal, it's still a better concept "on paper" to keep Flex away from directly manipulating the database.
Related
sub completecheckout {
$cryptedcard = md5_hex($cardnum . $salt);
$grabcart = qq~select pid from cart where uid='$cookievalue'~;
$dbh = DBI->connect($connectionInfo, $user, $passwd);
$sth = $dbh->prepare($grabcart);
$sth->execute();
while (#row = $sth->fetchrow_array()) {
$insert = qq~insert transaction (uid, pid, cctype, ccnum)
values ('$cookievalue', '$row[0]', '$cardtype',
'$cryptedcard')~;
$dbh = DBI->connect($connectionInfo, $user, $passwd);
$sth = $dbh->prepare($insert);
$sth->execute();
}
$select = qq~select * from registered where id in
(select uid from transaction
where uid='$cookievalue')~;
$dbh = DBI->connect($connectionInfo,$user,$passwd);
$sth = $dbh->prepare($select);
$sth->execute();
#userinfo = $sth->fetchrow_array();
print header;
print qq~<html><head><title>YAY</title></head><body><p>CHECK MYSQL<p><p>#row</p></body></html>~;
}
I am trying to parse through the table cart and insert all the items associated with the user into a transaction table when they click the final checkout button. The above code will only insert the last row into the transaction table.
Here is code that inserts more than once, but does not work because $product is empty every other time.
sub completecheckout {
$cryptedcard = md5_hex($cardnum . $salt);
$grabcart = qq~select pid from cart where uid='$cookievalue'~;
$dbh = DBI->connect($connectionInfo,$user,$passwd);
$sth = $dbh->prepare($grabcart);
$sth->execute();
#cart = $sth->fetchrow_array();
foreach $product (#cart) {
$insert = qq~insert transaction (uid, pid, cctype, ccnum)
values ('$cookievalue', '$product', '$cardtype',
'$cryptedcard')~;
$dbh = DBI->connect($connectionInfo,$user,$passwd);
$sth = $dbh->prepare($insert);
$sth->execute();
}
$select = qq~select * from registered where id in
(select uid from transaction
where uid='$cookievalue')~;
$dbh = DBI->connect($connectionInfo,$user,$passwd);
$sth = $dbh->prepare($select);
$sth->execute();
#userinfo = $sth->fetchrow_array();
print header;
print qq~<html><head><title>YAY</title></head><body><p>CHECK MYSQL<p><p>#userinfo</p></body></html>~;
}
Can anyone explain why this happens? I have been using while loops with fetchrow_array throughout my script to create tables linked to databases.
Firstly, you need to get into the habit of formatting your code better. It really helps following logic flow if the formatting imitates the logic.
Secondly, please turn on use strict and get used to declaring variables as close to their point of use as possible.
Thirdly, don't use global variables. Your subroutine uses $cardnum, $salt, $cookievalue and several other variables which are (presumably) defined outside of the subroutine. They should all be passed into the subroutine as parameters.
I know from previous conversations that you have no interest in learning Perl, you're just trying to get through a course that your college insists on. So I should make it clear that all of the advice above has nothing to do with Perl. That is all good general advice for any programming language.
Now, the specific problems.
You're creating a new $dbh any time you want to run a database query. Why not just connect once and then reuse that variable. A single $dbh can support multiple queries executing at the same time.
As Matt has pointed out in the comments, you are overwriting $sth. As I said above, a $dbh can support multiple concurrent queries, but each query needs its own statement handle. So you might do something like:
my $dbh = DBI->connect(...);
my $select_sth = $dbh->prepare($select_sql);
$select_sth->execute;
while (my #row = $select_sth->fetchrow_array) {
my $insert_sth = $dbh->prepare($insert_sql);
$insert_sth->execute;
}
Notice how I've a) reused the same $dbh and b) declared the $insert_sth within the loop so it's only available for the shorted possible amount of time.
If you were interested in Perl, I'd also show you how to make your code more efficient by using bind points in your SQL and passing extra parameters to execute(). I'd also recommend moving raw HTML out of your program and using a templating engine. But I strongly suspect you wouldn't be interested.
right now, I am kinda frustrated and I hope someone can help me and point me into the right direction.
I have an "old" project which uses the mysql statements for connection to database, etc.
Within this project I have the following:
An index file containing
*
* load configuration and connect to database
*/
$projectConfiguration = new projectConfiguration();
$dbconnect = $projectConfiguration->connect($projectConfiguration->databaseHost, $projectConfiguration->databaseName, $projectConfiguration->databaseUser, $projectConfiguration->databasePass);
// load controller
$ReqMod = FatFramework\Functions::getRequestParameter("mod");
if (!$ReqMod) {
$ReqMod = FatFramework\Functions::getRequestParameter("controller");
}
$module = ($ReqMod) ? $ReqMod : 'default';
In this style I call the views and actions in classes, like SaveAction()
Using mysql always made it very simple to use this database connection in the models called by the controllers like
public function loadCustomersList($sAdditionalWhere = false)
{
$sQuery = "SELECT * FROM customers WHERE 1 ";
if ($sAdditionalWhere) {
$sQuery .= "AND " . $sAdditionalWhere . " ";
}
$sQuery .= "ORDER BY company";
$sql = mysql_query($sQuery);
while (($customer = mysql_fetch_object($sql)) != false) {
$aCustomers[] = $customer;
}
return $aCustomers;
}
I want to totally refractor this project and use PDO. I tried for the last 4 hours to find a solution, but I can't figure out how to make it work.
I think I don't need an extra dbconnect class since PDO is a class itself, am I right?
In the new index file I tried the following:
$db = new database();
try{
$dbc = new PDO($db->get_DbConSettings());
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e)
{
echo 'Verbindung fehlgeschlagen: '.$e->getMessage();
}
But with this $dbc will not available in controllers or models. It there a way to make it available there? If not, what is the best solution?
Do I have to make a database connection in every model?
An other issue I have with this is:
$db->get_DbConSettings()
in
$dbc = new PDO
gives back
'mysql:host=127.0.0.1; dbname=c1virtbkk', 'root', '123'
($dbc = new PDO('mysql:host=127.0.0.1; dbname=c1virtbkk', 'root', '123');)
I cannot connect to the database. I get the following:
Verbindung fehlgeschlagen: could not find driver
If I don't use $db->get_DbConSettings and put the required information manually in, I don't get any error and can do queries. Any hints?
Help is really appreciated.
Thanks in advance!
Mark
Definitely don't create a new PDO connection in each model. Creating MySQL database connections is fairly quick, but there's still some overhead to doing so. You want to reuse a connection throughout your request. If nothing else, it allows you to share a transaction across multiple models.
Some frameworks store shared resource objects in a "registry" class which is a singleton key-value store. It's not really much more than a global hash array, but making it a class makes the registry itself more easily tested with PHPUnit. See https://framework.zend.com/manual/1.12/en/zend.registry.using.html for an example of a registry.
You're right that PDO is a class, even though it's implemented as a C extension instead of a PHP class. But it's a class, and new PDO(...) returns an object of that class.
One reason to create a db class of your own is to help you in unit-testing, because you could create a mock object for your db class so you can test your other classes (even model classes) without needing a live database connection. Your db class could extend or else contain a PDO object.
Your issue about the error "could not find driver" is probably because the PDO driver for mysql is not installed. PDO is one PHP extension, and then there's a separate extension for each brand of SQL database. You can confirm this with:
$ php -i
...lots of output...
PDO
PDO support => enabled
PDO drivers => mysql, odbc, sqlite
pdo_mysql
PDO Driver for MySQL => enabled
Client API version => mysqlnd 5.0.11-dev - 20120503 - $Id: 76b08b24596e12d4553bd41fc93cccd5bac2fe7a $
...more output for other extensions...
Note that PDO tells me which drivers I have installed: mysql, odbc, and sqlite.
So you need to install pdo_mysql. I'm not sure what OS you're on, but I'm often on CentOS Linux or Ubuntu Linux. The pdo_mysql is available as a separate package via yum or apt.
Re your comment:
Okay, here's an example of a registry:
class registry {
protected static $items = array();
public static get($key) {
return isset(self::$items[$key])?
self::$items[$key] : null;
}
public static set($key, $object) {
self::$items[$key] = $object;
}
}
In your controller initial code, you'd create a database object and store it in the registry:
$projectConfiguration = new projectConfiguration();
$dbconnect = $projectConfiguration->connect(
$projectConfiguration->databaseHost,
$projectConfiguration->databaseName,
$projectConfiguration->databaseUser,
$projectConfiguration->databasePass);
registry::set('db', $dbconnect);
Then in your model class methods (or anywhere you need the database), get the db object from the registry and use it:
public function loadCustomersList($sAdditionalWhere = false)
{
$sQuery = "SELECT * FROM customers WHERE 1 ";
if ($sAdditionalWhere) {
$sQuery .= "AND " . $sAdditionalWhere . " ";
}
$sQuery .= "ORDER BY company";
$db = registry::get('db');
$stmt = $db->query($sQuery);
$aCustomers = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $aCustomers;
}
I'm quite new to databases and have no idea where I have gone wrong. Please help me find out why I can't connect to my database.
I'm getting an error with Dreamweaver - Dynamicaly-related files cannot be discovered because there is no site definition for this document
My Site root is located in htdocs.
the main file I'm trying to run is "dataquery.php" - htdocs/LetsPlays/dataquery.php
<?php
include 'includes/databaseform.php';
$query = "SELECT * FROM userchanel";
$result = mysql_query($query);
while($person = mysql_fetch_array($result));
{
echo $person['chanelurl'];
}
?>
Dataquery is connected to "databaseform.php" - htdocs/LetsPLays/includes/databaseform.php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass ='';
$db = 'mysql_tut';
$conn = mysql_connect($dbhost,$dbuser,$dbpas);
mysql_select_db($userchanel);
?>
So I'm trying to connect to userchanel table through user tbl
screenshot: http://imageshack.us/f/23/usertbl.png/
Files run through wordpress are set up to run on 127.0.0.1
Please help me.
Sorry for the noobishness! I have no idea what I'm missing!
When I run the html file all I get is a blank page!
Replace the line
$conn = mysql_connect($dbhost,$dbuser,$dbpas);
with
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
notice the double 's' on $dbpass, also if I may you should not rely on deprecated features when writing new code, use PDO instead, also don't login to db as root, create a user, don't be lazy, with that your database connection code should like:
<?php
$db = new PDO('mysql:dbname=databasename', 'username', 'password',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
the init command is not actually necessary I just included it cause I always use it, while the querying could be done as
<?php
include 'includes/databaseform.php';
$query = $db->prepare("SELECT * FROM userchanel");
$query->execute();
while(($person = $query->fetch(PDO::FETCH_ASSOC)) !== false);
{
echo $person['chanelurl'];
}
If you're only using one column you should fetch only that as below:
<?php
include 'includes/databaseform.php';
$query = $db->prepare("SELECT chanelurl FROM userchanel");
$query->execute();
while(($channelurl = $query->fetch(PDO::COLUMN)) !== false);
{
echo $channelurl;
}
I didn't include closing braces for php code as they are not necessary also do some error checking var_dump($db->errorInfo()); and var_dump($query->errorInfo()); - didn't include this in the code as I only use them in checking any issues with my code, good luck!
instead of htdocs/LetsPlays/dataquery.php
try localhost/dataquery.php
I recommend you to make and additional file for database connection and include it anywhere you need. Because when you need to push project live you need to change in every file incase file is includeed you need to change just at one place and it effects every where connection for localhost is
<?php
// Replace the variable values below
// with your specific database information.
$host = "localhost";
$user = "root";
$pass = "";
$db = "yourdatabase";
// This part sets up the connection to the
// database (so you don't need to reopen the connection
// again on the same page).
$ms = mysql_pconnect($host, $user, $pass);
if ( !$ms )
{
echo "Error connecting to database.\n";
}
// Then you need to make sure the database you want
// is selected.
mysql_select_db($db);
?>
Save all the above code in one file save it as dbConfig.php and include it any where
like
include ("dbConfig.php");
Now in that file you are connected to db you can interact with database.
I have written some code in PHP that returns the html content from .edu domains. A brief introduction is given here: Errors regarding Web Crawler in PHP
The crawler works fine when the number of links to crawl are small (something around 40 URLS) but I am getting "MySQL server has gone away" error after this number.
I am storing html content as longtext in MySQL tables and I am not getting why the error arrives after at least 40-50 insertions.
Any help in this regard is highly appreciated.
Please note that I have already altered the wait_timeout and max_allowed_packet to accomodate my queries and the php code and now I don't know what to do. Please help me in this regard.
You might be inclined to handle this problem by "pinging" the mysql server before a query. This is a bad idea. For more on why, check this SO post: Should I ping mysql server before each query?
The best way to handle the issue is by wrapping queries inside try/catch blocks and catching any database exceptions so that you can handle them appropriately. This is especially important in long running and/or daemon type scripts. So, here's a very basic example using a "connection manager" to control access to DB connections:
class DbPool {
private $connections = array();
function addConnection($id, $dsn) {
$this->connections[$id] = array(
'dsn' => $dsn,
'conn' => null
);
}
function getConnection($id) {
if (!isset($this->connections[$id])) {
throw new Exception('Invalid DB connection requested');
} elseif (isset($this->connections[$id]['conn'])) {
return $this->connections[$id]['conn'];
} else {
try {
// for mysql you need to supply user/pass as well
$conn = new PDO($dsn);
// Tell PDO to throw an exception on error
// (like "MySQL server has gone away")
$conn->setAttribute(
PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION
);
$this->connections[$id]['conn'] = $conn;
return $conn;
} catch (PDOException $e) {
return false;
}
}
}
function close($id) {
if (!isset($this->connections[$id])) {
throw new Exception('Invalid DB connection requested');
}
$this->connections[$id]['conn'] = null;
}
}
class Crawler {
private $dbPool;
function __construct(DbPool $dbPool) {
$this->dbPool = $dbPool;
}
function crawl() {
// craw and store data in $crawledData variable
$this->save($crawledData);
}
function saveData($crawledData) {
if (!$conn = $this->dbPool->getConnection('write_conn') {
// doh! couldn't retrieve DB connection ... handle it
} else {
try {
// perform query on the $conn database connection
} catch (Exception $e) {
$msg = $e->getMessage();
if (strstr($msg, 'MySQL server has gone away') {
$this->dbPool->close('write_conn');
$this->saveData($val);
} else {
// some other error occurred
}
}
}
}
}
I have another answer that deals with what I think is a similar problem, and it would require a similar answer. Basically, you can use the mysql_ping() function to test the connection before your insert. Before MySQL 5.0.14, mysql_ping() would automatically reconnect the server, but now you have to build your own reconnect logic. Something similar to this should work for you:
function check_dbconn($connection) {
if (!mysql_ping($connection)) {
mysql_close($connection);
$connection = mysql_connect('server', 'username', 'password');
mysql_select_db('db',$connection);
}
return $connection;
}
foreach($array as $value) {
$dbconn = check_dbconn($dbconn);
$sql="insert into collected values('".$value."')";
$res=mysql_query($sql, $dbconn);
//then some extra code.
}
I was facing "Mysql server has gone away" error while using Mysql connector 5.X, replacing dll to the last version solved the problem.
Are you opening a single DB connection and reusing it? Is it possible that its a simple timeout? You might be better served by opening a new DB connection for each of your read/write operations (IE contact .edu, get text, open DB, write text, close db, repeat).
Also how are you using the handle? Is it possible that it has hit an error and has 'gone away' for that reason?
Well This is what I am doing now based on rdlowrey's suggestion and I guess this is also right.
public function url_db_html($sourceLink = NULL, $source) {
$source = mysql_real_escape_string($source);
$query = "INSERT INTO html (id, sourceLink, sourceCode)
VALUES (NULL,('$sourceLink') , ('$source'))";
try {
if(mysql_query($query, $this->connection)==FALSE) {
$msg = mysql_errno($this->connection) . ": " . mysql_error($this->connection);
throw new DbException($msg);
}
} catch (DbException $e) {
echo "<br><br>Catched!!!<br><br>";
if(strstr($e->getMessage(), 'MySQL server has gone away')) {
$this->connection = mysql_connect("localhost", "root", "");
mysql_select_db("crawler1", $this->connection);
}
}
}
So once the query has failed to execute, the script will skip it but will make sure the connection is re-established.
However, my web crawler is crashing when files such as .jpg, .bmp, .pdf, etc are encountered. Is there a way to skip those urls containing these extensions. I am using preg_match and has given pdf and doc to match. Yet I want the function to skip all links containing extensions such as mp3, pdf, etc. Is this possible??
I have few questions about Doctrine and MySQL working together. I don't understand it in 100%
I read somewhere that Doctrine can cooperate with MySQL DB. How it happens?
How do I load my DB?
How do I operate on my MySQL tables via doctrine (I'm no thinking about creating new ones)?
Does Doctrine save automatically changes to database?, if not then how to?
Some sample of code would be great. I don’t care too much about language can be in PHP, Yaml and others.
a) please specify more what you maen with "load DB". Doctrine is an ORM.
check here docs:
http://www.doctrine-project.org/projects/orm/1.2/docs/hu (check cookbook)
b) operations with tables with Doctrine are with DQL, example:
$q = Doctrine_Query::create()
->from('User u')
->leftJoin('u.Phonenumbers p');
$q->execute(); //you get a doctrine collection to iterate results of query
c)NO you need to save the object
$account = new Account();
$account->name = 'test 1';
$account->amount = '100.00';
$account->save();
here is account class
class Account extends Doctrine_Record
{
public function setTableDefinition()
{
$this->hasColumn('name', 'string', 255);
$this->hasColumn('amount', 'decimal');
}
}