PHP SQL Return just returns "Array" - firebird

I've tried using something similar to the following PHP code to retrieve items from a Firebird database.
$sql = "select P_1,P_2,P_3 from p_players('$playerid', '')";
//This sends the SQL select statement to the db
$rs=$db->Execute($sql);
//This converts the SQL statement to an array
$result = $rs->GetArray();
echo $result;
However, the echo result that I receive keeps returning "Array" no matter what I select as the database to query. What am I doing wrong? Thanks for any assistance.

Try this one:
$sql = "select P_1,P_2,P_3 from p_players('$playerid', '')";
//This sends the SQL select statement to the db
$rs=$db->Execute($sql);
//This converts the SQL statement to an array
$result = $rs->GetArray();
print_r $result;

Related

I am having trouble with my postgresql query

I have a query in mysql works well, but when I go to postgresql does not update me, I want to know where is my error.
I leave my php file the query update does not work
<?php
require_once "Controllers/conexion.php";
session_start();
$resultado=pg_query("SELECT nextval('user_id_seq') as key");
$row=pg_fetch_array($resultado, 0);
$key=$row['key'];
try {
$resultado = pg_query($conexion,"select * from encuesta_respuesta where id_user = '".$_SESSION['user']."' and id_encuesta = '".$_POST['id_encuesta']."'");
while( $row = pg_fetch_assoc($resultado)){
$data = $row;
}
if ($data['estado']=='F') {
header("Location: Inicio.php");
}
foreach($_POST['pregunta'] as $id_pregunta=>$valor){
$query="insert into encuesta_respuesta_opcion values (".$key.",".$_POST['id_encuesta'].",".$id_pregunta.",".$valor.")";
$resultado = pg_query($conexion,$query);
}
$query="update encuesta_respuesta set estado='F' where id_user=".$_SESSION['user']." and id_encuesta = ".$_POST['id_encuesta'];
$resultado = pg_query($conexion,$query);
$resp['error']=false;
} catch (Exception $e) {
$resp['error']=true;
}
header("Location: Inicio.php");
?>
Directly try to update data in your database, check this query works or not. If it works, then you have to change your query building procedure in your application. For example:
postgres=# create table test (id_user VARCHAR (50) PRIMARY KEY, id_encuesta VARCHAR (50), estado VARCHAR (10));
postgres=# insert into test values ('anower','engg.','A');
postgres=# update test set estado='F' where id_user='anower' and id_encuesta='engg.';
The query should work the same in MySql and postgres.
If you are getting different results during updates then your survey tables arent the same.
Most liked id_user and id_encuesta are autoincrement fields. So they dont necesary have the same values.
Try using a Select to see if they have same survey information.
SELECT *
FROM survey
where id_user=".$_SESSION['user']."
and id_encuesta = ".$_POST['id_encuesta'];

Error when using "ALL" operator when execute query

I need to execute following query using phalcon framework:
"SELECT id FROM table GROUP BY id HAVING '31' = ALL(array_agg(status))"
How can I execute this query using phalcon?
When I do following:
Model::query()
->columns(['id'])
->groupBy('id')
->having('31 = ALL(array_agg(status))')
->execute();
I get this error message:
Syntax error, unexpected token ALL, near to '(array_agg(status)) ', when parsing: SELECT id FROM [SomeNameSpace\Model] GROUP BY [id] HAVING 31 = ALL(array_agg(status)) (137)
I'm not 100% sure which Postgres functions are supported, but you can try like this:
Model::query()
->columns([
'id',
'ALL(array_agg(status)) AS statusCounter'
])
->groupBy('id')
->having('31 = statusCounter')
->execute();
Notice that I moved the aggregation functions in the select, rather in having clause.
UPDATE: here is an example of very custom query. Most functions used are not supported and it's sometimes cleaner just to write a simple SQL query and bind the desired Model to it:
public static function findNearest($params = null)
{
// A raw SQL statement
$sql = '
SELECT *, 111.045 * DEGREES(ACOS(COS(RADIANS(:lat))
* COS(RADIANS(X(coords)))
* COS(RADIANS(Y(coords)) - RADIANS(:lng))
+ SIN(RADIANS(:lat))
* SIN(RADIANS(X(coords)))))
AS distance_in_km
FROM object_locations
ORDER BY distance_in_km ASC
LIMIT 0,5;
';
// Base model
$model = new ObjectLocations();
// Execute the query
return new \Phalcon\Mvc\Model\Resultset\Simple(
null,
$model,
$model->getReadConnection()->query($sql, $params)
);
}
// How to use:
\Models\ObjectLocations::findNearest([
'lat' => 42.4961756,
'lng' => 27.471543300000008
])
You need to add ALL as dialect extension. Check this topic for example https://forum.phalconphp.com/discussion/16363/where-yearcurrenttimestamp-how-to-do-this

Zend: Inserting Large data in CLOB and BLOB?

I am pulling data from Google Places API and trying to insert reviews into oracle database using zend framework. But reviews that are very long are giving error like :
ORA-01461: can bind a LONG value only for insert into a LONG
When i try to run the insert query in Orqcle SQL Developer its giving the following error:
I tried some of the solutions i got on google and stackoverflow but still not working.
Here is my db code in zend:
public function addReview($bind) {
$bind['STATUS'] = 1;
$bind['CREATED_TIME'] = $this->_curDate;
$text = htmlentities($bind['TEXT']);
$query = "Insert INTO ".$this->_name." (LID,AUTHOR_NAME,AUTHOR_URL,RATINGS,TYPE,TIME,STATUS,TEXT)
VALUES (".$bind['LID'].",
'".$bind['AUTHOR_NAME']."',
'".$bind['AUTHOR_URL']."',
'".$bind['RATINGS']."',
'".$bind['TYPE']."',
'".$bind['TIME']."',
".$bind['STATUS'].",'".$text."')";
try {
$insert = $this->_dbAdpt->query($query);
} catch (Exception $e) {
echo $query; exit;
}
}
Somehow creating a procedure for inserting the reviews worked! Below is the procedure :
create or replace procedure google_review (lid in int,author_name in varchar2, author_url in varchar2,ratings in varchar2,
type in varchar2,time in varchar2,status int,text in varchar2)
as
begin
INSERT INTO TBL_REVIEWS
(
LID,
AUTHOR_NAME,
AUTHOR_URL,
RATINGS,
TYPE,
TIME,
STATUS,
TEXT
)
VALUES
(
LID,
AUTHOR_NAME,
AUTHOR_URL,
RATINGS,
TYPE,
TIME,
STATUS,
TEXT
);
end;

Using php DateTime object in mysql query

I'm trying to create a query that pulls information about sellers from my database, but only if their store has launched in the last 3 days. The easiest way I can think of to calculate the date for the query is using a new DateTime() object. When I output my code to test it, it's in the proper string for MySQL to query it with, but whenever I try to bind the variable, I get an error. I'm using Zend_Db to query, (PDO adapter)
action:
public function indexAction()
{
$dateMod = new DateTime();
$dateMod->modify('-2 days');
$dateMod->format('Y-m-d H:i:s');
// get sellers initialized in last 3 days
$sellerTable = new Application_Model_DbTable_Sellers();
$select = $sellerTable->select()->setIntegrityCheck(false);
$select->from(array('s' => 'seller'),array('sellerID', 'businessName'));
// select firstName, lastName, picture from user table, and businessName and sellerID from seller table.
$select->join(array('u' => 'user'), 's.userID = u.userID', array('firstName', 'lastName', 'picture'));
$select->where('s.active = 1 AND s.contentApproval = 1 AND s.paymentApproval = 1 AND s.featured = 1');
$select->where('s.launchDate > ?', $dateMod);
$select->order('s.launchDate DESC');
$newSellers = $sellerTable->fetchAll($select);
When I assign $dateMod to the view, it outputs the correct Y-m-d H:i:s format. But when I plug it into the query, I get the following error:
Message: SQLSTATE[42000]: Syntax error or access violation: 1064 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 ') ORDER BY `b`.`launchDate` DESC' at line 2
If I hardcode a value into dateMod in the mysql timestamp format, the query works fine. How can I access just the string value of the timestamp in the DateTime object? getTimestamp returns a unix formatted timestamp, even after assigning a format.
The format() function returns the formatted date, so you need to assign that to a variable for use in the query:
$dateFormatted = $dateMod->format('Y-m-d H:i:s');
$select->where('s.launchDate > ?', $dateFormatted);

Zend Query Select

Hi i need to do a simple query but something is wrong. I have $name and $surname and i need to search the (possible multiple) id that rappresent that name and surname and put all the id, name and surname in a array
I do this query:
$result=$this->_db_table->select()->where('name=?',$name)
->where('surname=?', $surname)->query()
->fetchAll();
$array=$result->toArray();
return $array;
If i use
$result=$this->_db_table->fetchAll();
$array=$result->toArray();
return $array
it work correctly and i have an array whith all the value in the database in that table. What is wrong in my first code???
After doing this
$result=$this->_db_table->select()->where('name=?',$name)
->where('surname=?', $surname)->query()
->fetchAll();
$result is already an array its not an object . So simply use it instead of calling toArray on it.
Correct code wd be
$result=$this->_db_table->select()->where('name=?',$name)
->where('surname=?', $surname)->query()
->fetchAll();
return $result;