Convert INSERT sequence into UPDATE sequence - sql

i have a SQL INSERT sequence in PDO like:
INSERT INTO property (id,name,addres...) VALUES (:id,:name,:address...)
And i want to do a UPDATE sequence, with the same fields. The problem is that i have 150 fields and about 3 or 4 different sequences, so if i make the update syntax manually its probably that it takes a lot of time and a lot of mistakes, is there any "automatic" way to convert it?
Thank you a lot

The way I would do this, is have a function which dynamically builds the query based on key-value pairs passed in an array:
function updateTable($table, $values)
{
// Set the base query
$query = 'UPDATE ' . $table;
// Build the query with the key value pairs
foreach($values as $key=>$data) {
$query . ' SET ' . $key . ' = ' . $data . ' ';
}
// Execute your query here
...
}
Obviously you would need to bind your PDO objects on each iteration of the loop but I wanted to give you the basic layout of a loop to handle what you want to achieve, you could then call it like this:
updateTable('Products', { 'product_name' => 'Apple', 'product_price' => 100.00})
This would then build the query:
UPDATE Products SET product_name = 'Apple', product_price = 100.00
You could easily extend this query to provide a WHERE parameter so you can refine your UPDATE query - please remember this is currently in-secure so please spend some time implementing proper sanitsation over variables before committing to the DB!
Hope this helps.

Related

Is there any way to set multiple LIKE options inside where clause in cakephp 3

I want to retrieve all rows matched on multiple partial prase against with a column. My situation can be explained as following raw sql:
SELECT *
FROM TABLENAME
WHERE COLUMN1 LIKE %abc%
OR COLUMN1 LIKE %bcd%
OR COLUMN1 LIKE %def%;
Here, abc, bcd, def are array elements. i.e: array('abc','bcd','def'). Is there any way to write code passing this array to form the above raw sql using cakephp 3?
N.B: I am using mysql as DBMS.
probably you can use Collection to create a proper array, but I think a foreach loop will do the job in the same amount of code. So here is my solution supposing $query stores your Query object
$a = ['abc','bcd','def'];
foreach($a as $value)
{
$or[] = function ($exp, $q) use ($value) {
return $exp->like('column1', '%'.$value.'%');
};
}
$query->where(['or' => $or]);
you could also use orWhere() but I see it will be deprecated in 3.6

pdo print info using given value pdo

function getCars($memebrNo) {
// STUDENT TODO:
// Change lines below with code to retrieve the cars of the member from the database
$stmd=$dbh->prepare('SELECT name FROM PeerPark.Car JOIN PeerPark.Member WHERE memberNo=:memberNo');
$stmd->bindParam(':memberNo', $memberNO, PDO::PARAM_STR);
$stmd->execute;
$result=$stmd->fetchAll(PDO::FETCH_COLUMN);
var_dump($result);
these are my codes, but i want to print like the following, besides can someone tell me am i using the memberNo given in function the right way? Thanks
$results = array(
array('car'=> 'Gary'),
array('car'=> 'Harry' )
);
To get a result like that, your query should be:
$stmd=$dbh->prepare('SELECT name AS car FROM PeerPark.Car JOIN PeerPark.Member WHERE memberNo=:memberNo');
and then you should fetch the results with:
$result = $stmd->fetchAll(PDO::FETCH_ASSOC);
PDO::FETCH_COLUMN returns an index array containing all the values of the column. PDO::FETCH_ASSOC returns a 2-dimensional array where each element is an associative array mapping the column names to their values.

Doctrine2 fetch Count more optimized and faster way Or Zf2 library

I am using Doctrine2 and Zf2 , now when I need to fetch count of rows, I have got the following two ways to fetch it. But my worry is which will be more optimized and faster way, as in future the rows would be more than 50k. Any suggestions or any other ways to fetch the count ?? Is there any function to get count which can be used with findBy ???
Or should I use normal Zf2 Database library to fetch count. I just found that ORM is not preferred to fetch results when data is huge. Please any help would be appreciated
$members = $this->getEntityManager()->getRepository('User\Entity\Members')->findBy(array('id' => $id, 'status' => '1'));
$membersCnt = sizeof($members);
or
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('count(p)')
->from('User\Entity\Members', 'p')
->where('p.id = '.$id)
->andWhere('p.status = 1');
$membersCnt = $qb->getQuery()->getSingleScalarResult();
Comparison
1) Your EntityRepository::findBy() approach will do this:
Query the database for the rows matching your criteria. The database will return the complete rows.
The database result is then transformed (hydrated) into full PHP objects (entities).
2) Your EntityManager::createQueryBuilder() approach will do this:
Query the database for the number of rows matching your criteria. The database will return a simple number (actually a string representing a number).
The database result is then transformed from a string to a PHP integer.
You can safely conclude that option 2 is far more efficient than option 1:
The database can optimize the query for counting, which might make the query faster (take less time).
Far less data is returned from the database.
No entities are hydrated (only a simple string to integer cast).
All in all less processing power and less memory will be used.
Security comment
Never concatenate values into a query!
This can make you vulnerable to SQL injection attacks when those values are (derived from) user-input.
Also, Doctrine2 can't make use of prepared statements / parameter binding, which can lead to some performance-loss when the same query is used often (with or without different parameters).
In other words, replace this:
->where('p.id = '.$id)
->andWhere('p.status = 1')
with this:
->where('p.id = :id')
->andWhere('p.status = :status')
->setParameters(array('id' => $id, 'status' => 1))
or:
->where($qb->expr()->andX(
$qb->expr()->eq('p.id', ':id'),
$qb->expr()->eq('p.status', ':status')
)
->setParameters(array('id' => $id, 'status' => 1))
Additionally
For this particular query, there's no need to use the QueryBuilder, you can use straight DQL in stead:
$dql = 'SELECT COUNT(p) FROM User\Entity\Members p WHERE p.id = :id AND p.status = :status';
$q = $this->getEntityManager()->createQuery($dql);
$q->setParameters(array('id' => $id, 'status' => 1));
$membersCnt = $q->getSingleScalarResult();
You should totally go to the dql version of the count.
With the first method you will hydrate (convert from db resultset to objects) each of the rows as single object and put them on one array and then count the amount items in that array. That will be a totally waste of memory and cycles if the only objective is to know the number of elements in that result set.
With the second method the dql will be gracefully converted to SELECT COUNT(*) Blah blah blah
plain SQL sentence and will retrieve directly the count from db.
The comment about ORM is not preferred to when to retrieve data is huge is true, in big batch process you should paginate your query to retrieve data instead all at the same time to avoid memory overrides but in that case you are only retrieving a single number, the total count so this rule doesn’t apply.
Query builder is so slow .
Use DQL for faster select .
$query = $this->getEntityManager()->createQuery("SELECT count(m) FROM User\Entity\Members m WHERE m.status = 1 AND m.id = :id ");
$query->setParameter(':id', $id);
You need setParameter for prevent SQL injection .
Stored procedure is fastest but it depend on your DB .
Make all relations of entity Lazy.

Calculate percentage in query ZF2

Is there a way to calculate the percentage between two values in a table and select it as a column? I know it's possible, but I'd like to know if it's possible in a ZF2 context specifically.
I have a select in my ZF2 application that fetches a bunch of data from a db (SQL Server). This query concerns a table "libraries" that I want to order by free disk space (a column in the table). But I don't want it to order by the absolute amount of free space but rather the percentage relative to the total disk space.
So I mean something like
libraries.freeSpace / libraries.totalSpace as 'percentage'
but within a ZF2 select. This is the query currently:
$resultSet = $this->tableGateway->select(function(Select $select) use($report){
$select->where('id = ' . $report[0]->customer)
->order('freeSpace', 'asc');
});
e: ANSWER.
Use Zend\Db\Sql\Expression your model.
Add columns to your select:
$select->columns(array(
'percentage' => new Expression('cast(libraries.freeSpace') as float / cast.('libraries.totalSpace') as float', false);
You can pass an expression to Columns, don't forget the second parameter, you will need to set this to FALSE to stop the table prefix being automatically added for you when you manually supply them.
use Zend\Db\Sql\Expression;
$resultSet = $this->tableGateway->select(function(Select $select) use($report){
$select->columns(array(
'percentage' => new Expression('libraries.freeSpace / libraries.totalSpace')
), FALSE)
->where('id = ' . $report[0]->customer)
->order('freeSpace', 'asc')
;
});

Is there SQL parameter binding for arrays?

Is there a standard way to bind arrays (of scalars) in a SQL query? I want to bind into an IN clause, like so:
SELECT * FROM junk WHERE junk.id IN (?);
I happen to be using Perl::DBI which coerces parameters to scalars, so I end up with useless queries like:
SELECT * FROM junk WHERE junk.id IN ('ARRAY(0xdeadbeef)');
Clarification: I put the query in its own .sql file, so the string is already formed. Where the answers mention creating the query string dynamically I'd probably do a search and replace instead.
Edit: This question is kind of a duplicate of Parameterizing a SQL IN clause?. I originally thought that it should be closed as such, but it seems like it's accumulating some good Perl-specific info.
If you don't like the map there, you can use the 'x' operator:
my $params = join ', ' => ('?') x #foo;
my $sql = "SELECT * FROM table WHERE id IN ($params)";
my $sth = $dbh->prepare( $sql );
$sth->execute( #foo );
The parentheses are needed around the '?' because that forces 'x' to be in list context.
Read "perldoc perlop" and search for 'Binary "x"' for more information (it's in the "Multiplicative Operators" section).
You specify "this is the SQL for a query with one parameter" -- that won't work when you want many parameters. It's a pain to deal with, of course. Two other variations to what was suggested already:
1) Use DBI->quote instead of place holders.
my $sql = "select foo from bar where baz in ("
. join(",", map { $dbh->quote($_) } #bazs)
. ")";
my $data = $dbh->selectall_arrayref($sql);
2) Use an ORM to do this sort of low level stuff for you. DBIx::Class or Rose::DB::Object, for example.
I do something like:
my $dbh = DBI->connect( ... );
my #vals= ( 1,2,3,4,5 );
my $sql = 'SELECT * FROM table WHERE id IN (' . join( ',', map { '?' } #vals ) . ')';
my $sth = $dbh->prepare( $sql );
$sth->execute( #vals );
And yet another way to build SQL is to use something like SQL::Abstract....
use SQL::Abstract;
my $sql = SQL::Abstract->new;
my $values = [ 1..3 ];
my $query = $sql->select( 'table', '*', { id => { -in => $values } } );
say $query; # => SELECT * FROM table WHERE ( id IN ( ?, ?, ? ) )
With plain DBI you'd have to build the SQL yourself, as suggested above. DBIx::Simple (a wrapper for DBI) does this for you automatically using the '??' notation:
$db->query("select * from foo where bar in (??)", #values);
In python, I've always ended up doing something like:
query = 'select * from junk where junk.id in ('
for id in junkids:
query = query + '?,'
query = query + ')'
cursor.execute(query, junkids)
...which essentially builds a query with one '?' for each element of the list.
(and if there's other parameters in there too, you need to make sure you line things up correctly when you execute the query)
[edit to make the code easier to understand for non-python people. There is a bug, where the query will have an extra comma after the last ?, which I will leave in because fixing it would just cloud the general idea]
I use DBIx::DWIW. It contains a function called InList(). This will create the part of the SQL that is needed for the list. However this only works if you have all your SQL in the program instead of outside in a separate file.
Use
SELECT * FROM junk WHERE junk.id = ANY (?);
instead