Changing the select parameters by calling ->select twice? - database

I had a query:
$query =
Yii::app()->db->createCommand()->setFetchMode(PDO::FETCH_OBJ)
->select('*')
->from('products p')
->limit(5);
And then I got results:
$result = $query->queryAll();
How can I use the existing query object, without rewriting it, to re-instantiate the values for "select" and "limit". I want to change select to "count(p.productid)" and unset limit. I tried the following but it does not work:
$query =
Yii::app()->db->createCommand()->setFetchMode(PDO::FETCH_OBJ)
->select('*')
->from('products p')
->limit(5);
$result = $query->queryAll();
$query =
$query
->select('count(p.productid)')
->limit(-1);
$result2 = $query->queryRow();
This still returns the result of the first select?
EDIT
Basically, I want to RESET the select. It looks like it builds on the select. So, I think you can do this:
$query =
$query->select('something')
->select('somethingElse')
->select('somethingMoreStuff');
My problem is that I want to "reset" the select. So basically UNDO these selects. Is this possible?

Why don't you do:
$intialQuery =
Yii::app()->db->createCommand()->setFetchMode(PDO::FETCH_OBJ)
->from('products p');
$query = $intialQuery
->select('*')
->limit(5);
$query2 = $intialQuery
->select('count(p.productid) as number')
->limit(-1);
$result = $query->queryAll();
$result2 = $query2->queryRow();

Related

Iterate through array of variables passing each one to a function in PowerShell

I have a function that exports the results of a SQL query to a json file:
# Connect to SQL Server
$SqlCommand.CommandText = $Query;
$SqlCommand.Connection = $SqlConnection;
# Execute query and get the result back
$QueryResult = $SqlCommand.ExecuteReader()
# Hold query result in data table
$QueryTable = New-Object "System.Data.DataTable"
$QueryTable.Load($QueryResult)
# Export query results to json
$QueryTable | Select-Object $QueryTable.Columns.ColumnName | ConvertTo-Json | Out-File "$OutputDirectory\$SqlInstance-$QueryName.json"
And I have multiple queries that I want to execute and have created variables for each one:
$q1 = "SELECT blah"
$q2 = "SELECT more blah"
$q3 = "SELECT even more blah"
I call the function by:
ExportQueryResultsToJson -Query $q1 -QueryName "q1"
I have around 80 queries that I want to execute so instead of having 80 lines of ExportQueryResultsToJson ... I want to use ForEach. I've created an array of variables:
$SqlServer2012QueryArray = #(
$q1,
$q2,
$q3
)
I've tried many variations of the following:
foreach ($Query in $SqlServer2012QueryArray) {
$Expression = "ExportQueryResultsToJson -Query '$Query' -QueryName $Query"
Invoke-Expression $Expresion
}
And I've tried using a splat but I can't figure out how to pass all queries in correctly.
What am I doing wrong?
You can approach this in a number of ways. Three possible ways, which are all very algorithmically similar, are below:
Using Your Array:
The solution depends on your array $sqlserver2012QueryArray having a list of sequentially numbered variables in the format q<number>. The first variable name must be q1.
for ($i = 0; $i -lt $sqlserver2012QueryArray.Count; $i++) {
ExportQueryResultsToJson -Query $sqlserver2012QueryArray[$i] -QueryName $((Get-Variable "q$($i+1)").Name)
}
Querying Already Created Variables:
This solution relies on your variables being named in the format q<number>. They do not have to be sequentially named. It could capture unwanted variables if they are named like q<number>abc.
foreach ($var in (Get-Variable -Name q[0-9]*)) {
ExportQueryResultsToJson -Query $var.Value -QueryName $var.Name
}
Using a Hash Table:
You can create a hash table with each key name being your variable name and the associated value being the query string. You can bypass creating the query variables all together with this solution by just inputting the query strings as the values.
$queryhash = #{'q1' = $q1; 'q2' = $q2; 'q3' = $q3; 'q14' = $q14}
foreach ($var in $queryhash.GetEnumerator()) {
ExportQueryResultsToJson -Query $var.Value -QueryName $var.Key
}
Note: In all cases, you should try to avoid Invoke-Expression. It is not generally a safe command to use because it welcomes code injection. I also don't see why it is necessary at all in this case either.

Looping through pscustomobject dataset and add to a SQL DB

I have a variable, $CiscoCMDB, which holds data for 2968 records like this (some fields are all filled, some are not like below):
SearchCode: D12345678911
Name1: 1212
Category: Office Phone
AssetTag:
Status: Stock
SerialNumber: FCH1549BBBB
Model: CISCO IP PHONE 7945G
MacAddress:
Location: SF
OwnerOrganization:
OwnerPerson:
I also have a SQL DB created, CiscoCMDB, with the same name for the columns that are present for the rows. I would like All records to be written to the SQL table. I've tried to use the Write-Datatable cmdlet, but it gave me errors. along with other CMDlets. I figured, if I am using SQL SELECT statements in my code, I should just use SQL INSERTs in my code. Only problem is, I'm not sure how to go about this other than knowing I will need a foreach loop to loop through.
Can someone help me on this as I'm getting confused and frustrated. I'm not exactly sure how to go about looping through correctly.
Pull data from another SQL DB
Organize data furthur (picking the columns I want)
Manipulate data to strip ^C from searchcode (all our search codes are prefaced with C)
Manipulate data to strip ^DN from Name1 field (again all Name1s are prefaced with DN)
Fill in my data
$CMDBCiscoQuery = #()
foreach ($row in $table) {
$hash = [ordered]#{
'SearchCode' = $row.SearchCode
'Category' = $row.Category
'Status' = $row.Status
'Name1' = $row.Name1
'SerialNumber' = $row.SerialNumber
'Model' = $row.Model
'MacAddress' = $row.MacAddress
'Location' = $row.Location
'OwnerOrg' = $row.OwnerOrganization
'Owner' = $row.OwnerPerson
}
$obj = New-Object -TypeName PSObject -Property $hash
$CMDBCiscoQuery+= $obj
$CMDBCisco = $CMDBCiscoQuery |
Select #{n='SearchCode';e={$_.Searchcode -replace "^C"}},
#{n='Name1';e={$_.DN -replace "^DN"}}, Category, AssetTag,
Status, SerialNumber, Model, MacAddress, Location,
OwnerOrganization, OwnerPerson
#Filling CMDB table
Write-Verbose "Filling CMDBCisco Table"
$ConnectionTimeout = 30
$ServerInstance = "myserver"
$Database = "Audits"
$conn = New-Object System.Data.SqlClient.SQLConnection
$ConnectionString = "Server={0};Database={1};Connect Timeout={2};Integrated Security = True;" -f $ServerInstance,$Database,$ConnectionTimeout
$conn.ConnectionString = $ConnectionString
$conn.Open()
$cmd = New-Object System.Data.SqlClient.SqlCommand($conn);
$conn.Close()

How to fetch and display an array using PDO?

I understand there are MANY ways to do all of this, but trying to do it the best way.
I have created the db parameters, dns, dbh, sth, sql and generally quite happy with the result up to ... well ... the result part.
<?php
// db parameters
$dbhost = "localhost";
$dbname = "x";
$dbuser = "y";
$dbpass = "z";
// driver invocation (dsn is short for data source name)
$dsn = "mysql:host=$dbhost;dbname=$dbname";
// create db object (dbh is short for database handle)
$dbh = new PDO($dsn, $dbuser, $dbpass);
// execution of database query (sth is short for statement handle)
$sql = "SELECT * FROM a_aif_remaining";
$sth = $dbh->prepare($sql);
$sth->execute();
NOT SURE WHAT TO PUT BELOW.... (A) or (B)
I just want to present a simple array of the data. One row from the table per line.
Option A
echo $_POST['fieldname1'];
echo $_POST['fieldname2'];
echo $_POST['fieldname3'];
Option B
while ($rows = $sth->fetch(PDO::FETCH_ASSOC)) {
echo $row[fieldname1],'<br>';
}
AND I AM CONFIDENT WITH THE ENDING
$dbh = NULL;
?>
Any advise would be GREATLY appreciated.
UPDATED CODE: (Produces nothing on the page)
<?php
// db parameters
$dbhost = "localhost";
$dbname = "theaudit_db1";
$dbuser = "theaudit_user";
$dbpass = "audit1999";
$dsn = "mysql:host=$dbhost;dbname=$dbname"; // driver invocation (dsn is short for Data Source Name)
try {
$dbh = new PDO($dsn, $dbuser, $dbpass); // connect to new db object (dbh is short for Database Handle)
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // set the PDO error mode to enable exceptions
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // set the PDO emulate prepares to false
// execute query to database (sth is short for Statement Handle)
$sql = "SELECT * FROM a_aif_remaining";
$sth = $dbh->prepare($sql);
$sth->execute();
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
$dbh = NULL;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Though I can't get what's the connection between A anb B, I can answer the
I just want to present a simple array of the data. One row from the table per line.
question.
$sql = "SELECT * FROM a_aif_remaining";
$sth = $dbh->prepare($sql);
$sth->execute();
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
where $data is a sought-for array.
The problem with your updated code is simple - you arent echo'ing your data out. You need to add something like..
foreach($data as $arKey=>$dataRow){
foreach($dataRow as $arKey=>$rowField){
echo $rowField.','; //concat with a ',' to give csv like output
}
echo '<br>'; //to get to next line for each row (may want to trim the last ','
}
I am also confused by the reference to $_POST. It is true both are associate arrays but that does not mean that the $_POST option is viable - the data would only be available in the $_POST if you put it there (eg $_POST = $data) which would be pointless. Or if you had posted the data from somewhere else. Neither seem to fit what you are asking so I would forget about the $_POST and just figure out how you access your multi dimensional $data array. There is endless tut's on this subject. Try using
var_dump($data)
to see whats inside that should help you visualise what is going on.
NOTE: in option B you are not correctly concatenating or referencing your array it should be:
while ($rows = $sth->fetch(PDO::FETCH_ASSOC)) {
echo $rows[fieldname1].'<br>'; //$row doesnt exist its $rows and you use . to concat not ,
}
Ah yes and probably better to use unset rather than setting $dbh to equal null
unset($dbh);

Database query to get decimal value in Joomla 2.5

I'm trying to make a query to a database in Joomla 2.5. I have a db named 'example', and I'm trying to get certain value named 'value' (very original) for a user whose id is 949:
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$user = 949;
$db->setQuery( 'SELECT value FROM example WHERE user_id = ' . $user );
$result = $db->loadObjectList();
echo $result;
However, I'm just getting 'Array' as result (the expected value is a decimal, e.g. 4.5).
Could someone please tell me what am I doing wrong?
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$user = 949;
$db->setQuery( "SELECT value FROM example WHERE user_id = '" . $user."'" );
$result = $db->loadObjectList();
echo $result;
try this one
$db->loadObjectList() returns an array of objects, which echo can't display. If you want to just return one value from one row, user $db->loadResult() instead.

How to create select list with field_create_field($field) drupal 7 with options

How to create select list, radio buttons, checkboxes with field_create_field() and how to specify the options to be given in these fields
Run this code with the details for an existing field with the properties that you want to copy:
$entity_type = 'node';
$field_name = 'body';
$bundle_name = 'article';
$info_config = field_info_field($field_name);
$info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
unset($info_config['id']);
unset($info_instance['id'], $info_instance['field_id']);
include_once DRUPAL_ROOT . '/includes/utility.inc';
$output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
$output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
drupal_set_message("<textarea rows=30 style=\"width: 100%;\">". $output .'</textarea>');
That will produce the PHP code used to create the field/field instance. Then you just need to go through the code and make the changes for your new field/instance.

Resources