PHP how do I create a list of all tasks - php

Alright, I have a table of tasks this table has a foreign key which is the "projectID"
I am selecting all the rows within that table that have the same projectID. But I now want to output the results in a list ("<li></li>")
//Select tasks
$sql = "SELECT * FROM tasks WHERE projectID = '".$project_ID."'";
$result5 = $db->sql_query($sql);
$data5 = mysql_fetch_assoc($result5);

You're going to need to iterate through each of the rows and output the taskList column value:
$sql = "SELECT * FROM tasks WHERE projectID = '".$project_ID."'";
$result5 = $db->sql_query($sql);
$data5 = mysql_fetch_assoc($result5);
// this will let you handle an empty result set without a count.
if( $data5 )
{
// opening the list only if there are things to put there
echo "<ul >";
do
{
// output the value from one row.
echo "<li>" . $data5['taskName'].'</li>';
}while($data5 = mysql_fetch_assoc($result5));
echo "</ul>";
}
else
{
echo 'No tasks found!';
}

Related

I want to retrieve data from mysql php

$query_importer1 = "SELECT * FROM items where item_id ='".$row1["item_id"]."'limit 5 ";
$result_importer1 = mysqli_query($conn,$query_importer1);
for ($i=0; $i<=mysqli_num_rows($result_importer1); $i++)
{
$row = mysqli_fetch_assoc($result_importer1);
echo ''.$row['item_name'].'<br>';
}
i want all item name but its printing only one
You do not need to execute for loop on records, You can get all records using while loop, Plz refer below code
$query_importer1 = "SELECT * FROM items where item_id ='".$row1["item_id"]."' limit 5 ";
$result_importer1 = mysqli_query($conn,$query_importer1);
while($row = mysqli_fetch_assoc($result_importer1)){
echo $row['item_name'];
}

How to loop for every value in table AND find average

I am a beginner programmer and I am trying to find the average user rating of vendor 2.
My steps are as follows:
1. User 'Jimmy' gives a rating of 3 to vendor 2 (ratings are out of 5)
2.TABLE vendoratings is updated
3. ratingstot.php then calculates the total sum of ratings and the number of responses for ALL vendors before updating TABLE vendortotalratings shown below
4.User 'Jimmy' clicks on 'View average user rating'
5. The values totalratings and totalno are retrieved and divided in Javascript
var average= totalratings/totalno
6. totalno is displayed to user Jimmy. END
Question
1. I need help forming the for or while loop in ratingstot.php to calculate both ratings and no. of responses belonging to vendor X before inserting them in vendortotalratings table for every vendor.
ratingstot.php
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
error_reporting(E_ERROR);
try{
//Database connection
$conn = new mysqli("localhost", "XXXXXXXX_XXX", "XXXXXXXX", "XXXXXXXX");
//Unsure how to loop this to make vendor new value every loop
for($i=0; $i<=6; $i++){
$vendor = ??
//Calculate sum of ratings from table ratings
$result = $conn->query("SELECT SUM(ratings) FROM ratings WHERE vendorid = '".$vendorid."' ");
$row = mysqli_fetch_array($result);
$totalratings = $row[0];
//Calculate no. of responses (by counting no. of rows)
$result1 = $conn->query("SELECT * FROM ratings WHERE vendorid = '" . $vendorid."' ");
$totalno = mysqli_num_rows($result);
//inserting the results into the table
$query = " UPDATE vendortotalratings SET ";
$query .= " totalratings = '". $totalratings ."', totalno='".$totalno."' ";
$query .= " WHERE vendorid = '". $vendorid ."'";
$result2 = $conn->query($query);
}
echo($outp);
}
catch(Exception $e) {
$json_out = "[".json_encode(array("result"=>0))."]";
echo $json_out;
}
?>
I have no idea how to loop this, are there any easier steps to calculate average of ratings for each vendors?
Instead of all these complicated things, you can simplify the required solution like this:
(Assumption: I'm assuming that vendorid, ratings, totalratings and totalno columns are of type INT)
Use the below statement/query to get the totalratings and totalno corresponding to each vendorid.
$result = $conn->query("SELECT vendorid, SUM(ratings) as totalratings, COUNT(userid) as totalno FROM vendorratings GROUP BY vendorid");
Now loop through the $result result set using while() loop.
while($row = $result->fetch_array()){
...
}
In each iteration of above while() loop, check if the vendorid value already exists or not. If it exists, then UPDATE the row with new totalratings and totalno, otherwise INSERT a new row comprising of vendorid, totalratings and totalno.
while($row = $result->fetch_array()){
$res = $conn->query("SELECT vendorid FROM vendortotalratings WHERE vendorid = " . $row['vendorid']);
if($res->num_rows){
// Update the existing row
$conn->query("UPDATE vendortotalratings SET totalratings = ".$row['totalratings'].", totalno = ".$row['totalno']." WHERE vendorid = ".$row['vendorid']);
echo "Affected rows: " . $conn->affected_rows . '<br />';
}else{
// Insert a new row
$res = $conn->query("INSERT INTO vendortotalratings VALUES(".$row['vendorid'].", ".$row['totalratings'].",".$row['totalno'].")");
if($res) echo "New row inserted <br />";
}
}
So the complete code of try-catch block would be like this:
// your code
try{
//Database connection
$conn = new mysqli("localhost", "XXXXXXXX_XXX", "XXXXXXXX", "XXXXXXXX");
$result = $conn->query("SELECT vendorid, SUM(ratings) as totalratings, COUNT(userid) as totalno FROM vendorratings GROUP BY vendorid");
while($row = $result->fetch_array()){
$res = $conn->query("SELECT vendorid FROM vendortotalratings WHERE vendorid = " . $row['vendorid']);
if($res->num_rows){
// Update the existing row
$conn->query("UPDATE vendortotalratings SET totalratings = ".$row['totalratings'].", totalno = ".$row['totalno']." WHERE vendorid = ".$row['vendorid']);
echo "Affected rows: " . $conn->affected_rows . '<br />';
}else{
// Insert a new row
$res = $conn->query("INSERT INTO vendortotalratings VALUES(".$row['vendorid'].", ".$row['totalratings'].",".$row['totalno'].")");
if($res) echo "New row inserted <br />";
}
}
}catch(Exception $e) {
$json_out = json_encode(array("result"=>0));
echo $json_out;
}
The question doesn't clarify how the records are first inserted in vendortotalratings table. So, assuming that there is already a record in this table for each vendor, you don't have to write a whole new loop.
Updating vendortotalratings:
SQL can take care of calculating the total ratings and their counts in a single query which can then replace the loop that you have.
UPDATE vendortotalratings vtr
INNER JOIN
(
SELECT vendorid, SUM(ratings) AS sumratings, COUNT(ratings) AS countratings
FROM vendoratings
GROUP BY vendorid
) vr
ON vtr.vendorid = vr.vendorid
SET
vtr.totalratings = vtr.totalratings + vr.sumratings
,vtr.totalno = vtr.totalno + vr.countratings
Computing averages:
As for your second question, to compute the average, you could run the following query which will give you the run-time result:
SELECT vendorid, totalratings, totalno,
CAST((totalratings/totalno) AS DECIMAL(10, 2)) AS avgrating
FROM vendortotalratings;
The variable avgrating can be accessed directly in PHP by using $row['avgrating'] if you're fetching an associative array from the results, or by using the appropriate index number, which in this case should be $row[3]

How to display the content of more then one SQL database row

I am trying to retrieve the data stored in an unknown number of mySQL database rows and display them using HTML. At the moment I can display data from one row.
Each row has a unique id number, I was planning to iterate through by comparing this number to the variable counter. But it would then leave me with the issue of displaying the results in HTML. At the moment I am just echoing variables that contain data from the rows. However what I want to create is a HTML list that increases in length depending on how many rows are in the table.
Here is my current PHP code for retrieving a row from the database is:
$sql = "SELECT * FROM project_tasks WHERE project_name='$proj_name' AND task_id='$counter'";
$query = mysqli_query($db_conx, $sql);
$row = $query->fetch_assoc();
$task_id = $row["task_id"];
$proj_name = $row["project_name"];
$task_name = $row["task_name"];
$task_importance = $row["task_importance"];
$task_description = $row["task_description"];
$task_deadline = $row["task_deadline"];
$task_members = $row["task_members"];
$task_budget = $row["task_budget"];
At the moment I am just displaying some of the results in HTML using this code:
<div id="inner_container">
<?php echo "$task_id $proj_name $task_name $task_deadline"; ?>
</div>
$sql = "SELECT * FROM project_tasks WHERE project_name='$proj_name' AND task_id='$counter'";
$query = mysqli_query($db_conx, $sql);
while($row = $query->mysqli_fetch_assoc()) {
$task_id = $row["task_id"];
$proj_name = $row["project_name"];
$task_name = $row["task_name"];
$task_importance = $row["task_importance"];
$task_description = $row["task_description"];
$task_deadline = $row["task_deadline"];
$task_members = $row["task_members"];
$task_budget = $row["task_budget"];
echo "$task_id $proj_name $task_name $task_deadline";
}
Since you have built an associative array using fetch_assoc all you need to do is loop through that array. The OO example on http://php.net/manual/en/mysqli-result.fetch-assoc.php should get you what you need. A quick example:
$sql = "SELECT * FROM project_tasks WHERE project_name='$proj_name' AND task_id='$counter'";
$query = mysqli_query($db_conx, $sql);
echo '<div id="inner_container">';
while ($row = $query->fetch_assoc()) {
$proj_name = $row["project_name"];
$task_name = $row["task_name"];
$task_deadline = $row["task_deadline"];
echo "$task_id $proj_name $task_name $task_deadline";
};
/* free result set */
$row->free();
echo '</div>;

Returning each unique user from a MySQL table and also the count of the number of rows for each user

I am using the following MySQL query to generate a table for users in a database. The query is designed to just return one row for each user, even though there are multiple rows for each user. This works fine, however I also need to calculate the number of unique entries for each user, to enter into the table where it states HERE. Do I need to use another query to return the count for all entries, and if so how do I integrate this with the code I already have?
$query="SELECT from_user, COUNT(*) AS num FROM tracks GROUP BY from_user ORDER BY COUNT(*) DESC";
$result=mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$user = $row['from_user'];
echo "<tr>";
echo "<td>".$user."</td>";
echo "<td>uploads (**HERE**)</td>";
echo "<td>favourites (count)</td>";
echo "</tr>";
}
?>
</table>
Because you've already created the custom field 'num', you can use that to get the count!
Add the following line after user = ...
$count = $row['num'];
Then you can
echo "<td>uploads ($count)</td>";
It miss your table stucture to know your field name, but, if i well understand your question you can use count + distinct in mysql.
You can check this answer too.
SELECT DISTINCT(from_user) AS user,
COUNT(from_user) AS num
FROM tracks
GROUP BY from_user
ORDER BY num DESC";
For the second problem you can doing a second query, or do a join tracks .
I think, in your case it's easier to you to do se second query inside the loop to get all detail from 'user' result.
$query1="SELECT DISTINCT(from_user), COUNT(*) AS num
FROM tracks
GROUP BY from_user
ORDER BY COUNT(*) DESC";
$query2="SELECT * FROM tracks";
$result1=mysql_query($query1) or die(mysql_error());
$result2=mysql_query($query2) or die(mysql_error());
$user_array = array();
while ($row = mysql_fetch_array($result1)) {
$user = $row['from_user'];
$num = $row['num'];
$uploads_array = array();
while ($sub_row = mysql_fetch_array($result2)) {
if( $sub_row['from_user'] == $user ) {
//for example only due to the unknown structure of your table
$uploads_array[] = array(
"file_name" => $sub_row['file_name'],
"file_url" => $sub_row['file_url']
);
}
}
$user_array[] = array(
"name" => $user,
"num_entry" => $num,
"actions" => $uploads_array
);
}
// now the table with all data is stuctured and you can parse it
foreach($user_array as $result) {
$upload_html_link_arr = array();
$user = $result['name'];
$num_entry = $result['num_entry'];
$all_actions_from_user_array = $result['actions'];
foreach($all_actions_from_user_array as $upload) {
$upload_html_link_arr[] = sprintf('%s', $upload["file_url"],$upload["file_name"]);
}
$upload_html_link = implode(', ',$upload_html_link_arr);
$full_row = sprintf("<tr><td>%s</td><td>uploads : %s</td><td>favourites (%d)</td></tr>", $user, $upload_html_link, $num_entry);
// now just echo the full row or store it to a table for the final echo.
echo $full_row;
}
I hope this help, mike

What's the most efficient way to query and sort a semicolon separated list of ids according to their associated strings from another table?

I have 2 tables in a mysql database : users and pets. In the users table there is a field that contains a semicolon separated list of the pets that a user has (pet_ids = 1;2;3;4;). These ids correspond to unique ids (keys) in the pets table which contain the pet name (1 = rex, 2 = goldie, 3 = squeak, 4 = bubble).
I want to present a list of these pets on a PHP page in alphabetical order but retain the id of the pet name to pass as a variable to another page when the name of the pet is clicked.
What is the most efficient way to achieve this.
So far the list I generate is not in alphabetical order but in order that the pets were added -
Functions for querying the database
function getUserPets($user_id) {
$query= "SELECT pet_ids FROM users WHERE id='$user_id'";
$result = #mysql_query ($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while($row = mysql_fetch_array($result)) {
$the_pets = $row['pet_ids'];
}
return $the_pets; //1;2;3;4;
}
function getPetName($id) {
$name = "";
$query= "SELECT name FROM pets WHERE id='" . $id . "' ";
$result = #mysql_query ($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while($row = mysql_fetch_array($result)) {
$name = $row['name'];
}
return urldecode($name);
}
The code for generating the list ...
$petstring = getUserPets($userid);
$petsarray = explode(";", $petstring);
foreach ($petsarray as $pet_id) {
echo("<li><h4>" . writeListPetName($pet_id) . "</h4></li>");
}
What is the most efficient way to get an alphabetized list - I need to keep the database structure the same.
If you have to work with separated lists for a set of ids, rather than a properly normalised table, at least use a single db query to return the set of pet names rather than separate queries for each individual pet.
$petsarray = implode(',',explode(";", $petstring));
function getPetName($ids) {
$name = "";
$query= "SELECT id, name FROM pets WHERE id IN (" . $ids . ") ORDER BY name";
$result = mysql_query ($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while($row = mysql_fetch_array($result)) {
$names[$row['id']] = urldecode($row['name']);
}
return $names;
}
var_dump($names);
And don't use # to suppress errors, trap for them properly
P.S. Why do you need to urldecode() the pet names?

Categories