MySQL Loop from two different Tables - php

i want to get values from two different tables.
my problem is the table have no relation to each other but the "team_id"
i have a "player" and a "player_stat" table.
my result should look like:
Playername (from the "player" table)
Points: 8, Assists: 2, Fouls: 0 (from the "player_stat" table)
Playername 2 (from the "player" table)
Points: 8, Assists: 2, Fouls: 0 (from the "player_stat" table)
Here is my try:
<?php
/* PLAYERSTAT */
$attrs = array(PDO::ATTR_PERSISTENT => true);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT data.player_stat
FROM
(SELECT * from player_stat
UNION
SELECT * from player) data
");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
?>
echo $row["playername"]."<br>";
echo $row["points"]." ".$row["assists"];
<?php }
?>
my tables
player:
id
team_id
name
created
player_stat:
id
team_id
points
assists
fouls
created

Your SQL query could look like this (supposed the team_id is supposed to connect the stats and the player):
SELECT
player.playername,
player_stat.points,
player_stat.assists,
player_stat.fouls
FROM
player
LEFT JOIN player_stat ON (player.team_id = player_stat.team_id)
But it's a little bit strange, that the only relation between your tables is the team_id. If the output should be per player you have to introduce the relation between the stats and the player.
Say, your player can be in a team, there should be a team_id and a player_id. And your JOIN would then read:
LEFT JOIN player_stats ON (player.player_id = player_stats.player_id)
and as addition you can query for your team:
WHERE
player.team_id = 55
or you can add other joins so that you get your team details and so on.

Modify your select statement to read:
SELECT * FROM player, player_stat WHERE player.team_id = player_stat.team_id
The above is based on your statement that they have the team_id in common. If this is not what you are trying to achieve please refine your question and post the database schema.

Related

Check First on Table A, if not found Check on other table

I am creating a Log in and I have separate tables for Users A and Users B.
What I want to do is check first in first table if the Users that trying to Login is in the Table A,
if YES, it will not go to the Table B to check the Login credentials, if NOT, go to Table B and check the Login credentials.
Table A
SELECT * FROM tableA WHERE userId='$userId' AND password='$password'
Table B
SELECT * FROM tableB WHERE accountNumber='$accountNumber' AND password='$password'
Note: The 2 Tables has different Field Name userId and accountNumber.
I presume you are fetching the values of username and password from client side so I will tell you only what you asked for.
$getUserBasic1=$db->prepare('SELECT * FROM tableA WHERE userId="$userId" AND password="$password"');
$getUserBasic1->execute();
$user= $getUserBasic1->fetchAll();
if(count($user)>0)
{
//if yes do what you want here
}
else
{
$getUserBasic2=$db2->prepare('SELECT * FROM tableB WHERE accountNumber="$accountNumber" AND password="$password"');
$getUserBasic2->execute();
$user2= $getUserBasic2->fetchAll();
//write your code here
}
You could use an INNER JOIN and select both table results taking Table A's result first if it exists, else take Table B's result.
Assuming both tables have some sort of reference like the User ID you can use something like this:
SELECT tbla.*, tblb.* FROM tableA tbla
INNER JOIN tableB tblb ON tbla.userId = tblb.userId
WHERE userId='$userId' OR accountNumber='$accountNumber' AND password='$password'
ORDER BY userId ASC
LIMIT 1
The query above uses the cross-reference (userId in this case) and joins both tables together before querying the results. It orders the results by Table A before Table B but limits the result to 1 bringing either Table A or Table B out depending which is null.
Try combining the tables, some thing like:
SELECT * FROM tableA, tableB WHERE tableA.userId='$userId' AND tableA.password='$password' OR tableB.accountNumber='$accountNumber' AND tableB.password='$password'
I have not checked, so may not work, but see if this gets what you are looking for!
Something like this:
$sql = "SQL QUERY FOR TABLEA";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// checking if result in TABLE A
}
else{
//search in TABLE B by updating your sql value.
}
I hope that you want to check for the registered user, the best way to do that is to keep one table and just search there itself keeping the userID as the primary key.

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!

Selecting from two tables issue

This is was am trying to do table A has all profession categories & table B has users details.i want select from the 2 tables and match up categories selected,if user select 'web developer' from a dropdown of categories.i want to display list of users under web developer.
<?php
$q = intval($_GET['q']);
//select state of the two tables here
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
?>
///
<?php }?>
it's unclear from the question and lack of database details what and how to do the sql query ( which I think is what you are actually asking for ) but something along these lines perhaps.
select * from `tableB` b
left outer join `tableA` a on a.`professionid`=b.`professionid`
where a.`profession`='Web Developer'

Select players as team and mark in db as selected

i have one table named players with 2 columns: players and status
I need to select unique random teams!
Every team has X players as: Y base and Z pivots
Y and Z its set due input form
If in insert 3 for base and 2 for pivots The result should be like 3 teams or 3 players:
team 1
Base 1
Pivot 1
Pivot 2
team 2
Base 1
Pivot 1
Pivot 2
team 3
Base 1
Pivot 1
Pivot 2
After i generate teams i must be able to set status as "selected". If i need to create another team all users with status "selected" can't be use in another new team!
I currently use:
$nteams=$_POST['teams'];
$nbase=$_POST['base'];
$npivots=$_POST['pivots'];
$allplayers=$nteams*($nbase+$npivots);
require_once "connect_to_mysql.php";
$sqlCommand = "SELECT id FROM players ORDER BY RAND() LIMIT $allplayers";
$query = mysql_query($sqlCommand) or die (mysql_error());
if(mysql_num_rows($query)<$allplayers) // sanity
die('Not enough players!');
else
for($team=1;$team<=$nteams;$team++)
{
for($base=1;$base<=$nbase;$base++)
{
$row = mysql_fetch_array($query);
echo "Team $team Base $base = {$row['id']}<br />";
}
for($pivot=1;$pivot<=$npivots;$pivot++)
{
$row = mysql_fetch_array($query);
echo "Team $team Pivot $pivot = {$row['id']}<br />";
}
}
mysql_close();
Add WHERE status<>'selected' to your $sqlCommand statement
Store all read IDs from the database in an array, e.g. $selectedIds
Run update script UPDATE players SET status='selected' WHERE id IN ('.implode(',', $selectedIds).')
Side notes:
Consider rewriting the whole loop. It can be done in one while loop and one cursor/flag - let this be a homework :)
Beware of SQL Injection
You can wrap SELECT and UPDATE in a transaction to avoid inconsistency and conflicts

MySQL: Join (2 tables) vs single queries (1 table)

In PHP, I have an array of 11 persons where just the ID of each person is given:
$persons = array(1, 3, 39, 72, 17, 20, 102, 99, 77, 2, 982);
In my MySQL database, there's a table containing detailed information about each person:
TABLE personInfo
- ID (integer)
- name (string)
- birth date (timestamp)
- weight (decimal)
- ...
PROBLEM:
So now, I want to select the matching name for each ID in the PHP array. I can only imagine two solutions to do this:
1. for-loop:
foreach ($persons as $person) {
$result = mysql_query("SELECT name FROM personInfo WHERE id = ".$person);
}
2. logical operator OR
$result = mysql_query("SELECT name FROM personInfo WHERE id = 1 OR id = 3 OR id = 39 OR ...");
Both solutions are slow, aren't they?
But if I had another MySQL table containing the IDs of the PHP array ...
TABLE ids
- ID (integer)
... I could use a join to make a really fast MySQL query, right?
$result = mysql_query("SELECT a.ID, b.name FROM ids AS a JOIN personInfo AS b ON a.ID = b.ID");
QUESTION:
Is all this correct so far? If yes: Why is this so? The MySQL query is faster if I have a second table? With only one table it is incredibly slow? What is the fastest way to solve my problem (selecting the names matching the IDs of the PHP array)?
If you have lots of ids (several hundreds or more), feeding the values into a temporary table and joining it is actually faster.
You may want to read this article:
Passing parameters in MySQL: IN list vs. temporary table
IF you have ID's you should just query the Id's you have. So
$result = mysql_query("SELECT name FROM personInfo WHERE id = 1 OR id = 3 OR id = 39 OR ...");
would be right, although I would use
$result = mysql_query("SELECT name FROM personInfo WHERE id IN (1,2,3,4....) )

Categories