How can I save time to run sql query? - php

I am a newbie and have very minimum experience to work with php and sql. I have tried the below code but it takes very large amount of time to run.
For each member of the students6 table, his/her Name and Registration number is collected from another table collegestudents and this process takes so much time that server gives
503 error
when students6 table contains huge amount of data. How can the code be changed
to accelerate the process?
$no1=0;
$zq1=mysqli_query($con, "select *
from students6
where CollegeCode='$college'
order by UniversityRollNo");
while($zq2=mysqli_fetch_array($zq1)) {
$xpa=mysqli_query($con, "select *
from collegestudents
where UniversityRollNo='$zq2[UniversityRollNo]'
and CollegeCode='$college'");//
$xp1a=mysqli_fetch_array($xpa);
$name=$xp1a['Name'];
$rgn=$xp1a['RegistrationNo'];
++$no1;
echo "<tr>
<td align='center' >$no1</td><td>$zq2[UniversityRollNo]</td>
<td>$name</td>
<td>$rgn</td>
<td>$zq2[SubjectPaper]</td>
<td align='center'>$zq2[Course]</td>
</tr>";
}

Do both queries in one JOINED query
$no1=0;
$stmt = $con->prepare("select *
from students6 s
JOIN collegestudents c ON c.UniversityRollNo = s.UniversityRollNo
where s.CollegeCode = ?
order by s.UniversityRollNo");
$stmt->bind_param('i',$CollegeCode); //<-- assumed that was holding the code????
$stmt->execute();
$results = $stmt->get_result();
while($zq2 = $results->fetch_assoc){
$name = $xp1a['Name'];
$rgn = $xp1a['RegistrationNo'];
++$no1;
echo "<tr>
<td align='center' >$no1</td><td>$zq2[UniversityRollNo]</td>
<td>$name</td>
<td>$rgn</td>
<td>$zq2[SubjectPaper]</td>
<td align='center'>$zq2[Course]</td>
</tr>";
}

Related

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.

sql query to fetch data column wise in php

i have created a table with the name of machine in database.
The columns are
edition, start and stop.
From my form, I am inserting multiple start and stop time for single edition.
like wise there are multiple edition.
How to display all data below edition and loop all the rows for single edition and if edition change then it display in another table.
I want to display reports and reports is refreshing after every 30 sec.
<?php
if (isset($_SESSION['city']))
{
$city = make_safe($_SESSION['city']);
}
$sql = "SELECT Distinct * FROM machine where city = '$city' AND DATE(created) = DATE(NOW())";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
?>
<tr>
<td class="scheduletime"><?php
echo $row["starttime"];
?></td>
<td class="actualtime"><?php
echo $row["stoptime"];
?></td>
<td class="actualtime"><?php
echo $row["Message"];
?></td>
</tr>
<?php
}
?>

retrieving and echoing multiple values from mysql column

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>

Mysqli query multiple tables

I'm trying to make a query that then displays certain results based on previous queries
The idea is that when someone logs into the page, it gets the session username and and saves it to a variable, from there the first query selects a row based on the session username, gets that value and does the same in the second query but on a different table this time getting the row based on the result from query 1 and query 3 is same as two and then its meant to echo it out
here's the code
$con = mysqli_connect("localhost","root","","boats4u");
$search = $_SESSION['myusername'];
if(mysqli_connect_errno())
{
echo "Failed to connect to database". mysqli_connect_error();
}
$pre_res = mysqli_query($con,"SELECT ownerNo FROM boatowner WHERE email ='$search'");
$pre_res = $pre_res -> fetch_assoc();
$result = mysqli_query($con,"SELECT boatNo FROM boatforrent WHERE ownerNo ='$pre_res'");
$result = $result -> fetch_assoc();
$result2 = mysqli_query($con,"SELECT * FROM boatviewing WHERE boatNo = '$result'");
echo "<table border='1'>
<tr>
<th>Client No</th>
<th>Boat No</th>
<th>View Date</th>
<th>Comments</th>
</tr>";
while ($row = mysqli_fetch_array($result2))
{
echo "<tr>";
echo "<td>". $row['clientNo']."</td>";
echo "<td>". $row['boatNo']."</td>";
echo "<td>". $row['viewDate']."</td>";
echo "<td>". $row['comment']."</td>";
}
echo "</table>";
?>
this is what displays
Notice: Array to string conversion in
E:\Download\Xampp\htdocs\owner.php on line 29
If I remove the first query then it no errors but obviously the search doesn't work then
any help appreciated
You should do one query and also parametize the search parameter. Something along the lines like:
$stmt = $con->prepare('
SELECT boatviewing.*
FROM boatowner owner
LEFT JOIN boatforrent ON boatforrent.ownerNo = owner.ownerNo
LEFT JOIN boatviewing ON boatviewing.boatNo = boatforrent.boatNo
WHERE owner.email = ?
');
$stmt->bind_param("s", $search);
$stmt->execute();
$result = $stmt->get_result();
Such code is normally more robust against SQL injection and it's also easier in case you change your database layout.
Next to that you actually run one query instead of three which allows the database to optimize data-retrieval and keeps roundtrips between the PHP script and the database server low.

php mysql query whitin While loop

I have a Mysql table which is use in php, first I use while loop to fetched the rows that as below
$q1 = "SELECT * FROM same_table WHERE `t_type`=1 AND `status`=0 AND `accept`='0'";
while($row1 = $q1->fetch_assoc()){
...table to output records
echo '<tr>
<td>$row1['col1']</td>
<td>$row1['col2']</td>
</tr>';
}
this will come out necessary records successfully.
secondly, there is another row with different purpose located under each of the above query row if the condition is true, with same table (within while loop),
while($row1 = $q1->fetch_assoc()){
echo '<tr>
<td>$row1['col1']</td>
<td>$row1['col2']</td>
</tr>';
$q2 = "SELECT * FROM same_table WHERE `t_type`=1 AND `status`=0 AND `bonus_accept`='0'";
$row2 = $q2->fetch_assoc();
if(($row2['col3'] == true){
echo '<tr>
<td>$row2['col1']</td>
<td>$row2['col2']</td>
</tr>';
}
}
so far the $q2 rows is show but always repeat the first record's data only even there is several row for $q1. if the data for $row2['col1'] is 100, the rest all show 100.
Please kindly help.

Categories