How to assign two SELECT queries results to single array variable($row)? - php

There are two queries with same fields names but different tables. I want fetch both select query's results in same array variable $result. I tried few things but nothing working for me. May b my bad day.
two table, need to be fetch in same variable $result.
$sql1="SELECT city,phone,name from table1 where city='NY'";
$result = $conn->query($sql1);
$sql2="SELECT city,phone,name from table2 where city='NY'";
$result = $conn->query($sql2);
I don't want $result lost $sql1 data after assigning same variable ($result) to second query. Please help

You can use UNION and along with that table record identifier to identify table records differently.
$sql1 = "(SELECT city,phone,name, 't1' ttype from table1 where city='NY')
UNION (SELECT city,phone,name,'t2' ttype from table2 where city='NY')";
$result = $conn->query($sql1);
Note: MySQL uses the DISTINCT clause as default when executing UNION queries if nothing is specified.
If you want duplicate records too, then use UNION ALL.

$sql1="SELECT city,phone,name from table1 where city='NY'
UNION
SELECT city,phone,name from table2 where city='NY'";
$result = $conn->query($sql1);

Related

using arrays to query with SELECT with PHP

I'm querying a table that returns id's and I'd like to use these id's within an array to perform another query.
I have the two queries working independently of each other by hard coding the id's into the second query just to be sure that it functions as expected, which it does.
$query = "SELECT item_id FROM items";
$query = "SELECT * FROM results WHERE results_item_id in (1,2,3,4)";
I'd like the return of the second query to include data for all of the id's returned to me from the first query.
Instead of sub query, you can do it by JOIN matching ON item_id = results_item_id
$query = "SELECT R.* FROM results R JOIN items I ON I.item_id = R.results_item_id";
Just put the query inside the IN, and add distinct so each item_id you only get in once:
$query = "SELECT * FROM results WHERE results_item_id in (SELECT distinct item_id FROM items)";

Insert into if not exist MySQL

I'm using PostgreSQL to get data and i want to insert it into MySQL. I have a php script which allows me to get the data, check for repeated and then insert it into MySQL DB. Problem is that instead of inserting only the non existing data it inserts one random row and doesn't insert nothing else.
$check_for_episode = mysqli_query($conn, "SELECT DISTINCT house_number,number FROM episode WHERE house_number LIKE '".$house_number."' AND number = ".$episode_id_pg." LIMIT 1");
if (mysqli_fetch_array($check_for_episode)){
}else{
$insert_episode = mysqli_query($conn, "INSERT INTO episode(".$episode_col.")VALUES('".$episode_values."')");
}
the variables $episode_col and $episode_values get data from an array called $episode through implode:
$episode_col = implode(", ", array_keys($episode));
$episode_values = implode("', '", array_values($episode));
This is you code.
IF statements are used for comparisons, yours is just fetching the array and there's no condition inside your IF statement. You need to fix the statements to get the columns and their respective values.
$check_for_episode = mysqli_query($conn, "SELECT DISTINCT house_number,number FROM episode WHERE house_number LIKE '".$house_number."' AND number = ".$episode_id_pg." LIMIT 1");
if (mysqli_fetch_array($check_for_episode)){
}else{
$insert_episode = mysqli_query($conn, "INSERT INTO episode(".$episode_col.")VALUES('".$episode_values."')");
}
You can try to use WHERE EXISTS or WHERE NOT EXISTS too.
SELECT DISTINCT column1 FROM table1
WHERE EXISTS (SELECT * FROM table2
WHERE table2.column1 = table1.column1);
SELECT DISTINCT column1 FROM table1
WHERE NOT EXISTS (SELECT * FROM table2
WHERE table2.column1 = table1.column1);
For more info: https://dev.mysql.com/doc/refman/5.7/en/exists-and-not-exists-subqueries.html

Relational table query gives me a null value in the field 'id' in table

I am creating a query and I used the LEFT JOIN to join two tables. But I'm having trouble in getting the fb_id value from the table, it gives me an empty result. Here is my code:
$sql = "SELECT * FROM tblfeedback a LEFT JOIN tblreply b ON a.fb_id = b.fb_id WHERE a.fb_status = 1 ORDER BY a.fb_id DESC";
$res = $con->query($sql);
....
....
The query above would give me a result like this :
I think that's why I don't get the fb_id value is because the last column is null. How do I get the value of fb_id from the first column? Thanks. I am really having trouble with this. I hope someone can enlightened my mind.
You should give an alias to the column in the parent table, because the column names are the same in both tables. When fetch_assoc() fills in $row['fb_id'], it gets the last one in the result row, which can be NULL because it comes from the second table.
SELECT a.fb_id AS a_id, a.*, b.*
FROM tblfeedback a
LEFT JOIN tblreply b ON a.fb_id = b.fb_id
WHERE a.fb_status = 1
ORDER BY a_id DESC
Then you can access $row['a_id'] to get this column.
More generally, I recommend against using SELECT *. Just select the columns you actually need. So you can select a.fb_id without selecting b.fb_id, and it will always be filled in.
Because you are using a left join, the 2 rows in your result set image are the rows from tblfeedback whose fb_id were not found in tblreply. We know this is true because all the tblreply columns in the result set are null.
With that said, its not real clear what you are asking for. If you are asking how you access the tblfeedback.fd_id column from your query via php, you can use the fetch_array method and use the 0 index.
$sql = "SELECT * FROM tblfeedback a LEFT JOIN tblreply b ON a.fb_id = b.fb_id WHERE a.fb_status = 1 ORDER BY a.fb_id DESC";
$res = $con->query($sql);
while($row = $res->fetch_array()) {
echo "fb_id: " . $row[0] . "<br>";
}

Add MySQL Count Column to PHP/HTML Table

I'm developing a website using HTML, PHP and MySQL to access a database. On one page I present a table with data from that database. This is some of the code I'm using:
$sql1 = "SELECT * FROM MyTable ORDER BY ID ASC";
$rs1 = mysqli_query($link,$sql1);
(...)
while($row1 = mysqli_fetch_assoc($rs1)) {
echo "<tr><td>".$row1['ID']."</td><td>".$row1['Field1']."</td><td></td><td>".$row1['Field2']."</td><td>".$row1['Field3']."</td></tr>\n" ;
}
Notice the empty <td></td>? That's because I want to have there the number of time a given ID appears on two other tables (there are foreign keys involved, obviously). I have sorted out the code I need for that:
$sql2 = "SELECT (SELECT COUNT(*) FROM MyTable2 WHERE ID2=$row1['ID'])+(SELECT COUNT(*) FROM MyTable3 WHERE ID2=$row1['ID']) AS total";
However, I'm struggling with figuring out a way to add this result to the other table. Any help?
try with this.. it inserts the total to an table after selecting the count.
"INSERT INTO total_table (total)
SELECT (SELECT COUNT(*) FROM MyTable2 WHERE ID2=$row1['ID'])+(SELECT COUNT(*) FROM MyTable3 WHERE ID2=$row1['ID']) AS total
WHERE cid = 2"

How to look at the result of a query

I have a SQL Query, although it is executing, but how should i verify if it is giving me the desired result.
For example: My query
$query3 = "SELECT COUNT(DISTINCT(uid)) AS `num`
FROM `user_info`
WHERE date(starttime)='2011-10-10'";
In the above query i am trying to count the number of distinct user ID's(uid) from the table named user-infowhere date is 2011-10-10.
How should i display the count which is calculated for the given date?.I need to know it and perform some further operations on it!
$query3 = "SELECT COUNT(DISTINCT uid) AS `num`
FROM `user_info`
WHERE date(starttime)='2011-10-10'";
$result = mysql_query($query3);
$row = mysql_fetch_array($result);
echo $row['num'];
Just do:
SELECT COUNT(DISTINCT uid) AS `num`
FROM `user_info`
WHERE date(starttime)='2011-10-10'
This SO post goes into some details about how count and count(distinct ...) work. With just count, there is a hidden/assumed function of count(all ... ) actually happening (it's just the default value). If you want to only count distinct things, switch it to the non-default and do the count(distinct ...) instead. I didn't know it existed for my first 6 months of writing sql or so...
You can set a variable sing the result...
SET #userVar=SELECT
COUNT(DISTINCT uid)
FROM
user_info
WHERE
DATE(starttime)='2011-10-10';
Then you can use that variable in your next operation or query.

Categories