PHP MYSQL, two tables - php

I have two tables and i want to echo the total call count once each user logins:
Login
Firstname | Lastname | Login ID
------------------------------
Tyler | Durden | 3
Call Count
Name | Call Count | Open | GrandTotal
------------------------------
Tyler Durden| 100 | 33 | 133
i tried:
<?php
$result = mysqli_query($mysqli, "SELECT * FROM csvdata WHERE Name=".$_SESSION['firstname']. ' ' .$_SESSION['lastname']." ");
while($res = mysqli_fetch_array( $result )) {
echo $res['Open'].' Open Calls';
echo $res['GrandTotal'].' Grand Total Calls';
}
mysqli_close($mysqli);
?>
But its not working, i think i have to join the the two tables to get it to work. What do you think?

Assuming your Call Count table is actually called csvdata, you'll want to format your SQL request string a bit by adding single quotes around the WHERE name = part.
<?php
$result = mysqli_query($mysqli, "SELECT * FROM csvdata WHERE Name='".$_SESSION['firstname']. ' ' .$_SESSION['lastname']."' ");
while($res = mysqli_fetch_array( $result )) {
echo $res['Call Count'].' Call Count';
echo $res['Open'].' Open Calls';
echo $res['GrandTotal'].' Grand Total Calls';
}
mysqli_close($mysqli);
?>

Good practice would require that you use primary keys to facilitate joins between tables and make sure two users with the same name can be differenciated.
In that case you may want to consider replacing the Name column in your Call Count table for your loginID. This way you could get your name from the Login table (as shown below). Also, as bad as it is to have duplicated data like your user's name in both tables, you do not need your GrandTotal column since you can easily get the sum of CallCount and Open to get the exact same number. In the end, your query should look more like this (assuming your tables are called Login and CallCount).
<?php
$result = mysqli_query($mysqli, "SELECT l.FirstName, l.LastName, cc.CallCount, cc.Open, (cc.CallCount + cc.Open) AS GrandTotal FROM Login AS l JOIN CallCount AS cc ON l.LoginID = cc.LoginID WHERE l.FirstName LIKE \"".$_SESSION['firstname']."\" AND l.LastName LIKE \"".$_SESSION['lastname']."\"");
// ...
?>

Related

Most Efficient way to MySQL Query inside query

i'm just learning PHP, and i have a question
Let just say, i have MySQL table "A"
Name | Job
--------|---------
Jynx | 1
Micah | 4
Nancy | 3
Turah | 1
And another table "B"
JobId | JobName
-------|-----------
1 | Lawyer
2 | Architec
3 | Farmer
4 | Mage
5 | Warrior
So supposedly in php i want to draw table that showed the content of table "A", but instead of displaying number at the "Job" colomn, they each display Job names from Table "B".
What is the most efficient way to do that?
For now, i just thinking of using
$conn = My database connect setting
$sql = "SELECT * FROM tableA ORDER BY Name";
$result = $conn->query($sql);
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>". $row['Name'] ."</td><td>";
$sql2 = "SELECT * FROM tableB WHERE JobId=$row['Job']";
$result2 = $conn->query($sql2);
while($row2 = mysqli_fetch_assoc($result2)) {
echo "<td>". $row2['JobName'] ."</td></tr>;
}
}
But wouldn't it take a lot of calculating proccess if there is multiple similliar colomn with hundreed of rows?
Is there any more efficient way to do this?
Sorry for my bad english
Thank you for your attention.
A join is definitely the way to go here.
SELECT a.Name, b.JobName
FROM tableA a
JOIN tableB b on (a.Job = b.JobId)
ORDER BY a.Name
Well, it is not easy to learn about JOIN, no time for now, but i will get to learn it latter.
As for now, i just get the idea to just use ARRAY instead
So before i draw the main table, i assign the supportive table (Table B) into associative array
$sql = "SELECT * FROM tableB ORDER BY Id";
$result = $conn->query($sql);
while($row = mysqli_fetch_assoc($result)) {
$job[$row['JobId']] = $row['JobName'];
}
And at the main table
$sql = "SELECT * FROM tableA ORDER BY Name";
$result = $conn->query($sql);
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>". $row['Name'] ."</td><td>". $job[$row['Job']];
}

Select from 2 tables not working with php mysql

I have two different tables of the following structure:
grouprel
id | userId | pupID | groupId
pupils
id | userId | fname | lname
pupId in groulrel is equal to id in pupils.
I want to fetch pupils from a different group and then order them by fname, lname.
Now I have two queries like this:
$q = "SELECT * FROM grouprel WHERE userid = ". $userid ." AND groupId = ". $_GET['id'] ."";
$r = mysqli_query($mysqli, $q);
while ($rows = mysqli_fetch_object($r)) {
$query = "SELECT id, fname, lname FROM pupils WHERE userid = ". $userid ." AND id = ". $rows->pupId ." AND status = 0 ORDER BY fname, lname";
$result = mysqli_query($mysqli, $query);
while($row = mysqli_fetch_object($result)) {
echo stuff...
}
}
This works, but it doesn't order the names alphabetically like I want to.
How could I fix this?
This is iterating over the first query:
while ($rows = mysqli_fetch_object($r)) {
And this iterates over each instance of the second query:
while($row = mysqli_fetch_object($result)) {
So if the first query returns 1,2,3, and each iteration of the second query returns A,B, then your output would be:
1 A
1 B
2 A
2 B
3 A
3 B
The second query is ordering by the ORDER BY clause you gave it. But you are ordering the entire output by the first query.
Ultimately, why do you need these separate queries at all? Executing a database query in a loop is almost always the wrong idea. It looks like all you need is one query with a simple JOIN. Guessing on your logic, something like this:
SELECT
pupils.id, pupils.fname, pupils.lname
FROM
pupils
INNER JOIN grouprel ON pupils.id = grouprel.pupId
WHERE
pupils.userid = ?
AND grouprel.groupId = ?
AND pupils.status = 0
ORDER BY
fname, lname
It may take a little tweaking to match exactly what you're looking for, but you can achieve your goal with a single query instead of multiple separate queries. Then the results of that query will be ordered the way you told MySQL to order them, instead of the way you told PHP to order them.

Working with 2 tables PHP & MySQL

I am working on a webpage that displays list of shops. I have 2 tables, shops and shops_sched.
+-shops-+
| id | title |
+-------------shops_sched-------------+
| id | shops_id | start_date | end_date |
Basically, the program displays the list of shops from the shops table, but if a value from shops.id is found # shops_sched.shops_id the page must output shops.title + 'coming soon'.
I understand this will be easy if I just place the date fields inside the table shops but due to programming restrictions I can't. I'm working on an existing project and I'm trying to minimize changes to existing functions. I can create new PHP functions if necessary though.
In addition, I need to get all the entries from the shops table. The Program needs to return all shops.title but for those shops whose id is found # shops_sched.shops_id, the program will have to return shops.title + "Coming Soon".
must output shops.title + 'coming soon'.
So do it like this:
$shops.title = "Donut-John";
echo $shops.title." coming soon";
To join the shops and shops_sched table
$query = SELECT `title` FROM `shops` JOIN `shops_sched` ON `shops`.`id` = `shops_sched`.`shops_id` WHERE `shops_sched`.`shop_id` = 5;
$result = mysql_query($query);
while($row = mysql_fetch_array($result) {
echo $row['title'] . 'coming soon';
}
For more about join you also can refer the following link
https://dev.mysql.com/doc/refman/5.0/en/join.html
http://www.tutorialspoint.com/mysql/mysql-using-joins.htm
Join the two tables :
SELECT shops.title
FROM shops INNER JOIN shops_sched ON shops.id = shops_sched.shops_id
The query should return only the the shops inside shops_sched
EDIT :
If I understood your question, try this :
SELECT shops.title, shops_sched.id
FROM shops LEFT JOIN shops_sched ON shops.id = shops_sched.shops_id
This will return all the titles, and the shops_sched.shops_id if shops.id = shops_sched.shops_id. In the other case, the hops_sched.shops_id will be null
Then you fetch the rows and if the second row is not null, print title + coming soon
Sample code : (Something like this)
$query = "SELECT `title`, 'shops_id' FROM `shops` LEFT JOIN `shops_sched` ON `shops`.`id` = `shops_sched`.`shops_id` WHERE `shops_sched`.`shop_id`";
$result = mysql_query($query);
while($row = mysql_fetch_array($result) {
if($row['shops_id'] != "")
{
echo $row['title'] . ' coming soon';
}
else
{
echo $row['title'];
}
}

Get id from table 1 to match with table 2

i am new to php, i have a idea of what i want to do but i am not sure how i can execute them
i have 2 table in mysql
table 1 contains:
ID|Name|AboutMe|Specialisation
Example:
101|Andrew|handsome|drawing
102|Jane|pretty|drawing
103|Daniel|cute|swimming
table 2 contains
ID|Link|Title
101|//image1.jpg|Drawing in the dark
102|//image2.jpg|Drawing in me
103|//image3.jpg|Fish swimming
I want to display some images that are link to a Specialisation only once my website run.
A flow of what i have
1)
// get all the ID with drawing as specialisation // will return 2 rows
select ID FROM table1 WHERE Specialisation = "Drawing";
id = ID
2) from each row that matches, take the ID to get the link from table 2 like so
// get row of the links from the userid
Select * FROM userdatafiles WHERE ID = id
store the links into a variable and send to my jquery to display.
So basically get the id of each row that matches drawing, and take the id to find the same id from table 2 and get the link, and send it out to jquery as a result.
As there are many rows that i have to send out and i need to use arrays & loops, i'm not sure how i can do that. Can someone guide me along to what i'm doing? Thanks!
UPDATE:
jquery:
$.ajax({
type: "POST",
//dataType: "json",
url: "CMS/PHP/displayFeatThumbs.php",
success: function(data) {
alert(data[0]);
}
});
PHP:
<?php
include 'dbAuthen.php';
$sql = 'SELECT * FROM userdatafiles JOIN users ON userdatafiles.UserID = users.UserID WHERE Specialisation = "Interactive Art & Technology"';
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $links[] = $row["Link"];
}
} else {
echo "0 results";
}
?>
no idea how to display the array index on jquery, tried both alert(data[0]), alert(data.links[0]);
You can use a natural join to connect 2 tables or more.
The query should look like this :
SELECT * FROM userdatafiles JOIN table1 ON userdatafiles.id = table1.id WHERE Specialisation = "Drawing"
The result will be a new table like this example:
table1: id | name | date
table2: id | city | country
result :
id | name | date | city | country
You can work with the data like this:
$result = mysql_query("Your Query");
while($row = mysql_fetch_object($result)){
//Access values with $row->ColumnName
}

PHP/Smarty Nested array from DB

Ok guys I am trying to access a php/mysql db via a nested query.
eg. I have 2 tables 1) persons and 2) registration. I have a refferal id tab in registrations. So when a user logs in he should be able to see 4 levels of registrations done below his id.
Table structure
Registration
id | Registration ID | regtype | Upline ID | uid |FirstName |MiddleName | LastName Last etc
personal
id| uid | upline | fname | miname | lname | etc and lot of other details
Now i am doing it like this to get to the first level.
$tid=$_GET['tid'];
$con = mysql_connect("localhost","db","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else
{
mysql_select_db("db", $con);
$resulta = mysql_query("SELECT * FROM personal WHERE id=$tid ");
$counta = mysql_num_rows($resulta);
while ($rowa = mysql_fetch_assoc($resulta)) {
$selid=$rowa['uid'];
$amount=$rowa['amountf'];
$plan=$rowa['planname'];
$resultfulla[] = $rowa;
}
$resultb = mysql_query("SELECT * FROM regtab WHERE regtab.upline=$selid " );
$countb = mysql_num_rows($resultb);
$rowz=array();
while ($rowb = mysql_fetch_assoc($resultb)) {
$rowz[] = $rowb;
}
Now i am able to get to one level but how do i cycle the second array and the arrays that will be produced later to get a tree structure. Or so....any help....
With the array rowz i am able to store the results of the 1st line regstration that i have done. Now using this array i need to find out how to get the second line registrations that have been done below array rowz.....
Join your queries and get the result.
$sql = "SELECT * FROM personal
LEFT JOIN regtab ON regtab.upline = personal.uid
WHERE personal .id=".$tid;
Get all the results in php.

Categories