PDO query to remove text from 3 MySQL tables at once? - pdo

As an absolute beginner in these things, I am stuck: I need to build a query to remove all occurrences of a string from 3 tables, something like
$sql = "UPDATE table_1, table_2, table_3 SET column=REPLACE(column, '$string', '')";
How can I build a prepared statement to do this? Something like
$sql = "UPDATE table_1, table_2, table_3 SET column=:column";
$q = $dbh->prepare($sql);
$q->execute(array(':column'=>"REPLACE(column, '$string', '')"));
obviously does not work.

Run three queries. There's no sane way to do this in a single query.
As far as the prepared statement goes, you need to include the REPLACE() function in the query, not in the placeholder:
$q = $dbh->prepare("UPDATE table SET column = REPLACE(column, :string, '')");
$q->execute([ ':string' => $string ]);

Related

Create a SQL select query dynamically at runtime

I have a requirement where I need to write a SQL select query with dynamic columns at runtime. There are few mandatory and optional fields in the DB. I want to generate the query at runtime based on the values present in the incoming request.
Ex: DB has colms A,B,C,D,E
scenario 1: request has only value for A, query should be generated as
select * from table where A='<somevalue>'
scenario 2 . Request has value for A and D , query should be generated as
select * from table where A='<somevalue>' and D='<somevalue>'
Currently it is being handled using java to create string for not null values and appending it to select statement to form the final query.
Ex:
if (A!=null)
String query_a='<somevalue>'
else
query_a=""
and then appending <query_a> <query_b> to form final query
Is there a better way to achieve this?
In your SQL script, you can better parametrize like below. I've assume that you are using parameters.
**It's basically sql idea.
SELECT *
FROM table
WHERE (
(#p1 IS NULL OR columnA = #p1)
OR (#p2 IS NULL OR columnB = #p2)
OR (#p3 IS NULL OR columnC = #p3)
OR (#p4 IS NULL OR columnD = #p4)
)
You may want to consider doing this construction of queries in Java, creating an appropriate Prepared Statement for each case.
List<String> clauses = new ArrayList<String>();
List<String> params = new ArrayList<String>();
clauses.add("1=1");
if (you_want_to_search_on_column_a) {
clauses.Add("column_a = ?");
params.Add(value_to_search_on_column_a);
}
if (you_want_to_search_on_column_b) {
clauses.Add("column_b = ?");
params.Add(value_to_search_on_column_b);
}
String queryString = "SELECT * FROM table WHERE " + String.join(" AND ", clauses);
PreparedStatement stmt = con.prepareStatement(queryString);
for (int i = 0; i < params.size; i++ ) {
stmt.setString(i+1, params.get(i));
}
ResultSet rs = stmt.executeQuery();
This way you'll present queries with exactly the filtering criteria you need, and so give MySQL's query planner the best possible shot at optimizing each one.
If you were working with Oracle or SQL server it would be worth your trouble to keep a cache of PreparedStatement objects, but that's not so with MySQL.

Laravel Query builder: left join, select, and where not working

Unfortunately the Laravel query builder seems not in a good mood!
Here is my table structure:
Table user structure
ID, USERNAME, NAME, USER_ROLE_MODULE_ID
Table user_role_module structure
ID, NAME
And this is my query builder statement
DB::table('user')
->leftJoin('user_role_module', 'user.user_role_module_id', '=', 'user_role_module.id')
->select('user.*', 'user_role_module.name as user_role')
->where("name LIKE '%Jhon%' ") "or other example" ->where("user_role LIKE '%admin%' ")
->paginate(10);
Goal:
I just want to get all data from user + user role name from user_role_module AND also applies in WHERE statement so I can use it for search feature.
I am getting result from WHERE statement without specifying table name. because it already stated which table and column to select from SELECT statement.
The problem:
if I search for name, it return error ambiguous column //Laravel is confusing whether taking name from user table or user_role_module table!
if I search for user_role, then the column doesn't exist
Why is it? What is the solution?
The problem:
user.NAME <-- both these columns are called NAME
user_role_module.NAME <--
You have multiple problems with your Laravel query. As #Viktor correctly pointed out, your join condition is wrong. You should be joining user.USER_ROLE_MODULE_ID to user_role_module.id. But the immediate cause of your error I believe is that both tables have a NAME column.
Just specify the columns you want using both table and column name. This way, no column name would be ambiguous.
DB::table('user')
->leftJoin('user_role_module', 'user.USER_ROLE_MODULE_ID', '=', 'user_role_module.id')
->select('user.ID', 'user.USERNAME', 'user.NAME AS userName',
'user_role_module.name as user_role')
->where("name LIKE '%John%'")
->paginate(10);
Change this:
DB::table('user')
->leftJoin('user_role_module', 'user.user_role_module_id', '=', 'user_role_module.id')
->select('user.*', 'user_role_module.name as user_role')
->where("name LIKE '%Jhon%' ") "or other example" ->where("user_role LIKE '%admin%' ")
->paginate(10);
with this:
DB::table('user')
->leftJoin('user_role_module', 'user.user_role_module_id', '=', 'user_role_module.id')
->where('user.name', 'like', '%Jhon%')
->select('user.*', 'user_role_module.name as user_role')
->get();
and make a custom pagination because select is not working with paginate.

How to use a calculated column to calculate another column in codeigniter

i hope you can help me with this simple question.
i try to use this nested query in codeigniter.
Select
ColumnA,
ColumnB,
calccolumn1,
calccolumn1 / ColumnC as calccolumn2
From (
Select
ColumnA,
ColumnB,
ColumnC,
ColumnA + ColumnB As calccolumn1
from testtable
);
how to convert this to codeigniter?
i know the inner SELECT should look a bit like this:
$this->db->select('ColumnA,ColumnB,ColumnC,ColumnA + ColumnB As calccolumn1');
$this->db->from('testtable');
$subquery = $this->db->get();
...
but then how do i have to proceed?
Thanks for you fast reply!
The query is working fine now! but i cant seem to find how to add the WHERE clause with my variable ($data) from the method which i wanted to add now.
normally i use
$this->db->where('Username', $data);
but since the where clause is now in the query, i didnt find a way yet to add it inside the query.
When it comes to more complicated queries I usually just do this:
$variable = 'x';
$query = $this->db->query("
SELECT...
FROM...
WHERE some_column = '$variable'
");
return $query->result_array();

Result from ActiveRecord::Base.connection.execute(sql) - PostgreSQL

How can I find number of records processed by PostgreSQL after executing a SQL statement using ActiveRecord::Base Connection class?
temp_sql = "UPDATE table_a SET column_a ='abc' WHERE column_b = 1"
result = ActiveRecord::Base.establish_connection(#db).connection.execute(temp_sql)
Or can you suggest better way to do this. Please keep in mind that above update statement is a simple one to keep question brief. My real queries are "set based" and involves complex create temp tables, update, insert statements.
Found the answer in PG::Result class. It is cmd_tuples method;
temp_sql = "UPDATE table_a SET column_a ='abc' WHERE column_b = 1"
result = ActiveRecord::Base.establish_connection(#db).connection.execute(temp_sql)
number_of_records = result.cmd_tuples

Regarding joins and subquery

I have below query that I am using ..
select * from app_subsys_param where assp_name like '%param_name%'
where param_name is the name of the parameter. From this query we will get the assp_id corresponding to the parameter. With this id we look up into app_subsys_parmval table to get the value of the parameter.
update app_subsys_parmval set aspv_value = 'true' where assp_id = id_val
Now instead of separately launching the two sql statements , I want to combime both of them as one is there any sub query or join mechanism that can combine both of them in one statement , please advise
You need to use UPDATE .. FROM syntax:
UPDATE app_subsys_paramval
SET aspv_value = 'true'
FROM app_subsys_param
WHERE app_subsys_param.id = app_subsys_paramval.id
AND app_subsys_param.value LIKE '%param_name%';
Use a subselect in your update statement:
UPDATE app_subsys_parmval
SET aspv_value = 'true'
WHERE id_val = (SELECT assp_id
FROM app_subsys_param
WHERE assp_name LIKE '%param_name%')
Note, I am assuming a bit about what's in the * of your select *.
Look at the MERGE statement. This is the ANSI SQL:2003 standard for UPDATE … FROM.
Documentation:
MERGE for DB2 for Linux/UNIX/Windows
MERGE for DB2 z/OS 9.1