Combine multiple table results into one table in php - php

I followed a web tutorial on how to build a basic search engine from my database the problem is that when I get the results displayed it shows each result in its own table on my page? I want to merge the results so they all show under one table in html.
<?php
include("dbconnect.php");
if(!isset($_POST['search'])) {
header("Location:www.bacons.me");
}
$search_sql="SELECT * FROM users WHERE username OR FirstName LIKE '%".$_POST['search']."%'";
$search_query=mysql_query($search_sql);
if(mysql_num_rows($search_query) !=0) {
$search_rs=mysql_fetch_assoc($search_query);
}
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="description" content="Bacons.me">
<meta name="keywords" content="HTML,CSS,JavaScript">
<meta name="author" content="James Narey">
<meta name=viewport content="width=device-width, initial-scale=1">
<link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16" />
<link rel="stylesheet" type="text/css" href="main.css" >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<title>Bacons.me</title>
</head>
<body>
<h1 class="logo">BACONS.ME</h1>
<nav>
<ul>
<li>Home</li>
<li>About</li>
<li>Search</li>
<li>Contact</li>
</ul>
<div class="handle">Menu<span class="arrow"> ▾</span></div>
</nav>
<p>Search Results</p>
<?php if(mysql_num_rows($search_query) !=0) {
do { ?>
<table>
<tr>
<th>Username</th>
<th>First Name</th>
<th>Surname</th>
<th>Shift</th>
<th>Agency</th>
</tr>
<tr>
<td><?php echo $search_rs['username']; ?></td>
<td><?php echo $search_rs['FirstName']; ?></td>
<td><?php echo $search_rs['LastName']; ?></td>
<td><?php echo $search_rs['Shift']; ?></td>
<td><?php echo $search_rs['Agency']; ?></td>
</tr>
<br>
</table>
<?php
} while ($search_rs=mysql_fetch_assoc($search_query));
} else {
echo "No results found";
}
?>
<html>
<title>results</title>
<head>
</head>
<body>
</body>
</html>
<footer>
<p class="footer">Website created by James Narey 2015.</p>
</footer>
</body>
</html>}

Put your table tag outside your do while loop, otherwise it would create new table at every iteration of the loop.
Your code structure should be like this
<?php if(mysql_num_rows($search_query) !=0) {?>
<table>
<?php do { ?>
<tr>
<th>Username</th>
<th>First Name</th>
<th>Surname</th>
<th>Shift</th>
<th>Agency</th>
</tr>
<tr>
<td><?php echo $search_rs['username']; ?></td>
<td><?php echo $search_rs['FirstName']; ?></td>
<td><?php echo $search_rs['LastName']; ?></td>
<td><?php echo $search_rs['Shift']; ?></td>
<td><?php echo $search_rs['Agency']; ?></td>
</tr>
<br>
<?php
} while ($search_rs=mysql_fetch_assoc($search_query));
?>
</table>

...} while ($search_rs=mysql_fetch_assoc($search_query));
I suspect this is the issue. You're creating a table for each time you fetch the next record. You probably want to do something like this:
<table>
<?php if(mysql_num_rows($search_query) !=0) {
do { ?>
// fill in table...
<?php
} while ($search_rs=mysql_fetch_assoc($search_query));
?>
</table>
Notice the table tags are outside the loop, so you'll only create a new row for each record you fetch

Just place the table tags outside the loop structure:
<table> do { ?> <tr>
<th>Username</th>
<th>First Name</th>
<th>Surname</th>
<th>Shift</th>
<th>Agency</th> </tr> <tr>
<td><?php echo $search_rs['username']; ?></td>
<td><?php echo $search_rs['FirstName']; ?></td>
<td><?php echo $search_rs['LastName']; ?></td>
<td><?php echo $search_rs['Shift']; ?></td>
<td><?php echo $search_rs['Agency']; ?></td> </tr> <br> <?php } while ($search_rs=mysql_fetch_assoc($search_query)); </table>

Related

Is there a way to speed up the load time of an HTML page that contains PHP?

Looking for any insights as to how to potentially speed up the page load time of the following:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tournament Details</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="content">
<<h2><center><font face="libel" size="8px" color="#FF7A59">Past Tournaments</font></center></h2>
<p>
<table>
<thead>
<tr>
<th>Date</th>
<th>Game</th>
<th>Type</th>
<th>Link</th>
<!--<th>Short URL</th>-->
<th>Winner</th>
<th># of Players</th>
</tr>
</thead>
<?php
$apikey = 'MYAPIKEY';
$jsonData = json_decode(stream_get_contents(fopen("https://api.challonge.com/v1/tournaments.json?state=all&api_key=$apikey", "r")),TRUE);
$finalJsonArr = array_column($jsonData,'tournament');
rsort($finalJsonArr);
?>
<tbody>
<tr>
<?php foreach($finalJsonArr as $arr){ ?>
<td><?php echo substr($arr['started_at'],0,10); ?></td>
<td><?php echo strtoupper($arr['game_name']); ?></td>
<td><?php echo strtoupper($arr['tournament_type']); ?></td>
<td> <a href="<?php echo $arr['full_challonge_url']."/standings"; ?>"</a>CLICK TO VIEW RESULTS</td>
<!--<td><?php echo $arr['url']; ?></td>-->
<td><?php
$matches = json_decode(stream_get_contents(fopen("https://api.challonge.com/v1/tournaments/".$arr['url']."/matches.json?state=all&api_key=$apikey", "r")),TRUE);
$participant = json_decode(stream_get_contents(fopen( "https://api.challonge.com/v1/tournaments/".$arr['url']."/participants.json?state=all&api_key=$apikey", "r")),TRUE);
// Extract subarrays
$participants = array_column($participant, "participant");
// index by id
$participants = array_column($participants, null, "id");
$numItems=count($matches);
$i = 0;
foreach ( $matches as $match ) {
// Extract player ID's
$id1 = $match['match']['player1_id'];
$id2 = $match['match']['player2_id'];
$id3 = $match['match']['winner_id'];
if(++$i===$numItems) {
echo $participants[$id3]["name"];
}
}
?></td>
<td><?php echo $arr['participants_count']; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</p>
</div>
</body>
</html>
I'm positive it's the 5th Column containing the name of the winner that is bogging the page down, however I'm not sure how to do this any differently in order to improve load speed.

styling a "order by desk" query table

I have made a script that is giving me the top 5 players according to most credits trough a desc 0,5 sql query
This is in a table, but it ain't really doing as i what it to go, what it does is every row it gives the table header, and its not making it as 1 table (see this screenshot)
this is my php and css:
<?php
include('connect.php');
$result = $db->prepare("SELECT * FROM `tbl_users` WHERE `credits` >'0' ORDER BY `credits` DESC LIMIT 0,5");
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style2.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Great+Vibes' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="floated_elements">
<table>
<thead>
<tr>
<th> ID </th>
<th> Wie </th>
<th> Hoeveel </th>
<th> email </th>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo $row['userID']; ?></td>
<td><?php echo $row['userName']; ?></td>
<td><?php echo $row['credits']; ?></td>
<td><?php echo $row['userEmail']; ?></td>
</tr>
</tbody>
</table>
<?php
}
?>
</div> <!-- Closing floated elements -->
<script>
$('table tr').each(function(){
$(this).find('th').first().addClass('first');
$(this).find('th').last().addClass('last');
$(this).find('td').first().addClass('first');
$(this).find('td').last().addClass('last');
});
$('table tr').first().addClass('row-first');
$('table tr').last().addClass('row-last');
</script>
</body>
</html>
i found that for rule and tried to apply it but not really giving the correct results
Edited to give additional code cause asked for
You have started for loop and put everything into that. Its not a right way. Try as below :
<?php
include('connect.php');
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style2.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Great+Vibes'
rel='stylesheet' type='text/css'>
</head>
<body>
<div class="floated_elements">
<table>
<thead>
<tr>
<th>ID</th>
<th>Wie</th>
<th>Hoeveel</th>
<th>email</th>
</tr>
</thead>
<tbody>
<?php
$result = $db->prepare("SELECT * FROM `tbl_users` WHERE `credits` >'0' ORDER BY `credits` DESC LIMIT 0,5");
$result->execute();
for($i=0; $row = $result->fetch(); $i++){ ?>
<tr>
<td><?php echo $row['userID']; ?></td>
<td><?php echo $row['userName']; ?></td>
<td><?php echo $row['credits']; ?></td>
<td><?php echo $row['userEmail']; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<script>
$('table tr').each(function(){
$(this).find('th').first().addClass('first');
$(this).find('th').last().addClass('last');
$(this).find('td').first().addClass('first');
$(this).find('td').last().addClass('last');
});
$('table tr').first().addClass('row-first');
$('table tr').last().addClass('row-last');
</script>
</body>
</html>

Increasing number of columns fails datatable in php

im having table reading values from database using PDO and display it in table,Then finally i used Datatable javascript code.Now my table having pagination,searching option.
But now i want to include one more column as 'Action' to do edit, delete fucntion.When i include these fifth column as Action. Then my table appears as normal..not as datatable format (pagination,searching option is not there). My coding below:
<?php
include("config.php");
include("header.php");
try {
$sql = "SELECT * FROM auditplan";
$stmt = $DB->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
?>
<link rel="stylesheet" href="<?=BASE_URL?>/bootstrap/css/bootstrap.css">
<link rel="stylesheet" href="<?=BASE_URL?>/bootstrap/css/bootstrap.min.css">
<script type="text/javascript" src="<?=BASE_URL?>js/jquery2.0.2.min.js"></script>
<script type="text/javascript" src="<?=BASE_URL?>js/jquery.dataTables.js"></script>
<script type="text/javascript" src="<?=BASE_URL?>js/jquery.dataTables.min.js"></script>
<link href="<?=BASE_URL?>themecss/datatables/dataTables.bootstrap.css" rel="stylesheet">
<script src="<?=BASE_URL?>themejs/plugins/datatables/dataTables.bootstrap.js"></script>
<script src="<?=BASE_URL?>themejs/jquery-ui-1.10.3.js"></script>
<script src="<?=BASE_URL?>themejs/jquery-ui-1.10.3.min.js"></script>
<div class="col-sm-9 col-md-10 main">
<h1 class="page-header"> Audit Plan </h1>
<a href="Auditplanentry.php" class="btn btn-primary" >Add New</a>
<table class="table table-striped" id="auditplantbl">
<thead>
<tr>
<th>Audit ID</th>
<th>Year</th>
<th>Month</th>
<th>Status</th>
<th>Comments</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
foreach($result as $row){ ?>
<tr>
<td><?php echo $row['auditid']?></td>
<td><?php echo $row['year'] ?></td>
<td><?php echo $row['month'] ?></td>
<td><?php echo $row['status']?></td>
<td><?php echo $row['comment']?></td>
</tr>
<?php }
?>
</tbody>
</table>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#auditplantbl').dataTable({
"bLengthChange": false,
});
});
</script>
You have 6 columns in your table header but only 5 in your body, you need to match the same number of columns in your header and body for datatable to work fine.
You need to add one in the body to add the buttons or whatever you were planning to do to delete or edit your items :
<?php
foreach($result as $row){ ?>
<tr>
<td><?php echo $row['auditid']?></td>
<td><?php echo $row['year'] ?></td>
<td><?php echo $row['month'] ?></td>
<td><?php echo $row['status']?></td>
<td><?php echo $row['comment']?></td>
<td> edit link / delete link </td>
</tr>
<?php }

jQuery DataTable appears without pagination control

I'm trying to insert Bootstrap pagination to my dynamic table content which I extract from my database as below, but nothing works:
<?php
$sn = $_POST["SN"];
$Reference = $_POST["Reference"];
$Libelle = $_POST["Libelle"];
$NOMENCLATURE = $_POST["NOMENCLATURE"];
$matricule = $_POST["matricule"];
include "./Connections/localhost.php";
$sqlTous = "
select mat.SN, mat.NOMENCLATURE, mat.ID_materiel, mat.Reference, mat.Date_affectation, mat.libelle, mat.Date_Acquisition, mat.Fournisseur,mat.commentaire, mat.Contrat from materiel mat
left join user usr on usr.ID_User = mat.ID_User ";
?>
<div>
<form method="post" action="./consultation.php" id="formClient">
<h4 class="widgettitle" width="10%" >Résultat</h4>
<br/>
<table class="table table-striped" id="example" class="display">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<?php
$reponse3 = mysql_query($sqlTous);
while ($rowMat1 = mysql_fetch_array($reponse3)) { ?>
<tbody class="table table-striped" id="example" class="display">
<tr>
<td><?php echo $rowMat1['SN']; ?></td>
<td><?php echo $rowMat1['NOMENCLATURE']; ?></td>
<td><?php echo $rowMat1['Reference']; ?></td>
<td><?php echo $rowMat1['libelle']; ?> </td>
<td><?php echo $rowMat1['Date_Acquisition']; ?></td>
<td><?php echo $rowMat1['Date_affectation']; ?></td>
</tr>
</tbody>
<?php } ?>
</table>
</form>
<script>
$(document).ready(function() {
$('#example').DataTable();
} );
</script>
In addition, i have included the following js and css files:
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Recherche matériel</title>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.10/css/dataTables.bootstrap.min.css" type="text/css" />
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.10/js/dataTables.bootstrap.min.js"></script>
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="js/jquery-migrate-1.1.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.9.2.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
There are some problems with your code:
tbody element shouldn't have id and class attributes and should be outside of the while loop.
You're including jquery-1.9.1.min.js twice.
<tbody>
<?php
$reponse3 = mysql_query($sqlTous);
while ($rowMat1 = mysql_fetch_array($reponse3)) { ?>
<tr>
<td><?php echo $rowMat1['SN']; ?></td>
<td><?php echo $rowMat1['NOMENCLATURE']; ?></td>
<td><?php echo $rowMat1['Reference']; ?></td>
<td><?php echo $rowMat1['libelle']; ?> </td>
<td><?php echo $rowMat1['Date_Acquisition']; ?></td>
<td><?php echo $rowMat1['Date_affectation']; ?></td>
</tr>
<?php } ?>
</tbody>

Add items to a cart from an array

I'm creating a php driven shopping cart as part of a task.
All products are currently stored in an array (I'm aware they would realistically be stored in a database, however for this task it isn't required)
I would like to know if its possible to add items to a cart from clicking a link, upon clicking proceed, it would take the user to a summary screen, displaying the cost of each item (value displayed from the array) and total cost of all items.
I am also looking to include a promotion code input box, is it possible to calculate and display a discount on button click, E.G "Update"
So far, I only have the products displayed in a table which is ok, the cart section is confusing me at the moment as well as the discount section.
<?php
$Item1 = array('SKU'=>test1, 'name'=>ProductTest1, 'Price'=>10.00);
$Item2 = array('SKU'=>test2, 'name'=>ProductTest2, 'Price'=>11.00);
$Item3 = array('SKU'=>test3, 'name'=>ProductTest3, 'Price'=>12.00);
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Style.css">
</head>
<body>
<div id="container">
<div id="main">
<table>
<tr>
<th>SKU</th>
<th>Name</th>
<th>Price</th>
<th>Action</th>
</tr>
<tr>
<td><?php echo $Item1[SKU]; ?></td>
<td><?php echo $Item1[name]; ?></td>
<td><?php echo '£'. number_format($Item1[Price],2); ?></td>
<td><a href=#>Add To Cart</a></td>
</tr>
<tr>
<td><?php echo $Item2[SKU]; ?></td>
<td><?php echo $Item2[name]; ?></td>
<td><?php echo '£'. number_format($Item2[Price],2); ?></td>
<td><a href=#>Add To Cart</a></td>
</tr>
<tr>
<td><?php echo $Item3[SKU]; ?></td>
<td><?php echo $Item3[name]; ?></td>
<td><?php echo '£'. number_format($Item3[Price],2); ?></td>
<td><a href=#>Add To Cart</a></td>
</tr>
</table>
<input id="Proceed" type="Submit" value="Proceed">
</div>
</div>
</body>
</html>
Your first port of call will be to look into sessions (http://www.w3schools.com/php/php_sessions.asp)
Your Add to Cart link will go through to a different PHP page, so it might be addtocart.php
Each Add to Cart link will pass through the SKU/Product ID, so the link for each will have a unique GET parameter - I.E. addtocart.php?sku=test1 - That way you know which Product you're adding to cart.
I'd read through a couple of tutorials from Google, like http://jameshamilton.eu/content/simple-php-shopping-cart-tutorial?PHPSESSID=99d373741727e3010a32319f1ebed001
If you're still having trouble, breakdown your question into specific points and I'm sure someone will help out.
See Simple PHP Shopping Cart without SQL for creating a shopping cart without a database.
At first this is not good way to use the array like this. Try this:
<?php
$products = array(
array('SKU'=>test1, 'name'=>ProductTest1, 'Price'=>10.00),
array('SKU'=>test2, 'name'=>ProductTest2, 'Price'=>11.00),
array('SKU'=>test3, 'name'=>ProductTest3, 'Price'=>12.00),
);
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Style.css">
</head>
<body>
<div id="container">
<div id="main">
<table>
<tr>
<th>SKU</th>
<th>Name</th>
<th>Price</th>
<th>Action</th>
</tr>
<?php foreach ($products as $key => $product): ?>
<tr>
<td><?php echo $product['SKU']; ?></td>
<td><?php echo $product['name']; ?></td>
<td><?php echo '£'. number_format($product['Price'],2); ?></td>
<td>Add To Cart</td>
</tr>
<?php endif; ?>
</table>
<input id="Proceed" type="Submit" value="Proceed">
</div>
</div>
</body>
</html>
Now how to solve the cart. You have to use something persistent. The session will be easiest:
<?php
session_start();
$products = array(
array('SKU'=>test1, 'name'=>ProductTest1, 'Price'=>10.00),
array('SKU'=>test2, 'name'=>ProductTest2, 'Price'=>11.00),
array('SKU'=>test3, 'name'=>ProductTest3, 'Price'=>12.00),
);
if (isset($_GET['action'] && $_GET['action'] === 'addToCart') {
if (!isset($_SESSION['cart']) $_SESSION['cart'] = array();
$_SESSION['cart'][] = $_GET['product'];
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Style.css">
</head>
<body>
<div id="container">
<div id="main">
<?php if (isset($_SESSION['cart']) && !empty($_SESSION['cart'])): ?>
<ul id="cart">
<?php foreach($_SESSION['cart'] as $product): ?>
<li><?= $products[$product]['name'] ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<table>
<tr>
<th>SKU</th>
<th>Name</th>
<th>Price</th>
<th>Action</th>
</tr>
<?php foreach ($products as $key => $product): ?>
<tr>
<td><?php echo $product['SKU']; ?></td>
<td><?php echo $product['name']; ?></td>
<td><?php echo '£'. number_format($product['Price'],2); ?></td>
<td>Add To Cart</td>
</tr>
<?php endif; ?>
</table>
<input id="Proceed" type="Submit" value="Proceed">
</div>
</div>
</body>
</html>
It should work. Just adapting your code.

Categories