retrieving and echoing multiple values from mysql column - php

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>

Related

How to display two or more array on same table

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.

Print calculated Value of variable before its been calculated

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;

Call a database variable with SQL in PHP

I have a database with the tables program and class. The class table has a foreign key from program, the id_program. In the PHP code below, I fetch the data from the class table and works great.
<?php
$A_apotelesma = NULL;
$query = "SELECT * FROM class";
$result = mysqli_query($con,$query) or die('Error, query failed');
$i=-1;
if ($result) {
while ($row = mysqli_fetch_array($result)) {
$i++;
$A_apotelesma[$i]['id_program'] = $row['id_program'];
$A_apotelesma[$i]['id_class'] = $row['id_class'];
$A_apotelesma[$i]['onoma'] = $row['onoma'];
$A_apotelesma[$i]['imera'] = $row['imera'];
$A_apotelesma[$i]['time_start'] = $row['time_start'];
$A_apotelesma[$i]['time_end'] = $row['time_end'];
}
}
echo "<table border=\"1\" bordercolor=\"#ff8533\">";
if(is_array($A_apotelesma)){
echo " <tr>
<td colspan='7' align='center'><strong><br>Στοιχεία υπάρχοντων τμημάτων:</strong><br><br></td>
</tr>
<tr>
<td align='left'>ID</td>
<td align='left'>Πρόγραμμα</td>
<td align='left'>Όνομα</td>
<td align='left'>Ημέρα</td>
<td align='left'>Ώρα έναρξης</td>
<td align='left'>Ώρα λήξης</td>
</tr>";
foreach($A_apotelesma as $in => $value){
echo "<tr>
<th width='16%'>".$value['id_class']."</th>
<th width='16%'>".$value['id_program']."</th>
<th width='16%'>".$value['onoma']."</th>
<th width='16%'>".$value['imera']."</th>
<th width='16%'>".$value['time_start']."</th>
<th width='16%'>".$value['time_end']."</th>
<td>
Διαγραφή τμήματος<br>
<img src=\"images/del.jpg\" onclick='delete_class(".$value['id_class'].")' onmouseover=\"this.style.cursor='pointer'\" />
</td>
</tr>";
}
}
else
echo "<tr><th>Δεν βρέθηκαν τμήματα.</th></tr>";
echo "</table>";
?>
I just would like in the foreach command the ".$value['id_program']." not to be the id_program value, but another value, called onoma from the "program" table. I tried:
SELECT onoma FROM program LEFT JOIN class ON program.id_program=class.id_program
but no luck. Any help would be really appreciated.
Something like this should work. You cannot overwite the id_program, you have to call it something else in the select statement
SELECT Program.Onoma as Onoma
FROM Program
INNER JOIN Class
ON Class.id_program = Program.id;
Need to join two tables rather than selecting values from single table.Replace your query:
$query = "SELECT c.id_class,c.imera,c.time_start,c.time_end,p.program_name,p.onoma FROM class c INNER JOIN program p ON c.id_program=p.id_program";
See program_name name is used instead of program_id to display program name from program table.

How to get data from tables linked to a single user

First of all thank you for help me in advance.
I am looking to make a system were i am using 1 mysql DB and 2 tables or more and connect the tables to a user in a session. So lets suppose that the user logs in in a location, after login he can view from another table the data relative to this user, like a support ticket system (very simple one).
So i created a login system with sessions and then i want to display from another table only the data from that single user but when i do this i get all the data from the table, other users can see other users submissions and i wanna stop that and make it single user, single data display from that user only.
So here is the codes i am using:
<?php
// Validate Client Details
session_start();
if(!isset($_SESSION["user_username"]))
{
header("location:index.php?action=login");
}
?>
Then i got this code to display the records:
<?php
$connect = mysqli_connect("localhost", "root", "root", "helpdesk");
$sql = "SELECT * FROM users INNER JOIN tickets ON users.user_id = tickets.ticket_id";
$result = mysqli_query($connect, $sql);
?>
It works great but displays all and not just the single user details.
The Output i am using:
<table class="table table-striped">
<tr>
<th>Ticket ID</th>
<th>Client Username</th>
<th>Ticket Issue</th>
<th>Message</th>
<th>Priority</th>
</tr>
<?php
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row["ticket_id"]; ?></td>
<td><?php echo $row["user_username"];?></td>
<td><?php echo $row["ticket_issue"]; ?></td>
<td><?php echo $row["ticket_message"]; ?></td>
<td><?php echo $row["ticket_priority"]; ?></td>
</tr>
<?php
}
}
?>
</table>
I hope someone can help me on this, my best regards and thanks in advance.
You missed where condition
$name=$_SESSION['user_username']
$sql = "SELECT * FROM users INNER JOIN tickets ON users.user_id = tickets.ticket_id where user_username='$name'";

Mysql Php Pagination for varios table

I have this pagination script
1 Show-page
$result_p = mysqli_query($conexao, "select count(*) as count FROM `banner-destaque`");
$row_p = mysqli_fetch_array($result_p);
$quant_resul = 10;
$pagina = 1;
$paginas = ceil($row_p['count'] / $quant_resul);
$result = mysqli_query($conexao, "select * FROM `banner-destaque` limit 0 , " . $quant_resul);
The script works fine to one mysql table, but I need to reuse the same pagination script for other mysql tables with diferent sizes.
This is the table that show te results
<table class="flat-table flat-table-1">
<thead>
<th>Id</th> **//Here i need get tables columns name to make it dinamically for reuse in other tables**
<th>Photo</th>
<th>Title</th>
<th>Description</th>
</thead>
<tbody>
<tr>
<?php
while ($row = mysqli_fetch_object($result)) {
echo
'
//and here i need get all columns values to populate the above column.
<td>'.$row->id.'</td>
<td>'.$row->foto.'</td>
<td>'.$row->titulo.'</td>
<td>'.$row->descricao.'</td>';
};
?>
Any solution? Thanks. I'm using mysqli to connect to the database.
make a function from the query script and then call it passing the database table name to it as a parameter. You can then re-use this for different tables
function paginate($conexao, $tblname){
$result_p = mysqli_query($conexao, "select count(*) as count FROM ".$tblname);
$row_p = mysqli_fetch_array($result_p);
$quant_resul = 10;
$pagina = 1;
$paginas = ceil($row_p['count'] / $quant_resul);
$result = mysqli_query($conexao, "select * FROM ".tblname." limit 0 , " . $quant_resul);
return $result;
}
<table class="flat-table flat-table-1">
<thead>
<th>Id</th> **//Here i need get tables columns name to make it dinamically for reuse in other tables**
<th>Photo</th>
<th>Title</th>
<th>Description</th>
</thead>
<tbody>
<tr>
<?php
$result = paginate($conexao, 'banner-destaque');
while ($row = mysqli_fetch_object($result)) {
echo
'
//and here i need get all columns values to populate the above column.
<td>'.$row->id.'</td>
<td>'.$row->foto.'</td>
<td>'.$row->titulo.'</td>
<td>'.$row->descricao.'</td>';
};
?>

Categories