Selecting number from SQL Server adds .0 - json

When I select a column in SQL Server and then print it, 3 becomes 3.0.
This is my connection:
$sql = new PDO("sqlsrv:Driver=$driver;server=$server,$port;Database=$database;ConnectionPooling=0", $uid, $pwd,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
This is my SELECT:
$sth = $sql->prepare("SELECT column FROM table
WHERE column2 = :value2");
$params = array(':value2' => $_POST['value2']);
$sth->execute($params);
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
echo json_encode($result);
In SQL Server database: 3
In echo: 3.0
What can be the reason for adding .0?

Related

Symfony passing custom sql parameters in the query

I am trying to pass table name and column name from String to the sql query, but for some reason it doesnt work.
This is an example of what am trying to do from symfony 4.4 documentation :
This is how I am trying to do it :
$sql = "SELECT
:col,
COUNT(*) AS `cnt`
FROM
:tab
GROUP BY
:col
";
$stmt = $conn->prepare($sql);
$stmt->execute([ 'col' => $col , 'tab' => $tab ]);
return $stmt->fetchAllAssociative();
output :
meanwhile, it works like this :
$sql = "SELECT
typeCl,
COUNT(*) AS `cnt`
FROM
client
GROUP BY
typeCl
";
$stmt = $conn->prepare($sql);
$stmt->execute([ 'col' => $col , 'tab' => $tab ]);
return $stmt->fetchAllAssociative();
And I still want to make my table and column parametrable .. is there anyway to do that ??
(It is not about my String values I used dump and die and make sure nothign wrong with that)
This is how i made it work :
$sql = "SELECT ".$col.",
COUNT(*) AS `cnt`
FROM
".$tab."
GROUP BY
".$col."
";
$stmt = $conn->prepare($sql);
$stmt->execute([ 'col' => $col , 'tab' => $tab ]);
return $stmt->fetchAllAssociative();

Getting a raw SQL query with variables in Yii1

Is Yii1 has any native methods to get the raw SQL with variables built?
I try to get a complex query built on a few subqueries using CDbExpression and CommandBuilder. I got this as a result:
SELECT * FROM `news` `t` WHERE id IN (:ycp0, :ycp1, :ycp2, :ycp3, :ycp4) LIMIT 5
The dump of the criteria content:
CDbCriteria Object (
[select] => *
[condition] => id IN (:ycp0, :ycp1, :ycp2, :ycp3, :ycp4)
...
[params] => Array(
[:ycp0] => CDbExpression Object(
[expression] => SELECT id FROM `news` `t` WHERE (rubric=:rb1) AND (:im2 & `im`=:im2) LIMIT 1
[params] => Array(
[:rb1] => 1
[:im2] => 2
)
)
...
)
)
I expected for compiled query string like this:
SELECT * FROM .. WHERE id IN(
(SELECT id FROM .. WHERE .. ORDER BY .. LIMIT 1),
(SELECT id FROM .. WHERE .. ORDER BY .. LIMIT 1)
) ORDER BY .. LIMIT 5
This is what I do in my code
$criteria = new CDbCriteria( ... );
$sql = $this->commandBuilder->createFindCommand($tableName, $criteria)->getText();
$queries[] = new CDbExpression($sql, $criteria->params);
Then I try to combine subqueries to one complex query
$criteria = new CDbCriteria( ... );
$criteria->addInCondition('id', $queries);
And finally, I try to get the result as SQL-query
$sql = $this->commandBuilder->createFindCommand($tableName, $criteria)->getText();
You get the SQL with params, as you have
$sql = $this->commandBuilder->createFindCommand($tableName, $criteria)->getText();
Then get the params enclosed in quotes:
$params = array_map(function($param) { return '"' . $param . '"'; }, $criteria->params);
Finally, replace the pairs:
echo strtr($sql, $params);
You can use enableParamLogging in your db config (boolean). You can set it up so it's used conditionally -- make sure to not use it in production.
'db' => [
'connectionString' => 'mysql:host=' . $dbhost . ';port=' . $dbport . ';dbname=' . $dbname,
'emulatePrepare' => true,
'username' => $db_user,
'password' => $db_pass,
'schemaCachingDuration' => 3600,
'charset' => 'utf8',
'enableProfiling' => $db_profile,
'enableParamLogging' => $db_params,
],
Then you can add 'class'=>'CWebLogRoute' to your log routes if you want to see all the output in your browser. docs
I think you want to do something like this:
$criteria = ...;
$command = $builder->createFindCommand($schema->getTable('name_of_table'), $criteria);
$results = $command->text;
There are few other options to perform the same thing but i will suggest you
should use the following
$results = MyModel::model()->findAllBySql("...");
Or you can prefer the following :
Sub-queries ActiveRecord Yii

Joomla! (with K2) MySql - Error when generating

I dont get it ... I tested a lot but dont get why a SQL error appears ...
In my case I use a function to generate a mysql-query to get all extra-field items from the database (K2 - Component).
It is used like this:
public static function readExtraFields ($fields, $as = 'array') {
if (!is_array($fields)) $fields = json_decode($fields);
$result = array();
$whereId = array();
$allFieldValues = array();
foreach ($fields as $field) {
$whereId[] = "`id`='".$field->id."'";
$allFieldValues[$field->id] = $field->value;
}
$query = "SELECT * FROM `#__k2_extra_fields` WHERE " . implode(" OR ", $whereId);
$queryResult = self::execQuery($query);
[...]
In this method a query will be generated like this (I printed it out)
SELECT * FROM `#__k2_extra_fields` WHERE `id`='1' OR `id`='2'
This is fine. When I execute the methode execQuery with the given query this error appears:
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 '' at line 1 SQL=SELECT * FROM `j7req_k2_extra_fields` WHERE
Thats all ... I dont get it. My method to execute my mysql-query:
public static function execQuery ($query) {
$db = JFactory::getDbo();
$db->setQuery($query);
$result = $db->loadObjectList();
return $result;
}
For testing I printed out the Query (the above) and set $query to the printed query and this runs without any problems like the way it should work ... So the query which is given is right ... what can be the problem ?
Edit 1
In my execQuery method I printed the $db out. This reuslt is given (you can find the query at the bottom of this object)
JDatabaseDriverMysqli Object
(
[name] => mysqli
[nameQuote:protected] => `
[nullDate:protected] => 0000-00-00 00:00:00
[_database:JDatabaseDriver:private] => podopraxis
[connection:protected] => mysqli Object
(
[affected_rows] => 1
[client_info] => mysqlnd 5.0.11-dev - 20120503 - $Id: bf9ad53b11c9a57efdb1057292d73b928b8c5c77 $
[client_version] => 50011
[connect_errno] => 0
[connect_error] =>
[errno] => 0
[error] =>
[error_list] => Array
(
)
[field_count] => 1
[host_info] => localhost via TCP/IP
[info] =>
[insert_id] => 0
[server_info] => 5.6.16
[server_version] => 50616
[stat] => Uptime: 48979 Threads: 1 Questions: 6461 Slow queries: 0 Opens: 163 Flush tables: 1 Open tables: 155 Queries per second avg: 0.131
[sqlstate] => 00000
[protocol_version] => 10
[thread_id] => 203
[warning_count] => 0
)
[count:protected] => 45
[cursor:protected] =>
[debug:protected] =>
[limit:protected] => 0
[log:protected] => Array
(
)
[timings:protected] => Array
(
)
[callStacks:protected] => Array
(
)
[offset:protected] => 0
[options:protected] => Array
(
[driver] => mysqli
[host] => localhost
[user] => root
[password] =>
[database] => podopraxis
[prefix] => j7req_
[select] => 1
[port] => 3306
[socket] =>
)
[sql:protected] => SELECT * FROM `#__k2_extra_fields` WHERE `id`='1' OR `id`='2'
[tablePrefix:protected] => j7req_
[utf:protected] => 1
[errorNum:protected] => 0
[errorMsg:protected] =>
[transactionDepth:protected] => 0
[disconnectHandlers:protected] => Array
(
)
)
It looks like your query fired in execQuery() function is missing the condition statement after "WHERE" clause of query.
Please make sure below part of condition comes in your query:
`id`='1' OR `id`='2'
let me know if I am not getting well about your question?
Also try to post here whole $db object by printing as below:
echo "<pre />";print_r($db);exit;

Zend DB Union Error

I have two query:
$select1 = $this->select()
->from(array('o'=>'table1'), array('*', 'o.field2 AS shared'))
->where('field4= ?', $input);
$select2 = $this->select()
->from(array('i'=>'table2'), array('*', 'ch.field1 AS shared'))
->where('ch.field5= ?', $input);
Both query works successfully. However, it does not work with the following union function even with shared parameter name. How come?
//Merge both query
$selectboth = $this->select()
->union(array($select1, $select2))
->order('shared');
$obj = $this->dbo->fetchRow($selectboth);
I am suspecting my fetchRow is the one causing this error in fetching.
if you have number of column same in both sql so you can ran into this issue:
http://framework.zend.com/issues/browse/ZF-4338
for example:
$select_q1 = $db->select()->...;
$select_q2 = $db->select()->...;
$main_select = $db->select()->union( array( '('.$select_q1 .')', '('.$select_q2 .')' ) );

Two prepared statements on one page - first works, second fails

I'm using MDB2 for prepared statements. I'm using the name-based example from the PEAR MDB2 site as a guide, and this is what I have so far:
$q = '
UPDATE
abc_news
SET
newstitle = :newstitle,
categoryid = :categoryid,
facilityid = :facilityid,
user_id_mod = :user_id_mod,
user_id_add = :user_id_add,
display = :display,
locked = :locked,
datemodified = NOW()
WHERE
newsid = :newsid
';
$types = array(
'text',
'integer',
'integer',
'integer',
'integer',
'integer',
'integer',
'integer',
);
$res = $mdb2_dbx->prepare($q, $types,MDB2_PREPARE_MANIP);
$data = array(
'newstitle' => $n_newstitle,
'categoryid' => $n_categoryid,
'facilityid' => $n_facilityid,
'display' => 1,
'locked' => 1,
'user_id_add' => $n_user_id_add,
'user_id_mod' => $n_user_id_mod,
'newsid' => $newsid,
);
$affected_rows = $statment->execute($data);
if (PEAR::isError($res))
die('error');
$statement->free();
$q = '
UPDATE
abc_news_text
SET
newstext = :newstext
WHERE
newsid = :newsid
';
$types = array(
'text',
'integer',
);
$statment = $mdb2_dbx->prepare($q, $types,MDB2_PREPARE_MANIP);
$data = array(
'newstext' => $n_newstext,
'newsid' => $newsid,
);
$affected_rows = $statment->execute($data);
if (PEAR::isError($res))
die('error');
$statement->free();
The first query works - an autoincremented $newsid is printed to the screen (it increases with each new submission).
Directly below, I get this error:
Fatal error: Call to undefined method MDB2_Error::execute() in news.php on line 160
Line 160 is the second $affected_rows = $statment->execute($data); line.
I'm freeing up the statement, and the syntax appears to be the same on both prepared statements.
What am I doing wrong here?
that is because You are getting an MDB2_ERROR object not a statement object. Your prepare() obviously didn't work and you are not checking for the success of the prepare() at all to know this.
Also, I am not sure how your first is working since you set the prepare result to $res variable instead of $statment. I also notice your variable name $statment has no e (not sure if this was a typo).