Why do i double my display in json - php

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

Related

How to correctly use WHERE with JOIN in SQL and PHP

So I'm trying to implement a JOIN in my PHP but I don't know how to include the WHERE clause with JOIN in my query.
I'm trying to do:
SELECT SpecialFacts.ConservationStatus, SpecialFacts.Reproduction, SpecialFacts.Length, Habitat.Type, Habitat.located
FROM SpecialFacts
INNER JOIN Habitat ON SpecialFacts.SpeciesID=Habitat.SpeciesID
WHERE SpeciesID="G. cuvier"
Basically I'm trying to make sure the join happens on the tables where the SpeciesID is G. cuvier but everything I have tried so far doesn't work and the error it is giving me now is "Column SpeciesID in where clause is ambiguous".
Here is my relevant PHP code:
<?php
include 'connect.php';
$result = mysqli_query($connect,"SELECT SpecialFacts.ConservationStatus, SpecialFacts.Reproduction, SpecialFacts.Length, Habitat.Type, Habitat.located FROM SpecialFacts INNER JOIN Habitat ON SpecialFacts.SpeciesID=Habitat.SpeciesID WHERE SpeciesID='G. cuvier'") or die("fail" . mysqli_error($connect));
$i = 0;
while($row = mysqli_fetch_array($result))
{
echo $row[$i];
$i = $i + 1;
}
Column SpeciesID exists in both tables, so it doesn't know which need to be compared to value given as G. cuvier. As you are writing every column name as table name with dot(.), the same should be in where condition column SpecialFacts.SpeciesID = "G. cuvier".
So query should be like:
SELECT SpecialFacts.ConservationStatus, SpecialFacts.Reproduction, SpecialFacts.Length, Habitat.Type, Habitat.located
FROM SpecialFacts
INNER JOIN Habitat ON SpecialFacts.SpeciesID=Habitat.SpeciesID
WHERE SpecialFacts.SpeciesID="G. cuvier"
It's not giving you that error because you're using WHERE incorrectly. It's giving you that error because there are multiple tables in your query that have a column with that name, hence the "ambiguous". You just need to disambiguate it by adding the table name to the identifier.
WHERE SpecialFacts.SpeciesID="G. cuvier"
or
WHERE Habitat.SpeciesID="G. cuvier"
Since you're inner joining the tables on that column, either table should work for the WHERE clause. I would suggest using the smaller table for performance reasons, but honestly I'm not 100% certain if it will matter or not. You can do EXPLAIN on each one to see how they compare.
Use below query instead
SELECT SpecialFacts.ConservationStatus, SpecialFacts.Reproduction, SpecialFacts.Length, Habitat.Type, Habitat.located
FROM SpecialFacts INNER JOIN Habitat
ON SpecialFacts.SpeciesID=Habitat.SpeciesID
WHERE SpecialFacts.SpeciesID='G. cuvier'
I have used single quote and used column name with table name.

How to user SQL two table field.? PHP

Here I want to access two table field but I cant get success. Here is my little code. please check that. I want to access Analysis.Right and tabl3.right.
I am printing its with foreach loop. like $res['Right'] of Analysis and $res['right'] of tabl3. when I try to print this it's show me error
Undefind index Right.
any one can help me
$qry = "select Analysis.Q_Id, tabl3.Q_Id, Analysis.Right, tabl3.right from tabl3 INNER JOIN Analysis ON Analysis.Q_Id = tabl3.Q_Id where Analysis.Q_Id = 3";
please help..
you have tow column with right name related to different table so there is not a column name right but 'Analysis.Right ' or 'tabl3.right'
or you can assign an alias for set the column name equalt to Right where you need .. eg:
$qry = "select
Analysis.Q_Id
, tabl3.Q_Id
, Analysis.Right as Right
, tabl3.right as Right_t3
from tabl3
INNER JOIN Analysis ON Analysis.Q_Id = tabl3.Q_Id where Analysis.Q_Id = 3";
Your result set has columns with the same name. Give them different names:
select t3.Q_Id, a.Right as a_right, t3.right as t3_right
from tabl3 t3 inner join
Analysis a
on a.Q_Id = t3.Q_Id
where a.Q_Id = 3;
When you look for the names in your code, look for a_right and t3_right.
Note that you don't need to return Q_Id twice. The ON clause guarantees that the values are the same.

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

Select using join tables and array in a table

Hi there I have 2 tables
|id|musicname|url|image|type
and the second table
|id|user|songslist|
inside songsids theres an array like this
1,3,5,6,8 etc ...
What Im aiming to do is select * from table1 and echo out the table1 as in an array but instead of tables two array , the actual row of table1.
So basically To take out each row that contains the id in songslist and put them all into a php array.
I have learned a lot about PHP arrays , but I'm not that good with mysql , Any Idea of how can I do that ?
EDIT
$selectmusiclist = mysql_query("SELECT * FROM music");
$songslist = array();
while ($songs = mysql_fetch_assoc($selectmusiclist)){
$songslist[] = $songs;
}
and then table 2 select:
$username="user1";
$selectuser = mysql_query("SELECT * FROM usersmusic where user=$username");
$user = mysql_fetch_assoc($selectuser);
$songslist = $user['songslist'];
NOW I need to tell the array $songslist[] to output only the songs with id $songslist contained ids
I think running a join like this will give you the results you are after.
SELECT * FROM usersmusic as um
join music as m
on um.songslist = m.id
where user = '$username'
If $username is not a static value make sure you escape it; don't want to get SQL injected in the future.
Also note the mysql_ driver is now deprecated you should consider updating to mysqli or PDO.

how to extract mysql data into json using php

i have retrieved mysql data from one table in json using the following script
$table_first = 'abc';
$query = "SELECT * FROM $table_first";
$resouter = mysql_query($query, $conn);
$set = array();
$total_records = mysql_numrows($resouter);
if($total_records >= 1){
while ($link = mysql_fetch_array($resouter, MYSQL_ASSOC)){
$set[] = $link;
}
}
echo json_encode($set);
how can i retrieved data from two other tables in which there is a foreign key of this table in both of those tables. OR simply how can i retrieved data from 3 mysql tables in php.
I believe the best way to go here is using a JOIN or just something like this:
$sql = "SELECT
tabl1.*, table2.*, tabl3.* FROM table1, table2, table3
WHERE
table1.fk1 = table2.id AND
table1.fk2 = table2.id";
//Do the whole selection process...
If you make the queries separately, you'll be forcing 3 queries onto your database and will end in a performance hit that you dont need. So, the idea is load all the data from the DB using joins or similar that and then encode the results. Is faster and you'll leave the merging work to MySQL
Hope I can help
You can get all data firstly.
Then merge the data array.
Finally use json_encode to change the data format.
There is a foreign key of this table in both so you can use "join" to retrieve values from other tables.
Suppose that there are two tables as State(st_id,st_name) and City(ct_id,ct_name,state_id). Now, primary key are st_id & ct_id respectively of tables State & City.
Connection between this two table can be establish by joining State.st_id and City.state_id.
Now, coming to your problem to retrieve data from two table State & City, we can make sql query like following,
$sql="select s.*, c.* from State s, City c
where s.st_id=c.state_id ";
Using above query you can fetch data from database and convert into json format and can send it to android system. here is a good article http://blog.sptechnolab.com/2011/02/10/android/android-connecting-to-mysql-using-php/. i hope you like it.
I believe your code roughly will look like this:
$query = "SELECT
A.column1 AS First_1
A.column2 AS First_2
B.column2 AS Second
C.column3 AS Third
FROM table1 A, table2 B, table3 C
WHERE
A.fk1 = B.id AND
B.fk2 = C.id";
where a column is a relevant record you want to show. Meanwhile,
AS will act as a key name in JSON.

Categories