Hey guys I have one mysql table tick where i have some info like user id now to display that data I need to retrieve from user table name of the user based on that id
?php
$mysql5 = mysqli_query($dbc, "SELECT * FROM tick where status='1' ORDER BY dt DESC LIMIT 6 ");
if($indtbl = mysqli_fetch_array($mysql5))
{
$title = $indtbl['tickettitle'];
$company = $indtbl['companyname'];
$companyid =$indtbl['compid'];
$trackid = $indtbl['trackid'];
$assignto = $indtbl['assignto'];
$priority = $indtbl['priority'];
}
?>
and user table query is based on first one
<?php
$findresults2323 = mysqli_query($dbc, "SELECT * FROM users WHERE id= '$assignto'");
if($rest = mysqli_fetch_array($findresults2323))
{
$userimg = $rest['img'];
$fname1 = $rest['fname'];
$lname1 = $rest['lname'];
}
?>
now the problem is when i am fetching the array
<thead>
<tr>
<th class="text-left">Title</th>
<th>Company</th>
<th>Ticket ID</th>
<th>Assign To</th>
<th>Priority</th>
</tr>
</thead>
<?php
while($rowten = mysqli_fetch_array($mysql5)) {
$retrive11 = mysqli_fetch_array($findresults23);
?>
<tr>
<td><a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $rowten["tickettitle"]; ?></td>
<td><a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $rowten["companyname"];?> <?php echo $rowten["compid"];?></td>
<td><a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $rowten["trackid"]; ?></td>
<td><a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $retrive11['fname'];?></td>
<td><a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $rowten["priority"]; ?></td>
</tr>
<?php
}
?>
i am getting the error
Notice: Trying to access array offset on value of type null on line 459
line 459 is
<td><a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $retrive11['fname'];?></td>
what I am doing wrong
In order to use 2 queries, you need to run the second query inside of the loop so it retrieves the specific user record for the given result from the tick query.
while($rowten = mysqli_fetch_array($mysql5)) {
$assignto = $rowten['assignto'];
$findresults2323 = mysqli_query($dbc, "SELECT * FROM users WHERE id= '$assignto'");
$retrive11 = mysqli_fetch_array($findresults23);
However, this is very inefficient as it requires a query on the user table for every result in the tick query. The proper way of doing this is to use a single query with a join.
SELECT tick.*, users.fname FROM tick LEFT JOIN users ON (tick.assignto=users.id) where tick.status='1' ORDER BY tick.dt DESC LIMIT 6
The result of this query will have all the data from both your queries in one result.
Related
Trying to get counts from 2 different tables into a simple HTML table.
This is my code:
$sql = "SELECT COUNT(*) FROM tasks";
$result = $conn->query($sql);
$rowcount=mysqli_num_rows($result);
if ($result->num_rows > 0) { ?>
<table style="width:100%">
<tr>
<th>Total</th>
</tr>
<?php while($row = $result->fetch_assoc()) { ?>
<tr>
<td><?=$rowcount;?></td>
</tr>
<?php } ?>
</table>
<?php } else { echo "0 results"; } ?>
When I run the code, it shows the amount of rows in the table, but it also creates the amount of rows with the number in it (i.e. 281 rows).
Table
281
281
281
281 etc.
My idea was to copy and paste the above to show a second table set of results (if it was correct), but is there a better way of doing this? I've been looking at how I would display SELECT (select COUNT(*) from tasks) , (select count(*) from quotes) into the following format (HTML):
Table
Count
Tasks
281
Quotes
42000
First of all your query does produces only one row for a table, not 281.
The second - I omit usage of prepared SQL statements with placeholders, which should always be used in a real project whenever applyable.
$rows = [];
foreach(['Tasks', 'Quotes'] as $table ){
$result = $conn->query("SELECT '$table' as 'table', count(*) as 'count' FROM $table");
if( $result )
$rows[] = $result->fetch_assoc();
}
if( empty( $rows ) )
print "0 results";
else {?>
<table style="width:100%">
<tr><th>Table</th><th>Count</th></tr>
<?=implode(
"\n",
array_map(function($row){
return "<tr><td>${row['table']}</td><td>${row['count']}</td></tr>";
}, $rows)
)?>
</table>
<?php }
I've been looking at how I would display SELECT (select COUNT() from
tasks) , (select count() from quotes) into the following format
(HTML)
You can just run the queries query, and use the result of the first to create the first row of the table, then the result of the second to create the second row. Since COUNT queries always return exactly 1 row when there's no GROUP BY, it's quite simple to do really:
$sql1 = "SELECT COUNT(*) FROM tasks";
$result1 = $conn->query($sql1);
if ($row = $result1->fetch_array()) $taskCount = $row[0];
else $taskCount = "error";
$sql2 = "SELECT COUNT(*) FROM quotes";
$result2 = $conn->query($sql2);
if ($row = $result2->fetch_array()) $quoteCount = $row[0];
else $quoteCount = "error";
?>
<table style="width:100%">
<tr>
<th>Table</th>
<th>Count</th>
</tr>
<tr>
<td>Tasks</td>
<td><?php echo $taskCount; ?></td>
</tr>
<tr>
<td>Quotes</td>
<td><?php echo $quoteCount; ?></td>
</tr>
</table>
Another way, if you want the HTML structure to be less repetitive / dependent on the tables queries, is to UNION the SELECTs into a single query:
$sql = "SELECT 'Tasks' AS 'table', COUNT(*) as 'count' FROM tasks";
$sql .= " UNION ";
$sql .= "SELECT 'Quotes' AS 'table', COUNT(*) as 'count' FROM quotes";
$result = $conn->query($sql);
?>
<table style="width:100%">
<tr>
<th>Table</th>
<th>Count</th>
</tr>
<?php
while ($row = $result->fetch_assoc()) { ?>
<tr>
<td><?php echo $row["table"]; ?></td>
<td><?php echo $row["count"]; ?></td>
</tr>
<?php
}
?>
</table>
I have 2 tables tbl_category and tbl_food.
I sorted the items from tbl_food to tbl_category by adding category_id to tbl_food, where category_id in tbl_food is identical to id in tbl_category.
But how do I take title from tbl_category and display it in a table that represents items from tbl_food?
<?php
//query to get all admin from dtb
$sql = "SELECT * FROM tbl_food";
//Exectue the query
$res = mysqli_query($conn, $sql);
//check if executed
if($res==TRUE)
{
//count rows to check wether we have data
$count = mysqli_num_rows($res); //get all rows in dtb
$sn=1; //create a variable and assign the value
//check numb of rows
if($count>0)
{
//there is data
while($rows=mysqli_fetch_assoc($res))
{
//using while loop to get data from dtb
//get individual data
$id=$rows['id'];
$title=$rows['title'];
$description=$rows['description'];
$price=$rows['price'];
$active=$rows['active'];
$category_id=$rows['category_id'];
//display values in table
?>
<tr>
<td><?php echo $sn++; ?></td>
<td><?php echo $title; ?></td>
<td><?php echo $description; ?></td>
<td><?php echo $price; ?> kn</td>
<td><?php echo $active; ?></td>
<td><?php echo $category_id; ?></td>
</tr>
<?php
}}
else{
?>
<tr colspan="4">
<td class="error">No categories added</td>
</tr>
<?php
}
}
?>
I think you need to edit your query by adding JOIN to join tbl_category to tbl_food via category_id, at first, like this:
$sql = "SELECT food.*, category.title FROM tbl_food AS food INNER JOIN tbl_category AS category ON category.id=food.category_id";
Secondly it seems you have mistake in iterating query results. mysqli_fetch_assoc($res) returns an associated array, so it must be like this:
$rows = mysqli_fetch_assoc($res)
foreach($rows as $row){
$id=$row['id'];
$title=$row['title'];
$description=$row['description'];
$price=$row['price'];
$active=$row['active'];
$category_id=$row['category_id'];
//Doing stuff
}
You have to method for get title from tbl_category
1- JOIN Method: it is already mentioned above
2- Condition Method:
$sql = "SELECT tbl_food.*, tbl_category.title FROM tbl_food,tbl_category WHERE tbl_category.id=tbl_food.category_id";
foreach($sql as $row){
$id=$row['id'];
$title=$row['title'];
$description=$row['description'];
$price=$row['price'];
$active=$row['active'];
$category_id=$row['category_id'];
}
This is a tricky question to search, hence my post here. I have a a header that displays the sum of all the values in a column of a table that is printed below it. However the table is generated from a MYSQL table and the sum of the column values is calculated as it is generated. So somehow I have to have a variable printed but only after the table is generated and I am not sure how to pass the variables back up to the print statement so it doesn't always print out a 0
I feel like the solution is that the sum should call a script (Javascipt) that generates and prints the table returning the sum of columns to then be printed. But I am not sure how I would do this
echo "
<h3>EPL</h3>
<h5>Total Score: $total</h5>
<table class='table table-bordered'>
<tr>
<th>#</th>
<th>Name</th>
<th>Score</th>
</tr>
<tbody class='row_position'>"?>
<?php
require('db_config.php');
$tablename = $_SESSION['username'] . "_epl";
$_SESSION['tablename'] = $tablename;
$sql = "SELECT * FROM $tablename ORDER BY position_order";
$users = $mysqli->query($sql);
while($user = $users->fetch_assoc()){
$con = mysqli_connect('localhost', 'root', 'root', 'predictions');
$sql1 = "SELECT * FROM `predictions`.`".$tablename."` WHERE (CONVERT(`title` USING utf8) LIKE '%".$user['title']."%')";
$sql2 = "SELECT * FROM `predictions`.`epl` WHERE (CONVERT(`title` USING utf8) LIKE '%".$user['title']."%')";
$result = mysqli_query($con, $sql1);
$row = $result->fetch_assoc();
$position1 = $row['position_order'];
$result->close();
$result = mysqli_query($con, $sql2);
$row = $result->fetch_assoc();
$position2 = $row['position_order'];
$total += abs($position1-$position2);
?>
<tr id="<?php echo $user['id'] ?>">
<td><?php echo $user['position_order'] ?></td>
<td><?php echo $user['title'] ?></td>
<td><?php echo abs($position1-$position2); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
To explain the table further, each user has their own table with the same format username_league, so I use some php code to grab the table. Additionally I have a base case table in this case 'epl' in which I compare the tables and calculate the scores based on the absolute difference in the column 'position_order'.
You should always aim for separation of your code and presentation. And beyond that, your database code is extremely inefficient. You're re-creating an entire database object for every instance of your original query.
Just put your PHP code before the HTML, or better yet in a separate file.
<?php
$total = 0;
require('db_config.php');
$tablename = $_SESSION['username'] . "_epl";
$_SESSION['tablename'] = $tablename;
$sql = "SELECT id, position_order, title FROM `$tablename` ORDER BY position_order";
$users_result = $mysqli->query($sql);
while($user = $users_result->fetch_assoc()) {
$users[] = $user;
}
foreach ($users as $user) {
$sql1 = "
SELECT position_order FROM `$tablename` WHERE CONVERT(`title` USING utf8) LIKE '%$user[title]%' LIMIT 1
UNION
SELECT position_order FROM `epl` WHERE CONVERT(`title` USING utf8) LIKE '%$user[title]%' LIMIT 1
";
$result = $mysqli->query($sql1);
$row = $result->fetch_assoc();
$position1 = $row['position_order'];
$user["position1"] = $position1;
$row = $result->fetch_assoc();
$position2 = $row['position_order'];
$user["position2"] = $position2;
$total += abs($position1 - $position2);
}
?>
There you are; using a single database object, one third fewer queries, all your values in an array. They're ready to use later in the file, or in your separate HTML view:
<h3>EPL</h3>
<h5>Total Score: <?=$total?></h5>
<table class='table table-bordered'>
<tr>
<th>#</th>
<th>Name</th>
<th>Score</th>
</tr>
<tbody class='row_position'>
<?php foreach($users as $user):?>
<tr id="<?=$user['id'] ?>">
<td><?=$user['position_order'] ?></td>
<td><?=$user['title'] ?></td>
<td><?=abs($user["position1"]-$user["position2"]); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
I don't know enough about the structure here, but I'd be very surprised if you couldn't make this a single database query.
Output buffering is your friend! Simply call ob_start before outputting the table i.e.
ob_start();
echo "
<table class='table table-bordered'>
<tr>
<th>#</th>
<th>Name</th>
<th>Score</th>
</tr>
<tbody class='row_position'>"?>
...
then once you have done generating the table, you can collect the output of the table's content using ob_get_clean, output the header and then the table content:
...
$table = ob_get_clean();
echo "<h3>EPL</h3>
<h5>Total Score: $total</h5>";
echo $table;
I've done something similar to this table below quite a few times, where I use a while statement to populate the <td> section of a table, but I've never done it before where part of the <td> is populated with a foreach statement, and it's confusing me.
In this example, I create a table, then I populate the first column with a list of suppliers, based on the number of tables inside of my database. (each supplier has its own table).
$supplierList = array();
$showTable = "SHOW TABLES from dbOne";
$getSuppliers = mysqli_query($con, $showTable);
while ($row = mysqli_fetch_row($getSuppliers)) {
$supplierList[] = $row;
}
$supplierList = array_reduce($supplierList, 'array_merge', array());
Now I have my array that contains the list of all my suppliers, and I use that to generate the <td>s in my table.
<table>
<thead>
<th style="text-align: center;">Supplier</th>
<th style="text-align: center;">Earliest line</th>
<th style="text-align: center;">Latest line</th>
<th style="text-align: center;"># of total lines</th>
</thead>
<?php
foreach ($supplierList as $subList) {
$supplierName = $subList;
$earlyExp = "SELECT date FROM $subList ORDER BY date DESC LIMIT 1" ;
$earlyExpQuery = mysqli_query($con, $earlyExp);
$lateExp = "SELECT date FROM $subList ORDER BY date ASC LIMIT 1" ;
$lateExpQuery = mysqli_query($con, $lateExp);
$countLines = "SELECT * from $subList";
$countLinesQuery = mysqli_query($con, $countLines);
$countLinesCount = mysqli_num_rows($countLinesQuery);
while ($row = mysqli_fetch_array($earlyExpQuery)) {
$earlyExpDate = $row['date'];
?>
<tbody>
<td><img src = "/img/suppliers/<?= $supplierName ?>.png"></td>
<td style="text-align: center;"><?= $earlyExpDate ?></td>
<td style="text-align: center;"><?= $lateExpDate ?></td>
<td style="text-align: center;"><?= $countLinesCount ?></td>
</tbody>
<?php
}
}
?>
</table>
The table itself builds correctly, and displays each supplier in a unique row. I cannot figure out though how to populate the other parts of the row with the information based off the unique supplier in the foreach statement.
Okay, I sorted this out. In case it helps anyone else, here's how I did it:
This code goes in the same spot as my post above - so in between the header and the body of the table. I did not need to use any <tr>.
<?php
foreach ($supplierList as $subList) {
$supplierName = $subList;
$earlyExp = "SELECT * FROM $subList where dateOne != '' UNION SELECT * from $subList where dateTwo != '' ORDER BY dateTwo, dateOne ASC LIMIT 1" ;
$earlyExpQuery = mysqli_query($con, $earlyExp);
$lateExp = "SELECT * FROM $subList where dateOne != '' UNION SELECT * from $subList where dateTwo != '' ORDER BY dateTwo, dateOne DESC LIMIT 1" ;
$lateExpQuery = mysqli_query($con, $lateExp);
$countLines = "SELECT * from $subList";
$countLinesQuery = mysqli_query($con, $countLines);
$countLinesCount = mysqli_num_rows($countLinesQuery);
while ($row = mysqli_fetch_array($earlyExpQuery)) {
$earlyExpDate = $row['dateTwo'] ? $row['dateTwo'] : $row['dateOne'];
}
while ($row = mysqli_fetch_array($lateExpQuery)) {
$lateExpDate = $row['dateTwo'] ? $row['dateTwo'] : $row['dateOne'];
?>
They key is that I had to close off each individual while statement except the last one - closing that after I closed the </tbody> tag but before the </table>, like so:
</tbody>
<?php
}
}
?>
</table>
I have created these 3 columns in my mysql table so I can have a list of each users transactions.
ticket_date, ticket_num, ticket_result
I also created a function to echo the value in those columns and it worked successfully.
function.php:
$sql = "SELECT *
FROM members
WHERE user_id = '{$_SESSION['user_id']}'";
$query = $this->db_connection->query($sql);
while ($row = $query->fetch_object()) {
global $me, $me2, $date;
$me = $row->ticket_num;
$me2 = $row->ticket_result;
$date = $row->ticket_date;
}
transactions.php
<table class="table">
<thead>
<th>Date</th>
<th>Ticket ID</th>
<th>Result</th>
</thead>
<tr>
<td><?php echo $date; ?> </td>
<td><?php echo $me; ?> </td>
<td><?php echo $me2; ?> </td>
</tr>
</table>
My problem now is that if a user has more than one transaction how would I be able to echo each value from a particular column separately. I am trying to echo each transaction into a .
Would I be able to store each value as an array so I could call it like this?
$row->ticket_num['0']
EDIT: I meant to ask how can I store the transactions into their respective columns. Such as storing more than one $ticket_date that apply to each transaction. Could I store information into the columns as an array so I can call each transaction using the array pointer?
I think the best thing to do, would be not to use global variables for this, unless there is any reason that your function can't return this data, i.e. it's returning something else. You could have something like this in your function.php:
$sql = "SELECT *
FROM members
WHERE user_id = '{$_SESSION['user_id']}'";
$query = $this->db_connection->query($sql);
$return = array();
while ($row = $query->fetch_object()) {
array_push($return, array($row->ticket_num, $row->ticket_result, $row->ticket_date ));
}
return $return
Then you can do this in your transactions.php:
<table class="table">
<thead>
<th>Date</th>
<th>Ticket ID</th>
<th>Result</th>
</thead>
<?php
$ticket = Whatever_Function();
foreach($ticket as $t){
echo"<tr> <td> ".$t[0]." </td><td>".$t[1]."</td><td>".$t[2]."</td></tr>";
}
?>
</table>
Edit
In relation to your additional question in the comments, a database structure like this should be set up:
By doing this, you are separating it, so that every table belongs to one thing or action. These can then be related to each other using an SQL Join like this:
SELECT * FROM Transactions tr
JOIN Users u ON u.UID = tr.UID
JOIN Tickets ti ON ti.TID = tr.TID
By looking at the above SQL code snippet, you should be able to see how it matches up the columns on the different tables. This creates one big virtual table that you can then search for stuff with, where their column names prepended with their given pseudonyms.
So if you wanted to get the email address of everyone that bought the ticket whose price was over £20, even though the tables you need aren't directly connected you could do:
SELECT u.email FROM Transactions tr
JOIN Users u ON u.UID = tr.UID
JOIN Tickets ti ON ti.TID = tr.TID
WHERE ti.Price > 20
Do something like this:
global $me, $me2, $date;
while ($row = $query->fetch_object()) {
$me[] = $row->ticket_num;
$me2[] = $row->ticket_result;
$date[] = $row->ticket_date;
}
transactions.php
<table class="table">
<thead>
<th>Date</th>
<th>Ticket ID</th>
<th>Result</th>
</thead>
<?php foreach($me as $k => $m){
echo "<tr>";
echo "<td>".$date[$k]."</td>";
echo "<td>".$m."</td>";
echo "<td>".$me2[$k]."</td>";
echo "</tr>";
?>
</table>