get table name from count query - php

How do you get table name from count query, I have multiple queries and I need to get table name from the query results, here is my query
$myquery = "select count(tb_id) as num_rows from table1; select count(tb1_id) from table2...";
if (myqli_multi_query($connection, $myquery){
..
$row = mysqli_fetch_assoc($result);
$num_rows = $row["num_rows"];
..
}
The query is working fine as I can get the number of rows, but I am unable to link the table name to the number of rows (result)
I have tried this, which executes without error, but unable to get the table name still
select count(tb_id) as num_rows, 'table1' as TableName from table1

You could put an identifier into your query you can refer to later.
$myquery = "select 'table1' as tablename, count(tb_id) as num_rows from table1;
select 'table2' as tablename, count(tb1_id) as num_rows from table2;"
// and so on

You can try mysqli_fetch_field
mysqli_fetch_field($result)->table;

Just add it in to the select or the column name.
Column name:
select count(tb_id) as table1_count from table1; select count(tb1_id) as table2_count from table2.
OR sep column:
(select count(tb_id) as num_rows, 'table1' as tablename from table1)
UNION
(select count(tb1_id), 'table2' from table2...)
UNION.... etc
Edited to add: you are returning sep resultsets; consider UNION above for a single resultset.

Related

Combine SQL statement

I would like to select different column from different row from the same table with one statement . How will I combine this to be one?
SELECT `shop_lat_log` FROM `customers` WHERE `phoneNumber`='254719401837'
SELECT `delivery_lat_log` FROM `customers` WHERE `phoneNumber`='25472054919'
You could just use each of two current queries as subqueries in one select statement:
SELECT
(SELECT shop_lat_log FROM customers WHERE phoneNumber = '254719401837') AS shop_lat_log,
(SELECT delivery_lat_log FROM customers WHERE phoneNumber = '25472054919') AS delivery_lat_log
FROM dual;
This assumes that each of your two queries returns a single value. If not, then perhaps a UNION would be more appropriate:
SELECT
shop_lat_log AS log_value,
'shop_lat_log' AS log_type
FROM customers
WHERE phoneNumber = '254719401837'
UNION ALL
SELECT
delivery_lat_log,
'delivery_lat_log'
FROM customers
WHERE phoneNumber = '25472054919'
You can use a UNION for that:
SELECT `shop_lat_log` FROM `customers` WHERE `phoneNumber`='254719401837'
UNION
SELECT `delivery_lat_log` FROM `customers` WHERE `phoneNumber`='25472054919'
Note that the second query must have the same number of columns as the first query, and the results will have the first query's column names.
So even though you're selecting the delivery_lat_log column in your second query, the results will be in the shop_lat_log column if you're fetching an associative array.
Use an SQL case statement
select case c.phone_number
when '254719401837'
then c.shop_lat_log
when '25472054919'
then c.delivery_lat_log
end as field
from customer as c
where c.phone_number in ('254719401837', '25472054919')

Codeigniter placeholder in select statement (select id, 0 as placeholder, ...)

I have query that counts ids in joined table. I need to do an union of returned table with another table in database.
The table returned from first query has 4 columns:
-group_id
-count
-name
-description
The table I want to unite with the first one has 3 columns:
-group_id
-name
-description
I run query through phpmyadmin and it worked perfectly. Query:
SELECT group_id, size, name, description
FROM(SELECT *, count(group_id) as size
FROM table1
GROUP BY group_id) as tmp
JOIN table2
ON tmp.group_id = table2.group_id
UNION
SELECT id, 0 as size, name, description
FROM table2
But when I try to make query with codeigniter, it won't work.
Error: Unknown column '0' in 'field list'
SELECT id, 0 as size, name, description
FROM table2
Here is the codeigniter code from module:
$this->db->select('group_id, size, name, description');
$this->db->from('(select *, count(group_id) as size from table1 group by group_id) as tmp');
$this->db->join('table2', 'tmp.group_id=table2.id');
$this->db->get();
$query1 = $this->db->last_query();
$this->db->select('id, 0 as size, name, description');
$this->db->from('table2');
$this->db->get();
$query2 = $this->db->last_query();
$this->db->query($query1. ' UNION ' .$query2);
$query = $this->db->get();
return $query->result_array();
To make the story short I need to know how to make placeholder with codeigniter or is there any other, better way to get the result I need?
You have to escape your select query by adding FALSE value as the second parameter of codeigniter's active record select() function.
So, it should be written like:
$this->db->select('id, 0 as size, name, description',FALSE);
When you add FALSE value to the second parameter of it, codeigniter won't keep the first parameter to be initialized by backtick character to the query.

How to update value when moving row to another table

I have 2 tables:
Table1
Table2
When I move a row from table1 to table2, I also want to update the datetime field and 1 more field.
Say both table have identical column like this:
id
shipped_by
datetime
other_column
I have the following sql line, but it is not working of course. But I want to have it something like that.
$query = "INSERT INTO table2
SELECT * FROM table1
WHERE id = '$id' UPDATE table2
SET shipped_by='$shipped_by', datetime='$datetime'";
The variable $shipped_by selects the userid, and $datetime date from now.
Can anyone help me with this sql code to make it work? I cannot figure it out.
Thank you.
To insert data form table1 with some column data modified can be done with insert and select without update.. select * should be used here, each column must be listed except for modified ones..
$query = "INSERT INTO table2
SELECT id, '$shipped_by', '$datetime', other_column FROM table1
WHERE id = '$id'";

mysql update subquery not working

mysql update syntax doesn't seem to work when I added the subquery.
Are there restrictions on subqueries on update syntax?
doesn't work:
update books set imagename ='name'
where book_ID='(select book_ID from books order by book_ID desc limit 1)';
works:
update books set imagename ='name'
where book_ID='101';
MySQL does have limits on subqueries using the table being updated. So yours is not allowed:
update books
set imagename ='name'
where book_ID = (select book_ID from books order by book_ID desc limit 1);
Instead, you can do:
update books
set imagename ='name'
order by book_ID desc
limit 1;
Here is the explanation in the documentation:
In general, you cannot modify a table and select from the same table
in a subquery. For example, this limitation applies to statements of
the following forms:
DELETE FROM t WHERE ... (SELECT ... FROM t ...);
UPDATE t ... WHERE col = (SELECT ... FROM t ...);
{INSERT|REPLACE} INTO t (SELECT ... FROM t ...);
Exception: The preceding prohibition does not apply if you are using a subquery for the modified table in the FROM clause. Example:
UPDATE t ... WHERE col = (SELECT * FROM (SELECT ... FROM t...) AS _t ...);
Here the result from the subquery in the FROM clause is stored as a temporary table, so the relevant rows in t have already been
selected by the time the update to t takes place.
Try This query.
Update books
Set imagename = name"
Where book_ID In (
Select T1.book_ID
From books As T1
Where T1.book_ID = '101'
)

remove identical values from 2 mysqli queries

I want to make 2 mysqli queries. But if there are values in the second query that are Identical to the values yielded from the first query I want to exclude those values from the result set. What I have now only seems to work for 1 identical value. the rest of the identical values are shown. how should I change this? Thanks.
$query1 = $db->query("SELECT colTab1 FROM table1");
while ($result1 = $query1 ->fetch_assoc()) {
$query2 = $db->query("SELECT colTab2 FROM table2 WHERE colTab2 <> $result1[colTab1]");
echo $result1['colTab1']."<br>";
}
while ($result2 = $query2 ->fetch_assoc()) {
echo $result2['colTab2']."<br>";
}
}
Well, you can modify your second query as follows:
SELECT colTab2 FROM table2 WHERE colTab2 NOT IN (SELECT colTab1 FROM table1)
Or maybe you just want to select the UNION of the two tables (which will omit duplicates by default):
SELECT colTab1 FROM table1
UNION
SELECT colTab2 FROM table2
(Note that relying on UNION to omit duplicates between the two recordsets is not quite the same thing, as any duplicates that exist within each recordset will also be omitted; if that is a concern, one can SELECT DISTINCT ... UNION ALL SELECT DISTINCT ... instead).
Just run one query; why bring back data from the database to filter on? Filter in the DB.
SELECT colTab2
FROM table2
WHERE colTab2 NOT IN (
SELECT colTab1
FROM table1
)

Categories