get first object from result array php - php

I have view file on my app there is code array I want to get first object of that array without going in loop.
<?php
$result = array_chunk($products->result_array(), 3);
foreach($result as $products){ ?>
<table style="width:100% style="page-break-after:always;" >
<tr>
<?php
foreach($products as $productArray){
$product = (object) $productArray;
echo '<td>';
?>
<div style="width: 100%; height: 210px; border: 1px solid #dddddd; margin: auto 5px 5px 0; padding: 5px;">
<div class="box-header">
<p class="box-title"><FONT SIZE=12><?php echo $product->product_name; ?></FONT></p>
</div>
<div style="height: 100px; text-align: center;">
<?php echo '<img src="'.'uploads/'. $product->photo.'" class="img-responsive" style="height:100px !important; width: 150px !important" />'; ?>
</div>
<div style="clear: both"></div>
<table class="table table-responsive">
<tr>
<th><FONT SIZE=12>ID</FONT></th>
<td><FONT SIZE=14><?php echo $product->product_id; ?></FONT></td>
</tr>
$result is array of object I'm getting from a form. In below you can clearly see I'm chunking it to 3 more array and looping though individual objects and getting their details to html for example.
<tr>
<th><FONT SIZE=12>ID</FONT></th>
<td><FONT SIZE=14><?php echo $product->product_id; ?></FONT></td>
</tr>
I want to get the first object details let's say want get $product->product_name of first object of result array without going in loop how to achieve that.
here is complete view file code.
<!DOCTYPE html>
<html class="bg-black">
<head>
<meta charset="UTF-8">
<title><?php if(isset($title)) echo $title.' | '; ?> Sales agent management software (SAMS) </title>
<style>
body{
font-size: 9px;
margin: 20px;
}
th,td,p,div,table,h3{margin:0;padding:0}
#page { margin: 20px; }
.header{
border-bottom: 0px solid #dddddd;
text-align: center;
position: fixed; top: 0;
}
.footer { position: fixed; bottom: 0px; text-align: center }
.pagenum:before { content: counter(page); }
</style>
</head>
<body>
<?php
$usd = get_option('lkr_per_usd', 134);
?>
<div class="footer">
Page: <span class="pagenum"></span>, creation time : <?php echo date('l jS \of F Y h:i:s A') ?>, create by: <?php echo user_full_name(singleDbTableRow(loggedInUserData()['user_id'])); ?>, $ Rate : Rs. <?php echo $usd; ?> </div>
<br />
<div class="box-body">
<?php
$usd = get_option('lkr_per_usd', 134);
?>
<?php
$result = array_chunk($products->result_array(), 3);
foreach($result as $products){ ?>
<table style="width:100% style="page-break-after:always;" >
<tr>
<?php
foreach($products as $productArray){
$product = (object) $productArray;
echo '<td>';
?>
<div style="width: 100%; height: 210px; border: 1px solid #dddddd; margin: auto 5px 5px 0; padding: 5px;">
<div class="box-header">
<p class="box-title"><FONT SIZE=12><?php echo $product->product_name; ?></FONT></p>
</div>
<div style="height: 100px; text-align: center;">
<?php echo '<img src="'.'uploads/'. $product->photo.'" class="img-responsive" style="height:100px !important; width: 150px !important" />'; ?>
</div>
<div style="clear: both"></div>
<table class="table table-responsive">
<tr>
<th><FONT SIZE=12>ID</FONT></th>
<td><FONT SIZE=14><?php echo $product->product_id; ?></FONT></td>
</tr>
<tr>
<th><FONT SIZE=12>LKR</FONT></th>
<td><FONT SIZE=14><?php $lkr = get_selling_price($product);
echo number_format(round($lkr, get_option('round_precision')) ); ?></FONT>
</td>
</tr>
<tr>
<th> <FONT SIZE=12>US $</FONT></th>
<td><FONT SIZE=14><?php echo number_format(round(lkr_to_usd($lkr), get_option('round_precision')) ); ?></FONT></td>
</tr>
</table>
<?php $GLOBALS['a']= $product->product_id; ?>
</div>
</td>
<?php } ?>
</tr>
<?php } ?>
</table>
</div><!-- /.box-body -->
</body>
</body>
</html>

ok man as i said u need to change your way of writing codes but about your specific question use this:
$result = array('a', 'b', 'c', 'd', 'e');
reset($array);
$first = current($array);
you can check this:
http://php.net/manual/en/function.reset.php
http://php.net/manual/en/function.current.php
But still about your way of coding. u should soon go to MVC or such ways of programming so u should separate your view and coding logics
like u may have a page like view_profile.php which is going to show user's information. in regular coding u have this:
view_profile.php:
<?php session_start();
// you check sessions to see if the user is logged in and has the right to view this page.
// like:
if ($_SESSIONS['is_user_logged_in']){
$username=$_SESSIONS['username'];
$name=$_SESSIONS['name'];
// ....
}else{
header('location: ./login.php');// if user is not authenticated u redirect to login page
exit();// prevents the rest of codes to be shown and executed
}
?>
<html>
<head>
<title>View <?php echo $name; ?>'s profile</title>
</head>
<body>
<div>Name: <span><?echo $name; ?></span></div>
......
</body>
</html>
But in a better way u can do it like this:
you have files like
'view_profile.htm' // holds the HTML
'view_profile.php // holds the PHP logic
'inc.php' // holds some useful functions that help you in writing PHP logic
view_profile.htm
<html>
<head>
<title>View <?php echo $name; ?>'s profile</title>
</head>
<body>
<div>Name: <span><?echo $name; ?></span></div>
......
</body>
</html>
inc.php
<?php
function ses_start(){
if(!session_id()){
session_start();
}
}
function ses_get($key){
ses_start();
if(!empty($_SESSION[$key])){
return $_SESSION[$key];
}
return NULL;
}
function ses_set($key,$val){
$_SESSION[$key]=$val;
}
function is_user_loggedin(){
ses_start();
if(!empty(ses_get('is_user_loggedin')){
return true;
}
return false;
}
function go($to){
header('location: '.$to);
exit();
}
//and lots of useful functions that help u connect and work with data base.
view_profile.php
<?php
include('inc.php');
if(is_user_loggedin(){
$username=ses_get('username');
$name=ses_get('name');
//...
}else{
go('login.php);
}
include('view_profile.html); // and u call the .htm file that holds the HTML the view file)
?>
this was a simple sample of separating codes logic(php codes) from views(html tags)
and also u may search about MVC Model-View-Controller and try working with simple MVC frameworks.

Related

Spread data in 3 columns

I need your help with this small issue as my developing level is not the best In the room ( faraway :-) )
I would like to spread the results of my SQL request in 3 columns.
After the first 37 entries, I would like the entries 38 to 74 are filling the column #2, and column #3 over 74...
I hope it is clear.
please find below the code of my page:
<title>TITLE</title>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght#700;800;900&display=swap" rel="stylesheet">
<style>
body {background-color: #000000;}
table {
background-color: #000000;
border-collapse: collapse;
width: 100%;
}
table, .table {
color: #fff;
font-family: "Montserrat", sans-serif;
font-size: 18px;
font-weight:800;
font-weight:Extra-bold;
}
tr:nth-child(even) {
background-color: #60451e;
}
</style>
<div class="container">
<div class="row">
<?php
include_once("inc/db_connect.php");
$sqlQuery = "SELECT name, GROUP_CONCAT(id ORDER BY id SEPARATOR ' | ') as grouped_id FROM developers GROUP BY name";
$resultSet = mysqli_query($conn, $sqlQuery) or die("database error:". mysqli_error($conn));
?>
<table id="editableTable" class="table table-bordered">
<tbody>
<?php while( $developer = mysqli_fetch_assoc($resultSet) ) { ?>
<tr id="<?php echo $developer ['id']; ?>">
<td><?php echo $developer ['name']; ?><br>  <span style="color: #ffc000">BOXES > <?php echo $developer ['grouped_id']; ?></span></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
and I would like to keep a formatting similar to this for each entry:
echo $developer ['name']; ?><br>  <span style="color: #ffc000">BOXES > <?php echo $developer ['grouped_id']; ?></span>
Thank you in advance

How to list the records in horizontal order using modulus (%) operation?

I have problem in my task where I suppose to display my record in horizontally with 3 columns
Unfortunately, my display is become vertical.
The task require us to use modulus (%) operator in order to display the records. The records are stored in database (id, title, picture, category, author). There are 11 books that store in database. Here is my PHP code:
<?php
include_once('config.php');
$result = mysqli_query($mysqli, "SELECT * FROM books ORDER BY id ASC");
?>
<style>
img {
border: 1px solid #ddd;
border-radius: 4px;
padding: 5px;
width: 200px;
}
.p2 {
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
padding-left: 10px;
}
.p3 {
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
padding-left: 10px;
color: blue;
}
</style>
<div class="container">
<center>
<h1>Koleksi Buku Peribadi</h1>
<table>
<?php
$x=11;
$y=3;
$i=$x % $y;
while($i && $book = mysqli_fetch_array($result)) {
?>
<tr>
<td>
<img src="Gambar-buku/<?php echo $book['picture'];?>">
<p class='p2'>Penulis:<span class='p3'> <?php echo $book['author'];?> </span>
<br> <i><?php echo $book['category'];?></i>
</p>
<center><button type="button">Details</button> </center>
</td>
</tr>
<?php
$i++; }
?>
</table>
</center>
</div>
Modulus is useful when you need to equally divide items into several categories.
Formally: index_of_category = index_of_item % number_of_categories
Practically: In your case, you have 3 categories (columns). For item with index i, you find index of its column with i % 3.
For making table layout work, you then need to:
print tr opening tag for every item belonging in column with index 0
print tr closing tag for every item belonging in column with index 2.
In my example, you can change number of columns easily by modifying $numberOfColumns variable.
<div class="container">
<center>
<h1>Koleksi Buku Peribadi</h1>
<table>
<?php
$numberOfColumns = 3;
for ($i = 0; (($book = mysqli_fetch_array($result)) !== null); $i++) {
$printRowOpeningTag = $i % $numberOfColumns === 0;
$printRowClosingTag = $i % $numberOfColumns === $numberOfColumns - 1;
if ($printRowOpeningTag) {?>
<tr>
<?php } ?>
<td><img src="Gambar-buku/<?php echo $book['picture'];?>">
<p class='p2'>Penulis:<span class='p3'> <?php echo $book['author'];?> </span>
<br> <i><?php echo $book['category'];?> </i>
</p>
<center><button type="button">Details</button> </center>
</td>
<?php if ($printRowClosingTag) { ?>
</tr>
<?php } ?>
<?php
} ?>
</table>
</center>
</div>

Database information not lining up in a table (php/sql)

When using CSS for my DetailsTable the information I am getting from the database is not being displayed correctly in the table. All of that information is getting bunched up together and therefore isn't being laid out as a table.
If anyone could suggest why the information I am trying to get isn't being laid out in a table form that would be much appreciated
</head>
<body>
<div id="DetailsTable" >
<table>
<tr>
<th>Name</th>
<th>TypeOfShoe</th>
<th>Description</th>
<th>Price(£)</th>
<th>Fabric</th>
<th>Colour</th>
<th>Brand</th>
</tr>
</table>
<?php
$shoesID=$_GET['id'];
$stmt = $conn->prepare("SELECT shoes.name, shoes.images, shoes.description, shoes.price, types.typeOfShoe, types.fabric, types.colour, brands.name AS bname FROM shoes INNER JOIN types on types.types_id = shoes.type_id INNER JOIN brands on brands.brands_id = shoes.brands_id
WHERE shoes.id = :id");
$stmt->bindValue(':id',$shoesID);
$stmt->execute();
if ($shoes=$stmt->fetch()){
echo "<td>".$shoes['name']."</td>";
echo "<td>".$shoes['typeOfShoe']."</td>";
echo "<td>".$shoes['description']."</td>";
echo "<td>".$shoes['price']."</td>";
echo "<td>".$shoes['fabric']."</td>";
echo "<td>".$shoes['colour']."</td>";
echo "<td>".$shoes['bname']."</td>";
}
$conn=NULL;
?>
<br> <br/>
<div id="Image" >
<img src="<?php echo $shoes['images']; ?>" height="500px" width="500px" />
</div>
</div>
The CSS code is below.
body {
background-color: lemonchiffon;
}
#DetailsTable {
border-collapse: collapse;
width: 100%;
}
th, td {
text-align: left;
padding: 8px;
}
#Image{
display: block;
margin: auto;
width: 50%;
height: 10px;
clear: both;
}
You have closed the</table> tag before the php code, that maybe the problem
</head>
<body>
<div id="DetailsTable" >
<table>
<tr>
<th>Name</th>
<th>TypeOfShoe</th>
<th>Description</th>
<th>Price(£)</th>
<th>Fabric</th>
<th>Colour</th>
<th>Brand</th>
</tr>
<?php
$shoesID=$_GET['id'];
$stmt = $conn->prepare("SELECT shoes.name, shoes.images, shoes.description, shoes.price, types.typeOfShoe, types.fabric, types.colour, brands.name AS bname FROM shoes INNER JOIN types on types.types_id = shoes.type_id INNER JOIN brands on brands.brands_id = shoes.brands_id
WHERE shoes.id = :id");
$stmt->bindValue(':id',$shoesID);
$stmt->execute();
if ($shoes=$stmt->fetch()){
echo '<tr>';
echo "<td>".$shoes['name']."</td>";
echo "<td>".$shoes['typeOfShoe']."</td>";
echo "<td>".$shoes['description']."</td>";
echo "<td>".$shoes['price']."</td>";
echo "<td>".$shoes['fabric']."</td>";
echo "<td>".$shoes['colour']."</td>";
echo "<td>".$shoes['bname']."</td>";
echo '</tr>';
}
$conn=NULL;
?>
</html>
<br> <br/>
<div id="Image" >
<img src="<?php echo $shoes['images']; ?>" height="500px" width="500px" />
</div>
</div>

Dompdf is not printing the table with posted php form

When I try to print the table in the file_html.php it prints the static table with some error(that's a different question). However, when the php tags for the posted data are included in the file with the post variables, the pdf generated displays nothing at all except for the anchor tag which is at the bottom of the page.
Here is the index.php :-
require_once("dompdf/dompdf_config.inc.php");
require_once("dompdf/dompdf_config.custom.inc.php");
spl_autoload_register('DOMPDF_autoload');
function pdf_create($html, $filename, $paper, $orientation, $stream=TRUE)
{
$dompdf = new DOMPDF();
$dompdf->set_paper($paper,$orientation);
$dompdf->load_html_file('http://localhost/pdf/file_html.php');
$dompdf->render();
$dompdf->stream($filename.".pdf");
}
$filename = 'billofsale';
$dompdf = new DOMPDF();
$html = file_get_contents('http://localhost/pdf/file_html.php');
pdf_create($html,$filename,'A4','portrait');
And here is the file_html.php which consists the form with the post variable. Note : when the php with the post is removed the table prints out in the pdf.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
table, caption, tbody, tfoot, thead, tr, th, td {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
}
table {
border-collapse: collapse;
border-spacing: 0;
width:100%;
}
body{
font: normal medium/1.4 sans-serif;
}
th{
text-align: center;
border: 3px solid #ccd;
}
td{
padding: 0.25rem;
text-align: left;
border: 2px solid #ccc;
}
tbody tr:nth-child(odd){
background: #eee;
}
tbody:before, thead:after { display: none; }
</style>
</head>
<body>
<?php
if(isset($_POST['submit'])){
?>
<p>
<table>
<thead><th colspan="2">Purchaser's Information</th></thead>
<tbody>
<tr>
<td colspan="2">Purchaser's Name : <?php echo $_POST['pname']; ?></td>
</tr>
<tr>
<td colspan="2">Purchaser's Address : <?php echo $_POST['padd']; ?></td>
</tr>
<tr>
<td>City/Town : <?php echo $_POST['pcity']; ?> </td>
<td>Province : <?php echo $_POST['ppro']; ?></td>
</tr>
<tr>
<td>Postal Code :<?php echo $_POST['ppcode']; ?></td>
<td>Home Tel No :<?php echo $_POST['ptelno']; ?></td>
</tr>
<tr>
<td>Business Tel :<?php echo $_POST['pbtel']; ?></td>
<td>Email :<?php echo $_POST['pemail']; ?></td>
</tr>
<tr>
<td>Driver License : <?php echo $_POST['pdriverlic']; ?></td>
<td>Expiry Date :<?php echo $_POST['pdriverexp']; ?></td>
</tr>
</tbody>
</table>
</p>
<?php
}
?>
Print
</body>
</html>
You're loading file_html.php using $dompdf->load_html_file('http://localhost/pdf/file_html.php');. This method is like starting a new browser request using the GET method. Any variables set during the current PHP process are not passed through. This means the $_POST array is empty.
There are a few ways of addressing the issue, but since your table relies on data from the $_POST array I'd suggest using output buffering. You can render the content within index.php, capture the output, and feed it to dompdf.
Using your original sample as a starting point ...
<?php
ob_start();
require 'file_html.php'
$html = ob_get_contents();
ob_end_clean();
require_once('dompdf/dompdf_config.inc.php');
$dompdf = new DOMPDF();
$dompdf->set_paper('a4','portrait');
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream('billofsale.pdf');
?>
Now when you POST to index.php the $_POST array will be available to file_html.php.

PHP code being commented out

I'm using CentOS 6.4 with apache installed. I have a single php file called cmsSearch.php. At the top of the file I have PHP that executes fine (queries a Sphinx Search index). But, any php I try to run in the HTML that is below (trying to run a foreach and populate a table with the results of the Sphinx Search) just gets commented out when I view the page in the console (Chrome). Here is the whole cmsSearch.php file:
<?php
require("sphinxapi.php");
if($_POST['keyword'])
{
$keyword = $_POST['keyword'];
$client = new SphinxClient();
$client->SetMatchMode(SPH_MATCH_ANY);
$result = $client->Query($keyword, "staffDirectoryMember");
if(!$result)
{
print "ERROR: " . $client->GetLastError();
}
else
{
var_dump($result["matches"]);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Sphinx Test</title>
<style>
.container
{
border: solid 1px black;
height: 350px;
width: 700px;
margin: auto;
padding: 5px;
}
.output
{
margin-top:20px;
border: solid 1px red;
height: 200px;
}
</style>
</head>
<body>
<?echo "TEST"; ?>
<div class="container">
<div>
<form method="post" action="cmsSearch.php">
<input type="text" name="keyword">
<input type="submit" value="Search">
</form>
<div class="output">
<? echo "test2"; ?>
<table>
<thead>
<tr>
<th>ID</th>
<th>Weight</th>
<th>ClientId</th>
<th>DomainId</th>
<th>ContentTypeId</th>
</tr>
</thead>
<tbody>
<?
echo "Above for loop";
foreach($result["matches"] as $match)
{
echo "Print from for loop:";
var_dump($match);
?>
<!-- <tr>
<td><?=$match[id]?></td>
<td><?=$match[weight]?></td>
<td><?=$match[attrs][clientid]?></td>
<td><?=$match[attrs][domainid]?></td>
<td><?=$match[attrs][contenttypeid]?></td>
</tr> -->
<?}
echo "After for loop";
?>
</tbody>
</table>
</div>
</div>
</div>
Not sure why the php executes at the top fine (i can echo out and the var dump works), but then any php put in the HTML just shows as comments and doesn't do anything. Anyone have an idea?
Your PHP contained inside the HTML is using short tags which can be turned off in your php.ini file. Take a look at this directive and make sure it is set to true if you want to use them:
short_open_tag true
http://www.php.net/manual/en/ini.core.php#ini.short-open-tag
Try using <?php to start your PHP blocks, not <?... It's the difference between the blocks of code.

Categories