PDA

View Full Version : SELECT * > to $array



smrtak
8th September 2008, 10:56
how can i write in qt this?

PHP:


$sql = "SELECT * FROM ..."
...
while($row = mysql_assoc_array($result)){
$result[] = $row;
}
return $row;


I think am best way is use Object class (or maybe structs), but i want try something easy (XP).

lyuts
8th September 2008, 21:30
QSqlDatabase *db = QSqlDatabase::addDatabase("QPSQL7", "mainConnect");
//set db's credentials
if (!db->open()) {
// show some error message and stuff like that
}

QSqlQuery query(db);
QString qstr;
...
qstr = QString("your query goes here; ");

query.exec(qstr);

if (!query.first()) {
// in this case no data has been selected
// do what you think you shoul
}

do {
// process your data
} while (query.next())



http://doc.trolltech.com/4.4/qsqlquery.html

smrtak
9th September 2008, 18:21
sorry, wrong question...

i need this


something_as_assoc_array_inPHP DB:myDbFunction(){
QSqlDatabase *db = QSqlDatabase::addDatabase("QPSQL7", "mainConnect");
//set db's credentials
if (!db->open()) {
// show some error message and stuff like that
QSqlQuery query(db);
QString qstr;
qstr = QString("your query goes here; ");
query.exec(qstr);

if (!query.first()) {
// in this case no data has been selected
// do what you think you shoul
}
do {
something_as_assoc_array_inPHP = query..........
} while (query.next())
delete db;

return something_as_assoc_array_inPHP;
}


code:

var = DB:myDbFunction();
qtDebug() << var[0]["id"];

spirit
10th September 2008, 08:06
you still need to use QSqlQuery in loop like was written above.
you can get access to data using by index
QVariant QSqlQuery::value ( int index ) const or by field name using


QSqlRecord QSqlQuery::record () const
QVariant QSqlRecord::value ( const QString & name ) const


links:
getting value by index using QSqlQuery (http://doc.trolltech.com/4.4/qsqlquery.html#value)
getting record (http://doc.trolltech.com/4.4/qsqlquery.html#record)
geeting value by index using QSqlRecord (http://doc.trolltech.com/4.4/qsqlrecord.html#value)
getting value by name using QSqlRecord (http://doc.trolltech.com/4.4/qsqlrecord.html#value-2)

Lesiok
10th September 2008, 08:16
Can You explain for what ? I don't see any reason for that.

yxmaomao
10th September 2008, 10:21
I don't think there is an easy way to read all records into a Array directly.
Does anyone has good idea?

spirit
10th September 2008, 10:25
why not? you can keep list of pointers to QSqlRecord. why this is bad idea?

spirit
10th September 2008, 10:30
you can create you own container for returning result in this way. I've just show how to get values from query using existing methods.