MySQL two conditions for two tables - php

I have a mysql query:
$query5 = mysql_query("SELECT * FROM `pages` WHERE (`id`='$switch' AND `rand`='$randID' AND `email`!='".$_SESSION['user']."') ");
And second:
$query5 = mysql_query("SELECT * FROM `pages_admin` WHERE (`pId`='$switch' AND `rand`='$randID' AND `admin`!='".$_SESSION['user']."') ");
I use a while loop to present data.
while($row = mysql_fetch_array($query5)) {}
I need one mysql query instead two.

If these tables are related you can JOIN them using the foreign key.
If I'm not mistaken this pId in the table pages_admin is a foreign key to the id on the table pages, is that correct?
If so, you could do something like this to you query:
"SELECT * FROM pages p
LEFT JOIN admin_pages ap on p.id = ap.pId
WHERE (`pId`=$switch AND `rand`=$randID AND `admin`!='{$_SESSION['user']}')"
Note that I've changed the syntax, instead of merging string you can use only one containing all variables you need.

Related

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

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);

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)";

Why do i double my display in json

So i fetch my data from two tables in my php and encode it in one json object. I got everything i needed except that it doubles the display. And my teamone is located in the matches tables. instead of starting from array 0, it starts after the schedules tables. Which is array 7. I dont know why this happen.
Here is my php.
$sql = "SELECT * from schedule, matches;";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$db_name);
$result = mysqli_query($con,$sql);
$response = array();
while($row=mysqli_fetch_array($result))
{
array_push($response, array("start"=>$row[4],"end"=>$row[5],"venue"=>$row[6], "teamone"=>$row[8], "teamtwo"=>$row[9],
"s_name"=>$row[17]));
}
echo json_encode (array("schedule_response"=>$response));
mysqli_close($con);
?>
Here is my display. As you can see there are four displays but in my database it only has 2. It doubles the display. How do i fix this? Thanks
{ "schedule_response":[
{"start":"2016-11-10 00:00:00","end":"2016-11-04 00:00:00","venue":"bbbb","teamone":"aaa","teamtwo":"bbb",
"s_name":"hehehe"},
{"start":"2016-11-23 00:00:00","end":"2016-11-24 00:00:00","venue":"bbbbbbbb","teamone":"aaa","teamtwo":"bbb",
"s_name":"hehehe"},
{"start":"2016-11-10 00:00:00","end":"2016-11-04 00:00:00","venue":"bbbb","teamone":"ehe","teamtwo":"aha",
"s_name":"aaa"},
{"start":"2016-11-23 00:00:00","end":"2016-11-24 00:00:00","venue":"bbbbbbbb","teamone":"ehe","teamtwo":"aha",
"s_name":"aaa"}]}
I need to get the teamone, teamtwo and s_name values from the matches while i need the start, end and the venue from the schedule table in one query.
Schedule table
Matches Table
Because of your SQL query, you should not forget to perform some form of a grouping (the way you select results from both table defines that):
$sql = "SELECT * from schedule s, matches m GROUP BY s.id"; //I assume that your table schedule has an `id`
Or, you can rework the query to be more readable:
$sql = "SELECT s.*, m.* FROM schedule s
INNER JOIN matches m ON m.schedule_id = s.id
GROUP BY s.id"; //I assume that you have such database design that you have defined foreign key on table `matches`.
Of course, the INNER JOIN above could be LEFT OUTER JOIN - it all depends on your database design.
I think it is the problem with mysqli_fetch_array().
Can you please change mysqli_fetch_array() to mysqli_fetch_assoc()

Fetching all Data from Multiple tables based on Single id

I have to select data from multiple tables based on single key value. I have one table called maintable where I will get all the ids from, and i have another 10 tables in the same database which have maintable.id as a foreign key. Now I have to retrieve data from the 10 tables where maintable.id matches in one single table.
The code I have tried is:
$sql = select id from maintable;
$runsql = mysql_query($sql);
while($sqlRow = mysql_fetch_array($runsql ,MYSQL_ASSOC)) {
for($i=1;$i<=10(This is another table count);$i++) {
$servSql = "select * from table.$i where ref_id = ".$sqlRow['id'];
$runServerSql = mysql_query($servSql);
while($serverRow = mysql_fetch_array($runServSql,MYSQL_ASSOC)) {
}
}
}
Try something like this in a join:
SELECT * FROM maintable m
INNER JOIN othertable o
ON m.id = o.id
That will select from both tables using an inner join ON the id column. You may want to look up a basic SQL tutorial to learn the basic types of joins you can use. Good luck!

How can you access two identically-named columns in a MySQL LEFT JOIN query?

I have two tables.
table_x:
id INT(11)
tag INT(11)
table_tags:
id INT(11)
name VARCHAR(255)
Then I use PHP to perform the following query:
SELECT * FROM table_x LEFT JOIN table_tags ON table_x.tag = table_tags.id
The only problem is: how do I access table_x.id and table_tags.id in the results?
Here is the PHP code:
$query = "SELECT * FROM table_x LEFT JOIN table_tags ON table_x.tag = table_tags.id";
$results = mysql_query($query);
while($row = mysql_fetch_array($results))
{
// how do I now access table_x.id and table_tags.id ???
}
You name the columns in your column list:
SELECT
table_x.id AS x_id,
table_tags.id AS tag_id,
other, columns, here
FROM table_x LEFT JOIN table_tags
ON table_x.tag = table_tags.id
In general, it's considered good form to name the columns you want returned explicitly rather than relying on * (which may cause the actual number, order, and names of columns to change if the underlying table structure changes). At the same time, you can alias the column with new names in the result set for ease of use (the AS keyword is optional in most SQL dialects).
Update: OP states in a comment that he must use "*". Although this is not recommended, you can do this:
SELECT
table_x.id AS x_id,
table_tags.id AS tag_id,
*
FROM table_x LEFT JOIN table_tags
ON table_x.tag = table_tags.id
which combines both the named columns you want and the (bad) "*" technique. Your columns will be included in the result set twice, in the first two column positions and in their regular positions in the column list. The values will be the same.
Use it like this
$query = "SELECT (table_x.id) AS xid, (table_tags.id) AS tid FROM table_x LEFT JOIN table_tags ON table_x.tag = table_tags.id";
$results = mysql_query($query);
while($row = mysql_fetch_array($results))
{
**//fetch id of table_x with xid**
**echo "table_x id: ".$row['xid'];**
//fetch id of table_tags with tid
**echo "table_tags id: ".$row['tid'];**
}

Categories