To master2 in php, mysql. I'm new in php about 2 month
I need help. about update table.
I have page that display current table. when I click update button update, I want row 1, quantity in current table will decrease by IdItem from result table. So the equation will like this in current table quantity=quantity-quantityPass. So only field Item change quantity result. Now when I click update, it effect to all in table current result. any solution?
table for 'result'
+--------+-------------+--------------+-----------+--------+--------------+
| IdItem | username | rentItem | quantity | result | quantityPass |
+--------+-------------+--------------+-----------+--------+--------------+
| 84 | FahmiNazirul| Speaker | 1 | PASS | 1 |
+--------+-------------+--------------+-----------+--------+--------------+
| 86 | Andy | Keyboard | 3 | PASS | 2 |
+--------+-------------+--------------+-----------+--------+--------------+
| 89 | FahmiNazirul| Speaker | 5 | PASS | 3 |
+--------+-------------+--------------+-----------+--------+--------------+
table for current quantity 'update'
+--------+-------------+--------------+
| Id | Item | quantity |
+--------+-------------+--------------+
| 1 | Speaker | 10 |
+--------+-------------+--------------+
| 2 | Keyboard | 10 |
+--------+-------------+--------------+
tableupdate.php
$result = mysql_query("SELECT * FROM update where Item = Item");
echo "<table border='1'>
<tr>
<th>Item</th>
<th>Quantiti</th>
<th></th>
</tr>";
while($row = mysql_fetch_array($result))
{
$item= $row['Item'];
echo " <tr> ";
echo " <td> " . $row['Item'] . " </td> ";
echo " <td> " . $row['quantity'] . " </td> ";
echo " </tr> ";
}
echo "</table>";
echo " <a href ='quantityupdate.php?Item=$item' onclick='return Confirm_Box()' >Update</a>";
quantityupdate.php
$item =$_REQUEST['Item'];
// sending query
mysql_query("UPDATE update ,result SET update.quantity=update.quantity-result.quantityPass where update.Item = result.rentItem")
or die(mysql_error());
header("Location: update.php");
Use UPDATE with JOIN like this:
UPDATE kemaskini AS u
INNER JOIN result AS r ON u.Item = r.rentItem
SET u.quantity = u.quantity - r.quantityPass;
For the duplicate entries of the Item in the first table result you can do this:
UPDATE kemaskini AS u
INNER JOIN
(
SELECT rentItem, SUM(quantityPass) AS TotalquantityPass
FROM result
GROUP BY rentItem
) AS r ON u.Item = r.rentItem
SET u.quantity = u.quantity - r.TotalquantityPass;
SQL Fiddle Demo
mysql_query("UPDATE update ,result SET update.quantity=update.quantity-result.quantityPass where result.rentItem='$item' AND update.Item='$item'")
Related
I have subjects table contains subjects details and subject_student table contains the subjects selected by students. I want to select all the the subjects details selected by more than 2 students and also get the count of students for each subject selected by more than 2 students.
Subjects table
------------------------------
ID | Name | units
------------------------------
1 | web | 1
2 | programming | 1
3 | java | 1
4 | QA | 1
------------------------------
student_subject Table
Subject table
------------------------------
student_id | subject_id | status
------------------------------
1 | 1 | current
1 | 2 | current
2 | 1 | current
2 | 3 | current
3 | 1 | current
3 | 3 | current
4 | 1 | current
5 | 5 | current
------------------------------
so the result here must select the first row of subjects table and the 4 which is the count of students selected web subject
Here is the Query:
$query= "
SELECT s.sub_ID
, s.Name
, s.units
, count(st.subject_id) as cc
from subjects as s
LEFT
JOIN students_subject as st
ON s.ID = st.subject_id
GROUP
BY st.subject_id
Having count(st.subject_id)>2)
";
when I run the code it gives me this error:
Notice: Trying to get property of non-object
here is the PHP code:
global $con,$users;
$query= "SELECT s.sub_ID,s.Name, s.units,s.dept, count(st.subject_id)as cc from subjects as s LEFT JOIN students_subject as st
ON s.ID=st.subject_id GROUP BY st.subject_id Having count(st.subject_id)>2)";
//$query="SELECT * FROM subjects;";
$result=mysqli_query($con,$query);
if ( $result->num_rows == 0 ) // User doesn't exist
echo "Subjects doesn't exist!";
else { echo "
<tr>
<th>Subjects ID</th>
<th>Title</th>
<th>Units</th>
<th>Department</th>
<th>Check</th>
</tr>";
$r=0;
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['sub_ID'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['units'] . "</td>";
echo "<td>" . $row['cc'] . "</td>";
}
Check your query for names of tables and columns Subjects(ID,Name,units), students_subject(student_id,subject_id,status):
SELECT
sb.id AS sub_ID, -- !!!
sb.Name,
sb.units,
COUNT(st.student_id) AS cc
FROM Subjects sb
JOIN students_subject st ON st.subject_id=sb.id
GROUP BY sb.id,sb.name,sb.units
HAVING COUNT(st.student_id)>2
You also can use print_r in while for test names which were returned with mysqli_fetch_array
while($row = mysqli_fetch_array($result))
{
print_r($row);
...
Here doesn't need a bracket )
$query= "... Having count(st.subject_id)>2)"; // <--
Try to delete it
$query= "... Having count(st.subject_id)>2";
I have two tables, one is comments, and another is likesordislikes
comments
+----+--------+---------------+---------+
| id | userid | usercom | comname |
+----+--------+---------------+---------+
| 35 | 5 | check comment | 12 |
| 36 | 6 | comment test | 12 |
| 37 | 6 | third comment | 12 |
| 38 | 5 | number four | 12 |
| 39 | 7 | fifth | 13 |
| 40 | 4 | 6th | 13 |
| 41 | 18 | seven | 13 |
+----+--------+---------------+---------+
likesordislikes
+----+-------+------+-------+
| id | vtype | uid | comid |
+----+-------+------+-------+
| 1 | 0 | 5 | 35 |
| 2 | 1 | 6 | 35 |
| 3 | 1 | 7 | 35 |
| 4 | 0 | 8 | 36 |
| 5 | 1 | 5 | 36 |
| 6 | 1 | 9 | 35 |
| 7 | 1 | 10 | 36 |
| 8 | 1 | 11 | 36 |
| 9 | 1 | 20 | 35 |
| 10 | 0 | 9 | 35 |
| 11 | 1 | 21 | 37 |
+----+-------+------+-------+
In comments table userid is session id (logged in user) and comname is the post unique id on which comments are made by logged in users.
In likesordislikes table vtype is vote type where (0 = dislike , 1 = like), uid is logged in user id who likes or dislikes a comment and comid is from comments table (id) column
Now, i want to show total number of likes or dislikes under each comment for this specific comment.
the PHP code i am trying is here
$query1 = "SELECT
comments.id,
comments.usercom,
COUNT(likesordislikes.id) AS count
FROM
comments
LEFT JOIN likesordislikes ON
comments.id=likesordislikes.comid
WHERE likesordislikes.vtype='1'
GROUP BY
comments.id";
$query2 = "SELECT
comments.id,
comments.usercom,
COUNT(likesordislikes.id) AS count
FROM
comments
LEFT JOIN likesordislikes ON
comments.id=likesordislikes.comid
WHERE likesordislikes.vtype='0'
GROUP BY
comments.id";
$stmt = $DB->prepare($query1);
$stmt->execute();
$likes = $stmt->fetchAll();
$tlikes = count($likes);
$stmt = $DB->prepare($query2);
$stmt->execute();
$dislikes = $stmt->fetchAll();
$tdislikes = count($dislikes);
$slt = "SELECT * FROM `comments` where `comname` = '$c_name' and `post` = '$type'";
$res = mysqli_query($con, $slt);
while($fetch = mysqli_fetch_array($res)) {
echo $fetch['usercom']."<br />";
echo "Likes ".$tlikes."<br />";
echo "Dislikes ".$tdislikes;
}
that way, its not showing each comments likes/dislikes under that comment
in more clearer way, I want this result
Comments:
check comment
Likes 4 - Dislikes 2
comment test
Likes 3 - Dislikes 1
third comment
Likes 1 - Dislikes 0
number four
Likes - Dislikes
fifth
Likes - Dislikes
6th
Likes - Dislikes
seven
Likes - Dislikes
But its showing Likes 4 - Dislikes 2 on each comment on the article 12
Can anyone please check whats wrong in it?
You're basically getting all the likes and dislikes, for all the comments:
$query1 = "...";
$query2 = "...";
// ...
$tlikes = count($likes);
// ...
$tdislikes = count($dislikes);
And printing them for all the comments:
echo $fetch['usercom']."<br />";
echo "Likes ".$tlikes."<br />";
echo "Dislikes ".$tdislikes;
Which is why you're getting the same values for every comment. In order to fix your current code, you could create a map for $likes and $dislikes, like this:
$stmt = $DB->prepare($query1);
$stmt->execute();
$likes = array();
while($like = $stmt->fetch(PDO::FETCH_ASSOC){
$likes[$like['id']] = $like['count'];
}
And then, change your printing to something like:
while($fetch = mysqli_fetch_array($res)) {
echo $fetch['usercom']."<br />";
echo "Likes ".(empty($likes[$fetch['id']])?0:$likes[$fetch['id']])."<br />";
// ...
}
Note: You probably should filter the likes and dislikes queries the same way you filter the comments query (so you don't ask for things you won't use)
An alternative way is changing your three queries for a single one, which would change your code to something like this:
$slt =
"SELECT" .
" c.usercom," .
" SUM(CASE WHEN lod.vtype=1 THEN 1 ELSE 0 END) likes," .
" SUM(CASE WHEN lod.vtype=0 THEN 1 ELSE 0 END) dislikes" .
" FROM" .
" comments c LEFT JOIN likesordislikes lod ON lod.comid=c.id" .
" WHERE" .
" c.comname = '$c_name' AND c.post = '$type'" .
" GROUP BY" .
" c.id"
;
$res = mysqli_query($con, $slt);
while($fetch = mysqli_fetch_array($res)) {
echo $fetch['usercom']."<br />";
echo "Likes ".$fetch['likes']."<br />";
echo "Dislikes ".$fetch['dislikes'];
}
Here you have the query in case you want to see it working
Update
If you don't want to show two zeros, you could change your while to something like:
while($fetch = mysqli_fetch_array($res)) {
echo $fetch['usercom']."<br />";
if($fetch['likes']==='0' && $fetch['dislikes']==='0'){
$fetch['likes'] = '';
$fetch['dislikes'] = '';
}
echo "Likes ".$fetch['likes']."<br />";
echo "Dislikes ".$fetch['dislikes'];
}
Your query looks at the comname columns meaning it would give you everything for article 12 as you call it summed up and not separate for each of them.
You should be looking at the ids - something like
$slt = "SELECT * FROM `comments` where `id` = '$id' and `post` = '$type'";
where $id is the id in your comments table.
I am not sure how you can get this given the code you have shown but give it a try.
I need to be retrieve multiple unique values from an array set of data. Currently they are extracted as follows :
while($row1 = mysql_fetch_array($result1))
{
echo "<tr>".
"<td>".$row1[0] . "</td>".
"<td>".$row1[1] . "</td>".
"<td>".$row1[2] . "</td>".
"<td>".$row1[3] . "</td>".
"<td>".$row1[4] . "</td>".
"<td>".$row1[5] . "</td>".
"<td>".$row1[6] . "</td>".
"<td>".$row1[7] . "</td>".
//$row1[8] is the number of hours
"<td>".$row1[8] . "</td>".
//$row1[9] is the user
"<td>".$row1[9] . "</td>";
}
As commented above, I need to accumulate the hours per user. However, I have problem sorting the array as the user value has to be unique in the array whereas the number has to keep stacking.
Really confused now. Appreciate any help offered.
EDIT : $row1[8] is an integer yes.
The sample data output table ( sorry no image) will be as follows :
------------------------------------------------------------------------------------------
Users |Telephone | Address | Postal Code | Hobbies | Interest| FB |Twitter | Insta | Hours
------------------------------------------------------------------------------------------
John | 92238726 | SG | 345322 | Running | Movies | 1 | 0 | 0 | 5
Tom | 922382134 | MY | 345212 | Soccer | Movies | 1 | 0 | 0 | 8
Jerry | 92238726 | SG | 342122 | stamps | Nil | 0 | 1 | 0 | 5
John | 92238726 | SG | 345322 | Running | Movies | 1 | 0 | 0 | 12
Jerry | 92238726 | SG | 342122 | stamps | Nil | 0 | 1 | 0 | 2
Based on the output above which was extracted with the mysql_fetch_array, I'd like to sort the information to something like the following :
Users | Total Hours
John | 17
Tom | 8
Jerry | 7
SQL CODE :
"select DISTINCT jl.refno, jl.logno, jl.attendee, jl.jobsummary, FROM_UNIXTIME(jl.date, '%d/%m/%y') AS 'Date-In', from_unixtime(jl.dateout + (15*3600), '%d/%m/%y') AS 'Date-Out', #timein := (left(jl.timein,2)*60+right(jl.timein,2)) AS 'Time-In', #timeout := (left(jl.timeout,2)*60+right(timeout,2)) AS 'Time-Out', #temp := ((dateout -date)* 24 * 60) + #timeout - #timein AS 'temp', us.username from joblog jl, projects proj, users us where jl.project ='{$value}' AND proj.id ='{$value}' AND jl.staff = us.id"
Since you are using MySQL anyway, I recommend you to do it with an SQL. It's cleaner.
Edit your query to:
SELECT users, SUM(hours) as total FROM userTable GROUP BY users ORDER BY total DESC;
UPDATE - PHP Edition:
You can do it like this in PHP.
$counters = array();
while ($row1 = mysql_fetch_array($result1)) {
$counters[$row1[9]] += $rows1[8];
}
arsort($counters);
foreach ($counters as $name => $total) {
// do your output here
}
<?php
function totalHours($user){
$result=mysql_query("select sum(hours) as total from table_name where users='".$user."'");
$row=mysql_fetch_array($result);
return $row['total'];
}
$result=mysql_query("select * from table_name group by users");
echo "</table>";
echo "<tr>
<td>User</td>
<td>Total Hours</td>
</tr>";
while($row1 = mysql_fetch_array($result1))
{
echo "<tr>".
"<td>".$row1[0]. "</td>".
"<td>".totalHours($row1[0]). "</td></tr>";
}
echo "</table>";
?>
I need help creating a specific query, The following is an example of my deposit table, empId is a foreign key that refers to the primary key of my 'users' table which is 'userId'
Note:users table is not shown here
mysql> SELECT * FROM deposit
-> ;
+------------+---------------+---------+-------------+-------------+-------------+-------+
| CheckId | jobId | payRate | jobLocation | hours | date_paid | empId |
+------------+---------------+---------+-------------+-------------+-------------+-------+
| 1512 | entertainment | 12 | store1 | 10.00 | 2013-03-02 | 1 |
| 1510 | entertainment | 12 | store1 | 8.00 | 2013-03-01 | 1 |
| 1507 | retail | 10 | store1 | 8.00 | 2013-03-18 | 1 |
| 1506 | retail | 10 | store1 | 20.00 | 2013-03-19 | 1 |
+------------+---------------+---------+-------------+-------------+-------------+-------+
What i want is to calculate the sum of all hours for all specific jobId , in this case if i did the
query correctly it would look like this:
+---------------+---------------+---------+
| payID | payRate | hours |
+---------------+---------------+---------+
| entertainment| 12 | 18 |
| retail | 10 | 28 |
+---------------+---------------+---------+
In this case there is only two jobIds but it could have more than 2
This is the query i have and its only showing one payId, so I need help fixing it
also note that email is an attribute of my users table
<table>";
$query = "SELECT jobId, payRate, SUM(hours) AS 'All_Hours'
FROM users INNER JOIN deposit ON userId = empId
WHERE users.email = '" . $_SESSION['email'] ."'
GROUP BY jobId,payRate";
if (!$result) { //if the query failed
echo("Error, the query could not be executed: " .
mysqli_error($db) . "</p>");
mysqli_close($db); //close the database
} //by now we have made a successful query
while ($row = mysqli_fetch_assoc($result)){
echo "<tr><td>" .$row['jobId'] . "</td>
<td>" .$row['payRate'] . "</td>
<td>" .$row['All_Hours'] . "</td>
</tr>";
}
echo"</table>
you forgot to add GROUP BY clause in your query causing to have only one record in the result,
SELECT jobId, payRate, SUM(hoursWorked) AS 'All_Hours'
FROM users INNER JOIN paycheck ON userId = empId
WHERE users.email = 'session_email_here'
GROUP BY jobId, payRate
On the deposit table
SELECT jobId, payRate, sum(hours) FROM deposit
group by 1, 2
I would also suggest that you make it little bit more relational: jobId and jobLocation needs to be moved to new tables
For an accounting system, I'm using PHP & MySQL. I've two tables "GROUP" and "ACHEADS".
In the GROUP table, I have:
---------------------
| id (AI) | group |
---------------------
| 1 | Group 1 |
| 2 | Group 2 |
---------------------
In the ACHEADS table, I have:
-----------------------------------------
| id (AI) | ac_head | amount | j_id |
-----------------------------------------
| 1 | Something 1 | 2000 | 1 |
| 2 | Something 2 | 1000 | 1 |
| 3 | Something 3 | 5000 | 2 |
| 4 | Something 4 | 4000 | 2 |
| 5 | Something 5 | 8000 | 2 |
-----------------------------------------
I've joined the two tables as GROUP.id <<->> ACHEADS.j_id
Now I need to preview the data like this:
----------------------------------------------
Particulars | Details | Total |
----------------------------------------------
Group 1 | | |
Something 1 | 2000 | |
Something 2 | 1000 | 3000 |
----------------------------------------------
Group 2 | | |
Something 3 | 5000 | |
Something 4 | 4000 | |
Something 5 | 8000 | 17000 |
----------------------------------------------
GRAND TOTAL | | 20000 |
------------------------------------==========
Challenges
The table will be dynamic and will generate within a PHP loop (I'm
using a WHILE loop)
Remember: it's a table and if I miss echoing a td, then the table will break up
Problems
When I'm using the loop it's echoing the data on the Details td
accurately. But the sum of the details row according to j_id is also
echoing in each td
Preview here:
----------------------------------------------
Particulars | Details | Total |
----------------------------------------------
Group 1 | | |
Something 1 | 2000 | 3000 |
Something 2 | 1000 | 3000 |
----------------------------------------------
Group 2 | | |
Something 3 | 5000 | 17000 |
Something 4 | 4000 | 17000 |
Something 5 | 8000 | 17000 |
----------------------------------------------
My thoughts
If I can check whether it is the last data of the query, if isset,
then echo the total amount with it's td. (But remember the
Challenge#2)
Does it require a foreach loop?
I failed
I tried checking max(id), it works fine in SQL, but can't use it in
condition within a loop.
(If you still can't understand me, then on the second phase, I'll post my code.)
I would do 2 loops:
Fetch id from GROUP
Fetch amount from ACHEADS based on j_id
This would look something like (non-tested code):
echo '<table><tr><td>Particulars</td><td>Details</td><td>Total</td></tr>';
$total = 0;
$q1 = "SELECT id FROM `GROUP`";
$res1 = mysqli_query($q1);
while($row1 = mysqli_fetch_assoc($res1)) {
echo
$group_total = 0;
$j_id = $row1[id];
$q2 = "SELECT ac_head, amount FROM ACHEADS WHERE j_id = $j_id";
$res2 = mysqli_query($q2);
while($row2 = mysqli_fetch_assoc($res1)) {
echo '<tr><td>' . $row2[ac_head] . '</td>';
echo '<td>' . $row2[amount] . '</td></tr>';
$group_total = $group_total + $row2[amount];
$total = $total + $row[amount];
}
echo '<tr><td colspan="3" align="right">' . $group_total . '</td></tr>';
}
echo '<tr><td>GRAND TOTAL</td>';
echo '<td colspan="2" align="right">' . $total . '</td></tr>';
echo "</table>";
njk rockz!
It worked nicely. Thanks a lot, brother - it helped me a lot, I can't explain.
Here is my final code:
<tr style="background: #000; color:#fff;">
<th style="width:150px;">Particulars</th>
<th>Details</th>
<th>Amount</th>
</tr>
<tr>
<td>Opening Balance</td>
<td></td>
<td>500000</td> <!-- till not dynamic -->
</tr>
<?php
$total = 0;
$se = "SELECT * FROM group";
$res = mysql_query($se) or die (mysql_error());
while ($row = mysql_fetch_array($res))
{
?>
<tr>
<td colspan="3" style="font-weight:bold;"><?php echo $row['group']; ?></td>
</tr>
<tr>
<?php
$group_total = 0;
$se1 = "SELECT ac_head, amount FROM `acheads` WHERE `j_Id` = '".$row['id']."'";
$res1 = mysql_query($se1) or die (mysql_error());
while ($row1 = mysql_fetch_array($res1))
{
$group_total = $group_total + $row1['amount'];
?>
<td><?php echo $row1['ac_head']; ?></td>
<td><?php echo $row1['amount']; ?></td>
<td> </td>
</tr>
<?php
}
echo '<tr><td colspan="3" align="right">' . $group_total . '</td></tr>';
}
?>
</table>
</code>