PHP PDO queries not working - php

I have a dbfunctions class that has the functions to retrieve and write data to database. However, the retrieval doesn't work and I can't understand why it doesn't work.
The read functions looks like this:
public function haeParametreittaTietokannasta($f_sql) {
try {
$this->sql_lause = $this->db->prepare($f_sql);
$this->haku = $this->sql_lause->execute();
} catch (PDOException $ex) {
die("Tapahtui virhe tietoja noudettaessa : " . $ex->getMessage());
}
if(!$this->haku) {
$this->tulos = $this->haku->fetchAll();
return $this->tulos;
} else {
return false;
}
} // END FUNCTION
And this is how I call the function:
$countries = $dabase->haeParametreittaTietokannasta("SELECT * FROM countries");
The query always returns false, and I've tried showing error info and it says: array ( 0 => '00000', 1 => NULL, 2 => NULL, ) (And yes, I have created a new object in the main code.)
I've just started to learn PHP and there might be a simple error I just can't see...

You have the wrong if condition:
if(!$this->haku) {
should be
if($this->haku) {
$this->tulos = $this->sql_lause->fetchAll();
PDOStatement::execute() returns a boolean value. You can't use it for fetchAll().

Related

zend Framework 2 update query by TableGateway Object

public function update($table, $where = array(), $data_arr = array()){
print_r($data_arr);
$adapter = $this->tableGateway->getAdapter();
$projectTable;
if($table != null){
$projectTable = new TableGateway($table, $adapter);
}else{
$projectTable = new TableGateway('account_master', $adapter);
}
echo "158";
try {
echo "123";
$rowset = $projectTable->update(function(Update $update) use ($where, $data_arr) {
$update->set(array('statement_no' => '01010'));
$update->where($where);
echo $update->getSqlString();
});
} catch (\Exception $e) {
print_r($e);
}
print_r($rowset);
die();
}
my Output print : 158123
it's give me pass array in set() function that i already pass as argument. also i have tried to convert object to array ((arrya)$objetc) but it's not work for me.
[10-Jul-2017 05:11:34 America/Denver] PHP Catchable fatal error: Argument 1 passed to Zend\Db\Sql\Update::set() must be of the type array, object given, called in /home2/flywing1/vendor/zendframework/zend-db/src/TableGateway/AbstractTableGateway.php on line 336 and defined in /home2/flywing1/vendor/zendframework/zend-db/src/Sql/Update.php on line 93
You may do that by implementing a Zend\Db\Sql\Update object. You may create that object using the TableGateway. You should be able to do the following in your model
public function update($set, $where)
{
// Here is the catch
$update = $this->tableGateway->getSql()->update();
$update->set($set);
$update->where($where);
// Execute the query
return $this->tableGateway->updateWith($update);
}
Try it,
I was with the same issues, I tried with this, and it worked.
$rowset = $projectTable->update(array('statement_no' => '01010'), $where);

Same Function Passing different parameter in same query getting the both output at same time

I am sending two parameter From=2015-08-01 and To=2015-08-31 is working fine. Then how to also passing parameter (From2=2015-04-01 and To2 =2015-08-31) and getting the both output at same time. Please do not write any other functions. Please advise me.
This is my output.php
$res1=$con->selectnonschoolround1($From,$To);
while($row=pg_fetch_array($res1))
{
$r1=$row['non_slsc_qty'];
$r2=$row['non_slst_qty'];
$r3=$row['non_slot_qty'];
$r4=$row['non_slsc_ben'];
$r5=$row['non_slst_ben'];
$r6=$row['non_slot_ben'];
$Total_qty_non_r1=$row['total_qty'];
$Total_ben_non_r1=$row['total_ben'];
}
This is the class.php
class DB_con
{
function __construct()
{
$db = pg_connect("host=localhost port=5432
dbname=mydb user=postgres password=123");
}
public function selectnonschoolround1($From,$To)
{
$res1=pg_query("SELECT
SUM(non_slsc_qty) as non_slsc_qty,
SUM(non_slst_qty) as non_slst_qty,
SUM(non_slot_qty) as non_slot_qty,
SUM(non_slsc_ben) as non_slsc_ben,
SUM(non_slst_ben) as non_slst_ben,
SUM(non_slot_ben) as non_slot_ben,
SUM(non_slsc_qty+non_slst_qty+non_slot_qty) AS total_qty,
SUM(non_slsc_ben+non_slst_ben+non_slot_ben) AS total_ben
FROM table where date BETWEEN '$From' AND '$To'");
return $res1;
}
}
Pass function parameter as an array and then you need to check if parameter is array or not using PHP function is_array(). If its an array then loop through that array and execute the query with "from" and "to" indexes but, in this case you need to return an array from the executed query. If its not an array the keep the code as it is in your else part. In this you can use the same function for multiple value or for single values. Just keep in mind that the params should be proper. Hope this will help you out :)
Try this code and make the changes as per your need :).
class DB_con
{
function __construct()
{
//code
}
public function selectNonSchoolRound1($arr, $from = '', $to = '')
{
if (is_array($arr)) {
$returnArr = array();
foreach ($arr as $ars) {
$res1 = pg_query("your query using ".$ars['from'].$ars['to']);
array_push($returnArr, $res1);
}
return $returnArr;
} else {
$res1 = pg_query("your query using ".$from.$to.'variabls');
return $res1;
}
}
}
try {
$arr = array('0' =>
array('from' => '2015-08-01', 'to' => '2015-08-31'),
'1' => array('from' => '2015-08-01', 'to' => '2015-08-31')
);
$obj = new DB_con();
$result = $obj->selectNonSchoolRound1($arr);
// loop here with the $result variable
} catch (Exception $ex) {
echo $ex->getMessage();
}

Yii2: get raw sql of model->save()

I want to add record to a table with ActiveRecord.
Here is my code:
$model = new Article();
$model->title = 'test title';
$model->content = 'test content';
$model->category_id = 1;
$model->author_id = 1;
if ($model->validate()) {
$model->save();
}
$model->validate() returns true, but $model->save() returns false.
How to find generated raw sql of $model->save()?
Meanwhile:
$model->save()->rawSql is null and $model->getErrors() returns empty array.
In debug, all queries are logged, but I did not find any insert or update query.
$model->save()->rawSql call can not return null, it must throw an exception that you are trying to access property of non-object. $model->save() returns boolean value - either query executed successfully or not.
If $model->getErrors() returns empty array and query was not executed at all I'm pretty sure that something is wrong with model event handlers, especially beforeSave(), check it, it should not return false. Also check attached behaviors event handlers.
As for getting query. It's useless if it simply was not executed, but if it was, here are some ways to achieve it:
1) Probably the best way. Use debug panel. I also mentioned it here.
2) Look at logs as #robsch adviced.
You can't directly get raw SQL in code with $model->save(), It will call either insert() or update(). If you are interested, here is the part of code for insertInternal():
$values = $this->getDirtyAttributes($attributes);
if (empty($values)) {
foreach ($this->getPrimaryKey(true) as $key => $value) {
$values[$key] = $value;
}
}
$db = static::getDb();
$command = $db->createCommand()->insert($this->tableName(), $values);
if (!$command->execute()) {
return false;
}
If you call $command->rawSql you will get raw sql but you can't do that outside because the command is formed internally.
P.S. This piece of code:
if ($model->validate()) {
$model->save();
}
doesn't make sense because $model->save() will call $model->validate() internally.
This code won't show you exactly the raw sql but you'll get the query pre binding and the params
try {
// this will simulate $model->save();
$builder = $model->getCommandBuilder();
$table = $model->getTableSchema();
$command = $builder->createInsertCommand($table, $model->getAttributes());
$command->_connection->enableParamLogging = true;
$command->execute();
} catch (Exception $e) {
// getText() will print the query with the binding params
// getAttributes() will give you the attributes injected
var_dump($command->getText());
var_dump($model->getAttributes());
die();
}
The result will look like:
"INSERT INTO `fruit` (`order`, `name`, `season`) VALUES (:yp0, :yp1,:yp2)"
array(2) {
["order"] => int(1),
["name"] => null,
["season"] => null
}

Function returns string on first call, and an object on subsequent calls

I'm a little bit baffled by this, so I'm hoping someone can shed some light on it for me.
I have a function which is meant to return a column Status from one of my tables, visit.
function someFunction($visitId = null) {
$visit = VisitQuery::create()
->select(array('Status'))
->findPk($visitId);
}
If I var_dump($visit), when calling the function for the first time, it outputs:
string '1' (length=1)
Subsequent, identical calls to the function however seem to return an entire object:
object(Visit)[30]
protected 'startCopy' => boolean false
protected 'id' => int 362
protected 'job_id' => int 351
protected 'company_id' => int 2
protected 'type_id' => int 1
protected 'visit_date' => string '2013-08-23 00:00:00' (length=19)
protected 'status' => string '1' (length=1)
...
I'm calling the function for the first time with an (int) $visitId passed via a posted form:
var_dump($visitId); // int 362
Subsequent calls are made with an (int) $visitId which is returned from another function, saveVisit() (which uses Propel to save the record - I believe this may have something to do with it).
$visitId = saveVisit($visitId);
var_dump($visitId); // int 362
I tried to do some debugging, and for some reason the query issued to MySQL is different between the first function call and subsequent ones:
var_dump($con->getLastExecutedQuery());
SELECT visit.STATUS AS "Status" FROM `visit` WHERE visit.ID=362 // 1st call
SELECT `ID`, `JOB_ID`, `COMPANY_ID`, `TYPE_ID`, `VISIT_DATE`, `STATUS`, `REMIND`, `PRINTED` FROM `visit` WHERE `ID` = 362 // 2nd call
SELECT `ID`, `JOB_ID`, `COMPANY_ID`, `TYPE_ID`, `VISIT_DATE`, `STATUS`, `REMIND`, `PRINTED` FROM `visit` WHERE `ID` = 362 // 3rd call
Can anyone tell me why or how this is happening?
I'm using Propel 1.6.
Propel's create() method:
public static function create($modelAlias = null, $criteria = null)
{
if ($criteria instanceof VisitQuery) {
return $criteria;
}
$query = new VisitQuery();
if (null !== $modelAlias) {
$query->setModelAlias($modelAlias);
}
if ($criteria instanceof Criteria) {
$query->mergeWith($criteria);
}
return $query;
}
Propel's findPk() method:
public function findPk($key, $con = null)
{
if ($con === null) {
$con = Propel::getConnection($this->getDbName(), Propel::CONNECTION_READ);
}
// As the query uses a PK condition, no limit(1) is necessary.
$this->basePreSelect($con);
$criteria = $this->isKeepQuery() ? clone $this : $this;
$pkCols = $this->getTableMap()->getPrimaryKeyColumns();
if (count($pkCols) == 1) {
// simple primary key
$pkCol = $pkCols[0];
$criteria->add($pkCol->getFullyQualifiedName(), $key);
} else {
// composite primary key
foreach ($pkCols as $pkCol) {
$keyPart = array_shift($key);
$criteria->add($pkCol->getFullyQualifiedName(), $keyPart);
}
}
$stmt = $criteria->doSelect($con);
return $criteria->getFormatter()->init($criteria)->formatOne($stmt);
}
My function to retrieve the visit status:
function getVisitStatus($visitId = null) {
if (empty($visitId)) {
return false;
}
try {
$visit = VisitQuery::create()
->select(array('Status'))
->findPk($visitId);
} catch (Exception $e) {
echo $e->getMessage(); exit;
}
if (is_null($visit)) {
return false;
}
return $visit;
}
The function which saves a visit record:
function saveVisit($data = null) {
if (empty($data)) {
return false;
}
try {
$visit = (!empty($data['visit_id'])) ? VisitQuery::create()->findPk($data['visit_id']) : new Visit();
if (!is_object($visit)) {
return false;
}
$visitDataMap = array(
'JobId' => 'job_id',
'TypeId' => 'type_id',
'VisitDate' => 'visit_date',
'Status' => 'status',
'CompanyId' => 'engineer_id',
'Remind' => 'remind'
);
$visitData = array();
foreach ($visitDataMap as $column => $value) {
if (!empty($data[$value])) {
$visitData[$column] = $data[$value];
}
}
$visit->fromArray($visitData);
$visit->save();
return $visit->getId();
} catch (PropelException $e) {
echo $e->getMessage(); exit;
}
}
It seems that on the first call will grab your data but then put a copy of the full object in to the instance pool. I am not sure if this is a bug or valid behaviour (your code would suggest the former, but I'd love to hear from someone who knows more about Propel such as a dev) but you can stop it happening with:
VisitPeer::clearInstancePool();
Bear in mind you're losing a bit of caching from other queries you might have done here with the visit relation.
You will be able to confirm this by adding an echo in the BaseVisitPeer.php file. You will see something like this:
public static function getInstanceFromPool($key)
{
if (Propel::isInstancePoolingEnabled()) {
if (isset(VisitPeer::$instances[$key])) {
return VisitPeer::$instances[$key];
}
}
return null; // just to be explicit
}
If you add an echo somewhere inside the if (isset(VisitPeer::$instances[$key])) { statement, you should see it appear only after the second and subsequent calls. If you were to comment this whole if statement out then you would get the same result back each time - the one you correctly get back from your original call.
Hope that helps!

Best practice for returning "error" from a function

I have a function:
public function CustomerRating() {
$result = $db->query("...");
$row = $result->fetch_assoc();
if($row)
$output = $row['somefield'];
} else {
$output = "error";
}
return $output;
}
//somewhere on another page...
if(is_numeric($class->CustomerRating()) {
echo $class->CustomerRating;
} else {
echo "There is an error with this rating.";
}
Is there a better way to find errors? In this function, if no rows are returned, it doesn't mean an "error" per se, it simply means the value can't be calculated. When I check for the result of a function, I feel like there is a better way to check the data being returned before I display it in the if function. What's the best way to do this? I'd like to return a "false", but how would I check for that when calling the function? Thanks!
There are (in my opinion) 2 common ways:
Returning false
Many builtin PHP functions do that
Using SPL exceptions
Evolved PHP frameworks (Symfony2, ZF2, ...) do that
You need exceptions:
public function CustomerRating() {
$result = $db->query("...");
$row = $result->fetch_assoc();
if ($row !== null) {
return $row['somefield'];
} else {
throw new Exception('There is an error with this rating.');
}
}
// Somewhere on another page...
try {
echo $class->CustomerRating();
} catch (Exception $e) {
echo $e->getMessage();
}
Use exceptions. Avoid returning errors from functions and methods
Although returning false to indicate an error is prevalent in PHP libraries, there are several drawbacks:
you can not return a description about the error
if the false value is a valid return value of the function, then you can not use this approach
Another approach I see in my job is to return an array with both the normal result and the possible error, basically returning a pair, but then to get the real result you have to retrieve it from the array which is more unpleasant code to write
Exceptions are a full fledged solution to this problem but it's a bit cumbersome to write the try...catch block for simple errors. For a function that's documented to throw an exception, if you don't catch the exception when you call it, PhpStorm will complain about that, so in my opinion exceptions are better reserved for more severe errors
One way to return both the result and a possible error is to use a pass by reference parameter, which is used a lot in Objective C
/**
* get element from array
* #param $index int
* #param $list array
* #param $error object
*/
function getFromArray($index, $list, &$error=null) {
if ($index >= 0 && $index < count($list)) {
return $list[$index];
}
$error = "out of index";
return null;
}
$list = ['hello', 'world'];
$error = null;
$result = getFromArray(-1, $list, $error);
if ($error) {
echo "an error occurred " . $error;
} else {
echo $result;
}
if you don't care about the error, you can just call the function leaving out the error parameter
echo getFromArray(0, $list);
I would use exceptions - Saves on the confusion.
the best way to deal with errors is to throw an exception. that way you can have all kinds of different errors and handle them accordingly.
you can then just do:
try {
$myvar = CustomerRating();
//do something with it
} catch (Exception $e) {
echo $e->getMessage();
}
Try this out:
public function CustomerRating() {
$result = $db->query("...");
$row = $result->fetch_assoc();
if($row){
$output = $row['somefield'];
} else {
$output = false;
}
return $output;
}
//somewhere on another page...
if($class->CustomerRating() !== false) {
echo $class->CustomerRating();
} else {
echo "There is an error with this rating.";
}
This will make sure that it won't break if you return a zero.

Categories