How do I use in case of Joomla the mysqli bind_param
how would this example should be declared using joomla Database methods?
...
$statement->bind_param('s', $like);
$statement->execute();
In Joomla! 3.1, PDO/Sqlite and PDO/Oracle are supporting prepared statements, others are not implemented yet.
Given using a 'preparable' connection, it would work this way:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('...')->where('...');
$query->bind(':s', $like);
$db->setQuery($query);
$records = $db->loadObjectList();
Related
I am trying to run the following query, which takes someone's name and attempts to insert it into an SQL Server database table.
$name = "Ronnie O'Sullivan"
$dataSource = "127.0.0.1"
$database = "Danny"
$connectionString = "Server=$dataSource;Database=$database;Integrated Security=True;"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
$query = "INSERT INTO People(name) VALUES('$name')"
$command = $connection.CreateCommand()
$command.CommandText = $query
$command.ExecuteNonQuery()
$connection.Close()
The problem I am facing is that the single quote is causing an issue in my query. The query is being executed as
INSERT INTO People(name) VALUES('Ronnie O'Sullivan')
which causes an SQL syntax error.
My question is how do I escape my $name variable so that it renders on the SQL side.
One solution is to do a find and replace on my $name variable, find: ' replace: ''
$name.Replace("'", "''")
Is there a more elegant solution out there, or a function that I can't seem to find?
Thank you.
You can try to update your code to to use a parametrised value that will cope with quotes in a string:
$query = "INSERT INTO People(name) VALUES(#name)"
$command = $connection.CreateCommand()
$command.CommandText = $query
$command.Parameters.Add("#name", $name) -- | Out-Null (may be required on the end)
$command.ExecuteNonQuery()
I'm not experienced with powershell but referenced this post for a parametrised query:
Tanner's helpful answer is definitely the most robust and secure solution, because using a [parameterized / prepared statement (query) eliminates any possibility of a SQL injection attack.
However, in this constrained case, where you want to insert a value into a single-quoted SQL string ('...'), you can get away with simply doubling any embedded ' characters in the value:
$query = "INSERT INTO People(name) VALUES('$($name -replace "'", "''")')"
The above uses PowerShell's string interpolation via $(...), the subexpression operator, to embed an expression that uses the -replace operator to double all embedded ' instances in the value of $name.
Note: You could also use $name.Replace("'", "''") above, which performs better in this simple case, but PowerShell's -replace operator is generally preferable, not only for being PowerShell-native, but for offering superior abilities, because it is regex-based and supports array as its LHS - see this comment on GitHub.
I use PowerShell to query SQL databases, and I am quite familiar with that process. However, I am now tasked with building an automated task that queries Oracle for information.
It seems straight forward: Install proper Oracle DLL's, import them into PS, execute the query much like SQL. However, this is not the case. All I get when I request information is a list called FieldCount. This seems to imply that I am able to see the information, it's just not displaying correctly. I'd like the actual values, and nothing seems to get this for me.
Thanks to anyone who knows anything about this, as my hands are tied and this is the only way I can think of to get this information from Oracle on a scheduled basis. I am not the Oracle admin, I only have read access to this view.
function Get-OracleData($cmdText){
Add-Type -Path 'C:\app\client\username\product\12.1.0\client_1\odp.net\managed\common\Oracle.ManagedDataAccess.dll'
$username = 'username'
$password = 'password'
$con = New-Object Oracle.ManagedDataAccess.Client.OracleConnection('User Id=$username;Password=$password;Data Source=OracleServerName')
$con.Open()
$cmd = New-Object Oracle.ManagedDataAccess.Client.OracleCommand
$cmd.Connection = $con
$cmd.CommandText = $cmdText
$rdr = $cmd.ExecuteReader()
if($rdr.Read()){
return $rdr
}else{return 0}
}
Get-OracleData -cmdText '
SELECT em.employee_number,
em.last_name,
em.first_name,
em.middle_names,
em.email_address,
em.start_date,
em.term_date,
em.location_addr_line_1,
em.location_city,
em.location_work_state,
FROM CustomView em
'
Found the answer in the link below. I was able to get what I needed by inserting the below code at the line where $cmd.CommandText = $cmdText is located in my original post, and getting rid of what's below it.
$ds = New-Object system.Data.DataSet
$da = New-Object Oracle.ManagedDataAccess.Client.OracleDataAdapter($cmd)
[void]$da.fill($ds)
return $ds.Tables[0] | Select *
This returns to a variable, and I can get the first entry using $results[0], and $results[0].EMPLOYEE_NUMBER, etc.
Reference: http://poshcode.org/3965 #line55
I am new to Joomla. I know that the following query should work correctly, but I have no clue where to place this query? I have added a blank module which can run PHP, but when I place this code there, nothing shows up. I really appreciate if someone can tell me where to place this code to be able to view the query results.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('id, name');
$query->from('#__users');
$db->setQuery($query);
$result = $db->loadObjectList();
print_r($result);
PHP 101 - you have the result but now you need to print or echo the result in order to show
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('id, name');
$query->from('#__users');
$db->setQuery($query);
$result = $db->loadObjectList();
print_r($result);
I am new to perl. I am given a task to connect to SQL server management 2012 and print a table from the database. Can you please guide me how to install all the drivers required and advise me what is wrong with my code, as i get no error and no required output.
use DBI;
my $host = 'programer'; #servername
my $database = 'DW'; #database name
my $user = 'prg'; #username
my $pwd = 'prg#123'; #password
my $dsn = "dbi:ODBC:Driver={SQL Server};Server=$host;Database=$database";
my $dbh = DBI->connect($dsn, $user, $pwd) or die("database not found");
$query="select * from Banking_AccountSummary_Citibank";
$exe=$dbh->prepare($query) or die("cannot prepapre query");
$exe->execute()or die("cannot execute");
$dbh->disconnect
Please guide me...
There is nothing wrong with your code. You don't need to install anything if you have use strict and use warnings and your code does not issue any warnings and does not die.
All you need to do is fetch your results and output them, or do whatever you want to do.
use Data::Dump;
my $exe = $dbh->prepare("select * from Banking_AccountSummary_Citibank")
or die("cannot prepapre query");
$exe->execute()
or die("cannot execute");
while (my $res = $exe->fetchrow_hashref) {
dd $res;
}
There are several ways to fetch your data and fetchrow_hashref is only one of them. I suggest you read the documentation of DBI and look at the examples given there.
Note: the convention is to name your statement handles $sth, just like the database handle is named $dbh. That will help others read your code.
Following this tutorial I tried to use PowerShell to retrieve xml data from SQL Server, but I only get one element back.
Here is a query to show the actual data:
But running this script I only get one element back:
$SQLServer = 'MYSERVER,1433'
$SQLDBName = "test"
$Query =
#'
USE test
SELECT EventLogXML FROM ForwardedEvents
'#
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $Database; Integrated Security = True"
$SqlConnection.open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $Query
$SqlCmd.Connection = $SqlConnection
$xr = $SqlCmd.ExecuteXmlReader()
$xd = New-Object System.Xml.XmlDataDocument
$xd.Load($xr)
$xr.Close()
$SQLConnection.Close()
$xd
$xd only has one element. What am I doing wrong?
---edit
I can confirm its only one xml doc by doing $xd.outerxml which reveals the complete doc. It is only one of the thousand or so event xml docs I'm storing in the EventLogXML column.
I think that XmlDataDocument is mainly for returning a single xml. Basically if you do in sql select * from bla for xml, auto you then can read it with the ExecuteXmlReader and XmlDataDocument. This is not what you want.
Modifying the example you linked to your needs we'll get somethign like:
$con = New-Object System.Data.SqlClient.SqlConnection
$con.ConnectionString = "Server=.; Database=AdventureWorks2012;Integrated Security=true"
$con.open()
$cmd = New-Object System.Data.SqlClient.SqlCommand
$cmd.CommandText = "SELECT Instructions FROM Production.ProductModel WHERE Instructions is not null"
$cmd.Connection = $con
$as = New-Object System.Data.SqlClient.SqlDataAdapter
$ds = New-Object System.Data.DataSet
$as.SelectCommand = $cmd
$as.Fill($ds);
$xmlDocs = $ds.Tables[0] | %{ [xml]$_.Instructions }
Now xmlDocs will contain a list of xml documents, one document per row.
Powershell wraps XML stuff into handy little objects, which you can explore using .Property syntax. If you just look at $xd, powershell by default will only show you the root node.
I don't know the structure of your XML column, but if the root node is called MyRoot, followed by common subnodes called MySub, try something like this:
$xd.MyRoot.MySub
This is just as the linked example shows the need to use $xd.root.Location
Edit
Ok so that is not the problem. Looks like it is by-design to return back only the first row when calling ExecuteXmlReader with a normal select statement (doc here):
if more than one row is returned, the ExecuteXmlReader method attaches
the XmlReader to the value on the first row, and discards the rest of
the result set
From some basic searching around, this blog post seems to explain the issue the best, and provides a workaround. See also here.
I may be out to lunch, but couldn't it be because you are declaring the database as $SQLDBName and then trying to connect to $Database in your connectionstring?