not able to json_encode PDO result - pdo

I can't json_encode my array returned from PDO:
var_dump(json_encode($result)); returns false
I have also reassigned this array to a new array, looping through the PDO result.
Here is my code:
$host = "localhost";
$database = "test";
$username = "root";
$password = "";
$db = new PDO("mysql:host={$host};port:3306;dbname={$database}", $username, $password);
!$db && exit("Database connect failed");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $db->prepare("SELECT sample.* FROM test.sample LIMIT 10");
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
var_dump(json_encode($result));

I've found the same problem, found out that the $result itself is error/false.
you should check the content of your $result, using
print_r($result);
if it is so (still false), you should your database coneection or your syntax query.

Related

Get output parameter from procedure Phalconphp

My Code :
$item = new Items2;
$connection = $item->getReadConnection();
$sql = "CALL `OLViewItemsListViewAllWithCount`('','','',0,0,0,0,0,0,0,'2018-05-15',0,0,10,#aa);";
$items = new Resultset(null,$robot,$connection->query($sql));
i need to get the #aa from this Result as a output parameter
how can i get it ?
Need to select out parameters in second query like..
$item = new Items2;
$connection = $item->getReadConnection();
$sql = "CALL `OLViewItemsListViewAllWithCount`('','','',0,0,0,0,0,0,0,'2018-05-15',0,0,10,#aa);";
$items = $robot,$connection->query($sql)->fetchAll(\Phalcon\Db::FETCH_ASSOC);;
$sql2 = "SELECT #aa";
$aa = $connection->query($sql2)->fetch();
echo $aa['#aa];

Retrieving a int value from database

I am trying to get sender_id and receiver_id into my variables but it is giving me following error
Warning: mysql_fetch_array() expects parameter 1 to be resource,
object given in /opt/lampp/htdocs/Task/php/insertdatanew.php on line
36
Warning: mysql_fetch_row() expects parameter 1 to be resource, object
given in /opt/lampp/htdocs/Task/php/insertdatanew.php on line 42 N
CODE:
<?php
$sender_id = 0;
$receiver_id = 0;
session_start();
if(isset($_SESSION['login_user'])) {
//header('location: chat.php');
}
else {
header('location: chatlogin.php');
}
if(isset($_REQUEST['sender']) AND isset($_REQUEST['msg']) AND isset($_REQUEST['time']) AND isset($_REQUEST['receiver']) ){
$msg = $_REQUEST['msg'];
$time = $_REQUEST['time'];
$sender = $_REQUEST['sender'];
$receiver = $_REQUEST['receiver'];
echo $sender;
echo $receiver;
echo $msg;
echo $time;
//echo $msg;
if ( empty($_REQUEST['msg']) ) {
}
else{
require_once 'dc_chat.php';
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$result = $mysqli -> query("SELECT id from users where username LIKE '{$sender}'");
$row = mysql_fetch_row($result);
$sender_id = $row[0];
$result = $mysqli -> query("SELECT id from users where username LIKE '{$receiver}'");
$row = mysql_fetch_row($result);
$receiver_id = $row[0];
//echo $receiver_id;
$sql = $mysqli -> query("INSERT INTO `messages` (`sender_id`, `receiver_id`, `msg`, 'chattime') VALUES ('{$sender_id}', '{$receiver_id}', '{$msg}' ,'{$time}')");
if(! $sql ) {
echo 'N';
}
else {
echo 'Y';
}
}
}
else{
echo "hello";
}
?>
I am getting $msg, $time, $sender, $receiver from a ajax and datatype is JSON
You are mixing mysql and mysqli functions. mysql_fetch_row should probably be mysqli_fetch_row.
Replace if (!$sql) with if ($mysqli->affected_rows == 0) to test for success on the INSERT statement.
If you suspect an error in your SQL statement use echo $mysqli->error; after your query line to put that on the screen.

Why does CGridView fail to filter if we use `$criteria->condition` and/or `$criteria->params`?

I have the following:
public function search() {
$criteria = new CDbCriteria();
$criteria->compare('id',$this->id);
$criteria->compare('entity_id',$this->entity_id);
$criteria->compare('name',$this->name,true);
(etc...)
if (Yii::app()->user->role == SiteUser::ROLE_AUTHOR) {
$userId = Yii::app()->user->getId();
$entity = Entity::model()->find("user_id = $userId");
$criteria->condition = 'entity_id=:entity_id';
$criteria->params = array(':entity_id'=>$entity->id);
}
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
When I apply this:
if (Yii::app()->user->role == SiteUser::ROLE_AUTHOR) {
$userId = Yii::app()->user->getId();
$entity = Entity::model()->find("user_id = $userId");
$criteria->condition = 'entity_id=:entity_id';
$criteria->params = array(':entity_id'=>$entity->id);
}
the user can only see on CGridView is own records. Nice.
But, for some reason, the filter doesn't work.
If I comment those lines:
$criteria->condition = 'entity_id=:entity_id';
$criteria->params = array(':entity_id'=>$entity->id);
The filter works. But, obviously, the user will see ALL users records.
Update:
If instead of using condition and params properties I use compare() method, like this:
$criteria->compare('entity_id',$entity->id);
It works.
Why does it work with compare, and NOT with condition and params?
When you use this
if (Yii::app()->user->role == SiteUser::ROLE_AUTHOR) {
$userId = Yii::app()->user->getId();
$entity = Entity::model()->find("user_id = $userId");
$criteria->condition = 'entity_id=:entity_id';
$criteria->params = array(':entity_id'=>$entity->id);
}
what happens is the condition property is reset (due to the fresh assignment), the compare function you have used earlier appends the comparison to the the condition see http://www.yiiframework.com/doc/api/1.1/CDbCriteria#compare-detail for information on how this works, therfore when you do a fresh assignment it clears all the existing conditions.
Therefore Either you can use a new criteria object like below
if (Yii::app()->user->role == SiteUser::ROLE_AUTHOR) {
$userId = Yii::app()->user->getId();
$entity = Entity::model()->find("user_id = $userId");
$criteria2= new CDbCriteria();
$criteria2->condition = 'entity_id=:entity_id';
$criteria2->params = array(':entity_id'=>$entity->id);
$criteria->mergeWith($criteria2);
}
or you can move the logic for SiteUser::ROLE_AUTHOR before the compare statements

Get raw sql from Phalcon query builder

Is it possible to extract raw sql query from the query builder instance in Phalcon? Something like this?
$queryBuilder = new Phalcon\Mvc\Model\Query\Builder();
$queryBuilder
->from(…)
->where(…);
$rawSql = $queryBuilder->hypotheticalGetRawQueryMethod();
By error and trial the below seems to working. Would be great if someone could confirm if there's a better way.
$queryBuilder = new Builder();
$queryBuilder->from(…)->where(…);
$intermediate = $queryBuilder->getQuery()->parse();
$dialect = DI::getDefault()->get('db')->getDialect();
$sql = $dialect->select($intermediate);
Edit: As of 2.0.3 you can do it super simple, see comment for full details:
$modelsManager->createBuilder()
->from('Some\Robots')
->getQuery()
->getSql()
you can use getRealSqlStatement() (or similar function name) on the DbAdapter. See http://docs.phalconphp.com/en/latest/api/Phalcon_Db_Adapter.html
According to documentation you can get this way the resulting sql query.
Or wait, this might not work on querybuilder. Otherwise you can setup low level query logging: http://docs.phalconphp.com/en/latest/reference/models.html#logging-low-level-sql-statements
$db = Phalcon\DI::getDefault()->getDb();
$sql = $db->getSQLStatement();
$vars = $db->getSQLVariables();
if ($vars) {
$keys = array();
$values = array();
foreach ($vars as $placeHolder=>$var) {
// fill array of placeholders
if (is_string($placeHolder)) {
$keys[] = '/:'.ltrim($placeHolder, ':').'/';
} else {
$keys[] = '/[?]/';
}
// fill array of values
// It makes sense to use RawValue only in INSERT and UPDATE queries and only as values
// in all other cases it will be inserted as a quoted string
if ((strpos($sql, 'INSERT') === 0 || strpos($sql, 'UPDATE') === 0) && $var instanceof \Phalcon\Db\RawValue) {
$var = $var->getValue();
} elseif (is_null($var)) {
$var = 'NULL';
} elseif (is_numeric($var)) {
$var = $var;
} else {
$var = '"'.$var.'"';
}
$values[] = $var;
}
$sql = preg_replace($keys, $values, $sql, 1);
}
More you can read there
The following is the common solution:
$result = $modelsManager->createBuilder()
->from(Foo::class)
->where('slug = :bar:', ['bar' => "some-slug"])
->getQuery()
->getSql();
But you might not expect to see the query without its values, like in:
die(print_r($result, true));
Array
(
[sql] => SELECT `foo`.`id`, `foo`.`slug` FROM `foo` WHERE `foo`.`slug` = :bar
[bind] => Array
(
[bar] => some-slug
)
[bindTypes] =>
)
So, this simple code might be useful:
public static function toSql(\Phalcon\Mvc\Model\Query\BuilderInterface $builder) : string
{
$data = $builder->getQuery()->getSql();
['sql' => $sql, 'bind' => $binds, 'bindTypes' => $bindTypes] = $data;
$finalSql = $sql;
foreach ($binds as $name => $value) {
$formattedValue = $value;
if (\is_object($value)) {
$formattedValue = (string)$value;
}
if (\is_string($formattedValue)) {
$formattedValue = sprintf("'%s'", $formattedValue);
}
$finalSql = str_replace(":$name", $formattedValue, $finalSql);
}
return $finalSql;
}
If you're using query builder then like given below then getPhql function can serve the purpose as per phalcon 3.4.4 version.
$queryBuilder = new Builder();
$queryBuilder->from(…)->where(…)->getQuery();
$queryBuilder->getPhql();
if (!function_exists("getParsedBuilderQuery")) {
/**
* #param \Phalcon\Mvc\Model\Query\BuilderInterface $builder
*
* #return null|string|string[]
*/
function getParsedBuilderQuery (\Phalcon\Mvc\Model\Query\BuilderInterface $builder) {
$dialect = Phalcon\Di::getDefault()->get('db')->getDialect();
$sql = $dialect->select($builder->getQuery()->parse());
foreach ($builder->getQuery()->getBindParams() as $key => $value) {
// For strings work fine. You can add other types below
$sql = preg_replace("/:?\s?($key)\s?:?/","'$value'",$sql);
}
return $sql;
}
}
Simple function that im using for debugging.

how to fix update error

i want to update all row's alternativegroups with $id value.
the action getting error: coldchain can not be null.
when i search the db for pk = $a, It's coldchain value is boolen(false). and db is postgresql
how can i set $q->attributes without posting other values?
public function actionUpdate($id){
if (isset($_POST['forms'])){
$arr = explode(',', $_POST['forms']);
foreach ($arr as $a){
$q = MedicineDrugform::model()->findbypk($a);
$q->alternativegroup = $id;
if ($q->save()){
echo $q->id."q saved <br />";
}
else {
echo "<pre>";
print_r($q->getErrors());
}
die();
$qu = MedicineDrugformUpdate::model()->findbyattributes(array('drug_form_id'=>$a));
$quu = MedicineDrugformUpdate::model()->findbypk($qu->id);
$quu->alternativegroup = $id;
if ($quu->save()){
echo $quu->id."qu saved <br />";
}
}
die();
$this->render('/site/messages', array('message'=>'formsaved'));
}
$this->render('add', array('id'=>$id));
}
maybe it cant find the corresponding record for
$q = MedicineDrugform::model()->findbypk($a);