Doctrine2 Iteration - doctrine-orm

I have the following code for a <select> on a form.
$query = $em->createQuery("SELECT g.name, g.id FROM SSMURBS\Group g ORDER BY g.name ASC");`
$groups = $query->iterate();`
$groups_option = "";
foreach( $groups as $row ){
$group = $row[0];
$groups_option .= "<option val=\"{$group['id']}\">{$group['name']}</option>\n";
}
But this throws an error. What works is...
$query = $em->createQuery("SELECT g.name, g.id FROM SSMURBS\Group g ORDER BY g.name ASC");
$groups = $query->iterate();
$groups_option = "";
$i = 0;
foreach( $groups as $row ){
$group = $row[$i];
$groups_option .= "<option val=\"{$group['id']}\">{$group['name']}</option>\n";
$i++;
}
Am I doing something wrong? The reference manual cites the first option as correct...

I found the answer to my own question:
While DQL permits SELECT g.id, g.name without throwing an error, this is actually SQL, not DQL. (Thanks, doctrine reference manual, for being so clear on this...)
The correct way to code this is
$query = $em->createQuery("SELECT partial g.{id,name} FROM SSMURBS\Group g ORDER BY g.name ASC");
$groups = $query->iterate();
$groups_option = "";
foreach( $groups as $group ){
$group = $group[0];
$groups_option .= "<option value=\"{$group->id}\">{$group->name}</option>\n";
}

Your variable names are mismatched.
Remove $group = $row[0] and use foreach ($groups as $group)
$query = $em->createQuery("SELECT g.name, g.id FROM SSMURBS\Group g ORDER BY g.name ASC");
$groups = $query->iterate();
$groups_option = "";
foreach ( $groups as $group ){
$groups_option .= "<option val=\"{$group['id']}\">{$group['name']}</option>\n";
}

Related

Export data from SP 2013 list to SQL database with comment versions

I'm trying to figure out a way to get comments from all item versions into one column in a sql table and view, but still unsuccessful.
I have listed the script I wrote below, but I can't add comments to it. Second script is light foreach loop which get comments history and add in new column in item, but this is not good solution if you have more than 10 000 items in SharePoint 2013 list.
Add-pssnapin microsoft.sharepoint.powershell
cls;
# env settings
#$env = "https://sharepoint.com/"
#$sqlConnectionString = "Server=servername\servername;Database=Database;User Id=UserID;Password=UserPassword;Timeout=15"
# settings
$webUrl = "$env"
$fromListUrl = "Lists/Name"
$fromViewName = "Sharepoint list view"
$targetTableName = "Target SQL table"
$targetViewName = "Target SQL View"
$targetPrimaryKey = "DBID"
$sourcePrimaryKey = "ID"
# script internal settings
$sqlDropTable = "DROP TABLE IF EXISTS [dbo].[{TABLENAME}]"
$sqlCreateTable = "IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[{TABLENAME}]') AND type in (N'U')) BEGIN CREATE TABLE [dbo].[{TABLENAME}]( [{PRIMARYKEY}] [int] IDENTITY(1,1) NOT NULL, CONSTRAINT [PK_{TABLENAME}_{PRIMARYKEY}] PRIMARY KEY CLUSTERED ([{PRIMARYKEY}] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY] END"
$sqlCreateColumn = "IF COL_LENGTH('{TABLENAME}', '{COLUMN}') IS NULL BEGIN ALTER TABLE [dbo].[{TABLENAME}] ADD [{COLUMN}] {TYPE} END "
$sqlSelect = "SELECT $targetPrimaryKey,$sourcePrimaryKey FROM [dbo].[$targetTableName]"
$sqlInsert = "INSERT INTO [dbo].[$targetTableName]({COLUMNS}) VALUES ({VALUES})"
$sqlUpdate = "UPDATE [dbo].[$targetTableName] SET {COLUMNVALUES} WHERE [$sourcePrimaryKey] = {IDVALUE}"
$sqlCreateView = "IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[{VIEWNAME}]')) EXEC dbo.sp_executesql #statement = N'CREATE VIEW [dbo].[{VIEWNAME}] AS SELECT {COLUMNS} FROM [dbo].[{TABLENAME}]' "
$sqlDropView = "DROP VIEW IF EXISTS [dbo].[{VIEWNAME}]"
$commit = $true # false to dont make changes in shp (folders creation, files upload, log items)
$recreate = $false # true will erase target table and create new
# script variables
$wasError = $false # flag to see if script encountered any error
$connection = $null
function GetColumnFromField($field, $row)
{
$name = $field.InternalName
if([string]::IsNullOrEmpty($fieldTitle))
{
$name = $field.InternalName
}
if(($field.Type -eq "User" -or $field.Type -eq "Lookup") -and $field.hidden -eq $false)
{
$value1 = [DBNull]::Value
$value2 = [DBNull]::Value
if($row -ne $null)
{
$value = $row[$field.internalname]
if([string]::IsNullOrEmpty($value) -eq $false)
{
try
{
$lookup = New-Object Microsoft.SharePoint.SPFieldLookupValue($value)
$value1 = $lookup.LookupId
$value2 = $lookup.LookupValue
if ($value1 -eq $null) { $value1 = 0 }
if ($value2 -eq $null) { $value2 = [DBNull]::Value }
}
catch
{
$value1 = 0
$value2 = $value
}
}
}
$cols = #()
$cols += ,#("$($name)_ID", "int", $value1, "$($field.Title) ID")
$cols += ,#("$($name)_Value", "nvarchar(255)", $value2, "$($field.Title)")
return ,$cols
}
$type = "NVARCHAR(MAX)"
if($field.Type -eq "Integer" -or $field.Type -eq "Counter")
{
$type = "int"
}
elseif($field.Type -eq "Number")
{
$type = "float"
}
elseif($field.Type -eq "DateTime")
{
$type = "datetime"
}
elseif($field.Type -eq "Boolean")
{
$type = "bit"
}
elseif($field.Type -eq "Guid")
{
$type = "uniqueidentifier"
}
elseif($field.Type -eq "Text" -or $field.Type -eq "Choice")
{
$type = "nvarchar(255)"
}
elseif($field.Type -eq "Note")
{
$type = "nvarchar(MAX)"
}
$value = [DBNull]::Value
if($row -ne $null -and $row[$field.internalname] -ne $null)
{
if($field.Type -eq "Integer")
{
$value = $row[$field.internalname]
}
elseif($field.Type -eq "Number")
{
$value = $row[$field.internalname]
}
elseif($field.Type -eq "DateTime")
{
$value = [System.DateTime]$row[$field.internalname]
}
elseif($field.Type -eq "Boolean")
{
$value = $row[$field.internalname]
}
elseif($field.Type -eq "Guid")
{
$value = $row[$field.internalname]
}
elseif($field.Type -eq "Text")
{
$value = $row[$field.internalname].tostring()
}
elseif($field.Type -eq "Note")
{
$value = $row[$field.internalname].tostring()
}
else
{
$value = $row[$field.internalname].tostring()
}
if ($value -eq $null) { $value = [DBNull]::Value }
}
$cols = #()
$cols += ,#($name,$type,$value,"$($field.Title)")
return ,$cols
}
try
{
# connect to shp
write-host "Started $([DateTime]::Now.ToString()), web: $webUrl, listurl: $fromListUrl, view: $fromViewName, target: $targetTableName"
$web = get-spweb $webUrl
$list = $web.getlist($fromListUrl)
$view = $list.views[$fromViewName]
if (!$?) {throw "Could not open SHP connections."}
write-host "Connected to SHP list: $($list.title)"
# connect to sql
$connection = New-Object System.Data.SqlClient.SqlConnection $sqlConnectionString
$connection.Open()
if (!$?) {throw "Could not open SQL connections."}
write-host "Connected to SQL db: $($connection.Database)"
# recreate target table
if($recreate -eq $true)
{
$dropTableQuery = $sqlDropTable.replace("{TABLENAME}",$targetTableName)
$dropTableCommand = New-Object System.Data.SqlClient.SqlCommand $dropTableQuery, $connection
if($commit)
{
$dropTableCommand.ExecuteScalar()
}
$dropViewQuery = $sqlDropView.replace("{VIEWNAME}",$targetViewName)
$dropViewCommand = New-Object System.Data.SqlClient.SqlCommand $dropViewQuery, $connection
if($commit)
{
$dropViewCommand.ExecuteScalar()
}
}
# ensure target table
$syncTableQuery = $sqlCreateTable.replace("{TABLENAME}",$targetTableName).replace("{PRIMARYKEY}",$targetPrimaryKey)
$syncTableCommand = New-Object System.Data.SqlClient.SqlCommand $syncTableQuery, $connection
if($commit)
{
$syncTableCommand.ExecuteScalar()
}
# ensure sql table columns
$viewColumns = ""
$syncColumnsQuery = $sqlCreateColumn.replace("{TABLENAME}",$targetTableName).replace("{COLUMN}", $sourcePrimaryKey).replace("{TYPE}", "int")
for($c = 0; $c -lt $view.viewfields.count; $c++)
{
$field = $list.fields.getfieldbyinternalname($view.viewfields[$c])
$columns = GetColumnFromField -field $field -row $null
foreach($column in $columns)
{
if($column.internalname -eq "ID")
{
continue
}
write-host "Ensuring column: $($column[0]) - $($column[1])"
$syncColumnsQuery += $sqlCreateColumn.replace("{TABLENAME}",$targetTableName).replace("{COLUMN}", $column[0]).replace("{TYPE}", $column[1])
$viewColumns += "[$($column[0])] as [$($column[3])],"
}
}
$syncColumnsCommand = New-Object System.Data.SqlClient.SqlCommand $syncColumnsQuery, $connection
if($commit)
{
$syncColumnsCommand.ExecuteScalar()
}
write-host "Sql columns ensured"
# ensure sql view
if($false)
{
$createViewQuery = $sqlCreateView.replace("{TABLENAME}",$targetTableName).replace("{VIEWNAME}",$targetViewName).replace("{COLUMNS}", $viewColumns.trimend(','))
$createViewCommand = New-Object System.Data.SqlClient.SqlCommand $createViewQuery, $connection
if($commit)
{
$createViewCommand.ExecuteScalar()
}
}
# read data from sql
$imported = new-object System.Collections.Hashtable
$selectCommandQuery = $sqlSelect
$selectCommand = New-Object System.Data.SqlClient.SqlCommand $selectCommandQuery, $connection
$dr = $selectCommand.ExecuteReader()
if ($dr.HasRows)
{
while ($dr.Read())
{
$key = $dr[$sourcePrimaryKey]
$value = $dr[$targetPrimaryKey]
if($imported.containskey($key) -eq $false)
{
$imported.add($key,$value)
}
}
}
$dr.close()
write-host "Loaded already imported rows: $($imported.count)"
# read data from list
$query = new-object microsoft.sharepoint.spquery
$query.query = $view.Query
$query.ViewAttributes = "Scope='Recursive'";
#$query.RowLimit = 40
$data = $list.getitems($query)
write-host "Loaded sharepoint list items: $($data.count)"
write-host "Processing items count: $($data.count)"
foreach($row in $data)
{
$key = $row[$sourcePrimaryKey]
Write-host "Processing item: $key... " -nonewline
if($imported.containskey($key))
{
Write-host "Row found Sql ID: $($imported[$key])... " -for yellow -nonewline
# generate update query
$updateColumnValues = ""
foreach($fieldInternalName in $view.viewfields)
{
if($fieldInternalName -eq "ID")
{
continue
}
$field = $list.fields.getfieldbyinternalname($fieldInternalName)
$columns = GetColumnFromField -field $field -row $row
foreach($column in $columns)
{
#write-host "Updating value: $($column[0]) - $($column[1]) => $($column[2])"
$updateColumnValues += "[" + $column[0] + "] = #" + $column[0] + ","
}
}
Write-host "UpdateQuery generated... " -nonewline -for green
# execute insert query
$updateCommandQuery = $sqlUpdate.replace("{COLUMNVALUES}", $updateColumnValues.TrimEnd(',')).replace("{IDVALUE}", $key)
$updateCommand = New-Object System.Data.SqlClient.SqlCommand $updateCommandQuery, $connection
# add values to parameters
foreach($fieldInternalName in $view.viewfields)
{
if($fieldInternalName -eq "ID")
{
continue
}
$field = $list.fields.getfieldbyinternalname($fieldInternalName)
$columns = GetColumnFromField -field $field -row $row
foreach($column in $columns)
{
$param = $updateCommand.Parameters.AddWithValue("#" + $column[0], $column[2])
}
}
if($commit)
{
$updateCommand.ExecuteScalar()
}
Write-host "UpdateQuery executed" -for green
}
else
{
# generate insert query with parameters
$insertCommand_Part1 = "[" + $sourcePrimaryKey + "],"
$insertCommand_Part2 = $row[$sourcePrimaryKey].tostring() + ","
foreach($fieldInternalName in $view.viewfields)
{
if($fieldInternalName -eq "ID")
{
continue
}
$field = $list.fields.getfieldbyinternalname($fieldInternalName)
$columns = GetColumnFromField -field $field -row $row
foreach($column in $columns)
{
#write-host "Setting value: $($column[0]) - $($column[1]) => $($column[2])"
$insertCommand_Part1 += "[" + $column[0] + "],"
$insertCommand_Part2 += "#" + $column[0] + ","
}
}
Write-host "InsertQuery generated... " -nonewline -for green
# execute insert query
$insertCommandQuery = $sqlInsert.replace("{COLUMNS}", $insertCommand_Part1.TrimEnd(',')).replace("{VALUES}", $insertCommand_Part2.TrimEnd(','))
$insertCommand = New-Object System.Data.SqlClient.SqlCommand $insertCommandQuery, $connection
# add values to parameters
foreach($fieldInternalName in $view.viewfields)
{
if($fieldInternalName -eq "ID")
{
continue
}
$field = $list.fields.getfieldbyinternalname($fieldInternalName)
$columns = GetColumnFromField -field $field -row $row
foreach($column in $columns)
{
$param = $insertCommand.Parameters.AddWithValue("#" + $column[0], $column[2])
}
}
if($commit)
{
$insertCommand.ExecuteScalar()
}
Write-host "InsertQuery executed" -for green
}
}
}
catch
{
$wasError = $true
write-host "error occured" -for red
write-host "$([system.datetime]::now.tostring(""yyyy.MM.dd_HH.mm.ss.ffff"")) - error: $($_.Exception.Message) in script: $($_.fullname)"
write-host "$([system.datetime]::now.tostring(""yyyy.MM.dd_HH.mm.ss.ffff"")) - error details: $($_.Exception.tostring())"
write-host "$([system.datetime]::now.tostring(""yyyy.MM.dd_HH.mm.ss.ffff"")) - error stack: $($_.ScriptStackTrace)"
write-host "$([system.datetime]::now.tostring(""yyyy.MM.dd_HH.mm.ss.ffff"")) - error position: $($_.invocationinfo.positionmessage)"
}
if($connection -ne $null)
{
$connection.close()
}
if($wasError)
{
write-host "Script encountered error" -for red
}
else
{
write-host "No error occured" -for green
}
write-host "Finished $([DateTime]::Now.ToString())"
Foreach loop to get item versions and comments ->
foreach($item in $items){
foreach($version in $item.Versions)
{
if($item["ID"] -eq $($item.id)){
#$VersionData = "$($version['Odpoved'])"
if($VersionData -ne $null){
if($item['Export_Odpoved'] -ne $version['Odpoved']){
#write-host $version['Odpoved']
#write-host $VersionData.ToString();
$item["Export_Odpoved"] += $version['Odpoved']
#write-host $item["Export_Odpoved"]
$item.SystemUpdate()
write-host $item["ID"] "updated" -ForegroundColor Green
#write-host #$VersionData "||" $item["ID"] "updated" -ForegroundColor Green
} else{write-host "preskakujem ziadost, nakolko je korektne zmigrovana" $item["ID"] -ForegroundColor Yellow}
};
};
};
};
Any suggestions to make it work ? Thanks

powershell System.Collections.Generic.List[System.String] and foreach

I'm finding that I have the following Generic List, and I can see it has items in it, but when I try to run the code, it's not hitting inside the foreach. This is my code:
function SQLQueryWriteToFile([string]$SQLquery, [string]$extractFile)
{
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "Server=blah;Database=blah;User ID=blah;Password=blah" #production #I have an error in this so it doesn't connect
$sqlConnection.Open()
if($sqlConnection.State -ne 'Open'){
$global:ErrorStrings.Add("Exception: $("Couldn't connect to DB with connection string given");; ") #this gets hit
}
###
$global:ErrorStrings = New-Object System.Collections.Generic.List[System.String] #System.Object]
$query = "Select blah"
$dir = "C:\blah"
SQLQueryWriteToFile $query $dir
$errorCodeAsString = ""
foreach ($item in $global:ErrorStrings.Members){
$errorCodeAsString += $item #this isn't hit
}
Any idea why it's not finding the error string in my list for the foreach loop, when I can see it's in there looking at $global:ErrorStrings? Based on this foreach list, I'm doing it correctly. I'm having trouble finding examples like what I'm doing. Thanks!
try this:
function SQLQueryWriteToFile([string]$SQLquery, [string]$extractFile)
{
[System.Data.SqlClient.SqlConnection] $sqlConnection=$null
[System.Data.SqlClient.SqlCommand] $command=$null
try
{
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "Server=blah;Database=blah;User ID=blah;Password=blah"
$command = New-Object System.Data.SqlClient.SqlCommand
$command.Connection=$sqlConnection
$command.CommandText=$SQLquery
$sqlConnection.Open()
$command.ExecuteNonQuery()
}
catch
{
$global:ErrorStrings.Add($_.Exception.Message)
}
finally
{
if ($sqlConnection -ne $null)
{
$sqlConnection.Close()
$sqlConnection.Dispose()
}
if ($command -ne $null)
{
$command.Dispose()
}
}
}
$global:ErrorStrings = New-Object System.Collections.Generic.List[System.String]
$query = "Select blah"
$dir = "C:\blah"
$global:ErrorStrings.Clear()
SQLQueryWriteToFile $query $dir
$errorCodeAsString=""
for ($i = 0; $i -lt $global:ErrorStrings.Count; $i++)
{
$errorCodeAsString +=$global:ErrorStrings.Item($i)
}
$errorCodeAsString

How to make controller opencart function

I have this script for making subdomain and I want to placed it in the opencart contoller. How to do that and how to make it work with the insert function?
$cpanel_user = 'root';
$cpanel_pass = 'password';
$cpanel_skin = 'x2';
$cpanel_host = 'yourdomain.com';
$subdomain = 'mysubdomain';
$dir = 'public_html/mysubdomain';
$sock = fsockopen($cpanel_host,2082);
if(!$sock) {
print('Socket error');
exit();
}
$pass = base64_encode("$cpanel_user:$cpanel_pass");
$in = "GET /frontend/$cpanel_skin/subdomain/doadddomain.html?rootdomain=$cpanel_host&domain=$subdomain&dir=$dir\r\n";
$in .= "HTTP/1.0\r\n";
$in .= "Host:$cpanel_host\r\n";
$in .= "Authorization: Basic $pass\r\n";
$in .= "\r\n";
fputs($sock, $in);
while (!feof($sock)) {
$result .= fgets ($sock,128);
}
fclose($sock);

Error occurs with while Loop PHP / MySQL NuSOAP

I have created a PHP / MySQL based web service. I wrote client.php as mentioned here
and server.php as below:
<?php
require_once("lib/nusoap.php");
$host = $_SERVER['HTTP_HOST'];
$miURL = 'http://'.$host.'/WS-Demo';
$server = new nusoap_server();
$server->configureWSDL('L3M_WebService', $miURL);
$server->wsdl->schemaTargetNamespace=$miURL;
$server->register('getDemoData',
array('fldpara' => 'xsd:Array', 'tblpara' => 'xsd:Array', 'cndpara' => 'xsd:Array'),
array('return' => 'xsd:string'),
$miURL);
function decryptRJ256($string_to_decrypt)
{
$key = 'salt_key - I';
$iv = 'salt_key - II';
$string_to_decrypt = base64_decode($string_to_decrypt);
$rtn = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $string_to_decrypt, MCRYPT_MODE_CBC, $iv);
$rtn = rtrim($rtn, "\4");
return($rtn);
}
function encryptRJ256($string_to_encrypt)
{
$key = 'salt_key - I';
$iv = 'salt_key - II';
$rtn = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $string_to_encrypt, MCRYPT_MODE_CBC, $iv);
$rtn = base64_encode($rtn);
return($rtn);
}
function getDemoData($flds, $tbls, $cnds){
$mysqli = new mysqli("localhost", "root", "", "test");
for($i=0;$i< count($flds); $i++) {
$flds[$i] = decryptRJ256($flds[$i]);
}
for($i=0;$i< count($tbls); $i++) {
$tbls[$i] = decryptRJ256($tbls[$i]);
}
for($i=0;$i< count($cnds); $i++) {
$cnds[$i] = decryptRJ256($cnds[$i]);
}
if(! empty($flds)) {
$what = implode(", ", $flds);
} else {
$what = "*";
}
if(! empty($tbls)) {
$from = implode(", ", $tbls);
}else {
$err = 1;
}
if(! empty($cnds)) {
$cond = " WHERE ";
$cond .= $cnds[0] . " = '" . $cnds[1] . "'";
} else {
$cond = "";
}
$sql = "SELECT ".$what." FROM ".$from . $cond;
$rsGetData = $mysqli->query($sql);
$responseData = '<?xml version="1.0" encoding="UTF-8"?>
<L3MDataSets>';
while($rowGetData = $rsGetData->fetch_assoc()) {
$responseData .= '<L3DataSet>';
foreach($rowGetData as $k => $v) {
$responseData .= '<' . $k . '>' . $v . '</' . $k . '>';
}
$responseData .= '</L3DataSet>';
}
$responseData .= '</L3MDataSets>';
$responseData = encryptRJ256($responseData);
$responseString = new soapval('return', 'xsd:string', $responseData );
return $responseData;
}
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
From the Above code in the getDemoData function, if I remove the while loop, it gives the proper output. But when I put back the while loop it shows me output as "-Error: Response not of type text/xml: text/html" even if the SQL query is correct. I have copied and paste the generated SQL query which works in phpMyAdmin.

How to search a substring in PHP array using regExp

$array = array(
array('foo_test1','demo_test1'),
array('foo_test2','demo_test2'),
array('blah_test1','exp_test1'),
array('blah_test2','exp_test2'),
array('foo_test3','demo_test3')
)
How to get all subarray which contains foo substring with its value using php and regExp.
Expected Output:
$array = array(
array('foo_test1','demo_test1'),
array('foo_test2','demo_test2'),
array('foo_test3','demo_test3')
)
You should be able to do it with
preg_grep($pattern,$array)
$input = array( /* your array */ );
$output = array();
foreach ( $input as $data ) {
$len = length($data);
for ( $i = 0; $i < $len; ++$i ) {
if ( strpos($data[$i], 'foo') > -1 ) {
$output[] = $data;
break;
}
}
}
$array = array(
array('foo_test1','demo_test1'),
array('foo_test2','demo_test2'),
array('blah_test1','exp_test1'),
array('blah_test2','exp_test2'),
array('foo_test3','demo_test3')
);
$search = 'foo';
$res = array();
foreach ($array as $arr) {
foreach ($arr as $value) {
if (preg_match('~'.preg_quote($search,'~').'~',$value)) {
// if one of the values in that array
// has the search word in it...
$res[] = $arr; break;
// push it into the $res and break
// the inner foreach loop
}
}
}
print_r($res);