Possible to reduce complexity of fetching and displaying data? - php

What I'm doing with the following code is fetching data from a table via PHP in order to display the data on a website.
$stri = "SELECT a, b, c, d, e, f FROM table";
$stat = $conn->prepare($stri);
if ($stat->execute()) {
while ($resu = $stat->fetch(PDO::FETCH_ASSOC)) {
foreach ($resu as $key=>$value) {
echo $value . "<br>";
}
echo "<br><br>";
}
}
However, it seems redundant to use two loops. Is there not a more efficient way to accomplish the same thing while allowing each item of each row to be handled independently?
I plan to do something like the following with it which is why I need to be able to handle the items independently.
if ($stat->execute()) {
while ($row = $stat->fetch(PDO::FETCH_ASSOC)) {
echo '<div class="row">';
foreach ($row as $key=>$value) {
echo '<div class=' .$key. '>';
if (empty($value)) echo '---<br>';
else echo $value;
echo '</div>';
}
echo '</div>';
}
}

However, it seems redundant to use two loops.
I cannot get what does it mean, but in all it's quite possible to reduce the complexity. For this you need to use PDO in the full force, not as a just a substitution for mysql_query(). A separation of concerns would also help
Get your data first in the form of array
$sql = "SELECT a, b, c, d, e, f FROM table";
$stmt = $conn->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll();
and then display it, somewhere inside the HTML part of the page
<?php foreach ($data as $row): ?>
<div class="row">
<?php foreach ($row as $key=>$value): ?>
<div class="<?=$key?>">
<?php if (!$value): ?>
---<br>
<?php else ?>
<?=$value?>
<?php endif ?>
</div>
<?php endforeach ?>
</div>
<?php endforeach ?>

function checking($val)
{
if(empty($val))
{
echo "---<br>";
}
else
{
echo $val;
}
}
$stri = "SELECT a, b, c, d, e, f FROM t";
try
{
$stat = $conn->prepare($stri);
$stat->execute();
$results = $stat->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $key=>$value)
{
echo implode('',array_map("checking",$value));
echo "<br><br>";
}
}
catch(Exception $e)
{
error_log($e->getMessage());
}
I do a little bit changed of your code. Instead of use if to catch error, I prefer to use try catch method.

Related

DataTables SQL Server UI Output

I have the following PHP code that connects to MS SQL SERVER and shows the data.
Can you show me by a simple example on how to convert the output to DataTables?
<?php
include("conn.php");
$sql = "SELECT * from contact";
$result = sqlsrv_query($conn, $sql);
while($value=sqlsrv_fetch_array($result))
{
echo "$value[ID]", " ... $value[Name]", ", $value[Address]", "<br>";
}
?>
All you need to do is build an HTML table from your array result (this assumes an associative array):
<?php
echo '<table id="MainTable">';
echo '<thead>';
echo '<tr>';
foreach (array_keys($results[0]) as $key) {
echo "<th>$key</th>";
}
echo '</tr>';
echo '</thead>';
echo '<tbody>';
foreach ($result as $row) {
echo '<tr>';
foreach (array_keys($row) as $key) {
echo '<td>$row[$key]</td>';
}
echo '</tr>';
}
echo '</tbody>';
?>
And then activate DataTable on it with javascript either linked in a separate file or in the <head> element:
$(function () {
$('#MainTable').DataTable();
}
See DataTables Documentation

Want to post multiple search results

I tried to make a search function, when your search a tag, its supposed to give you the images with that tag. When i just echo in the php code (line 101), it gives all the links. However, when i try to post it in the html, it only gives one result back.
php code
$postTags = "";
if (isset($_POST['Find'])) {
try {
$pdoConnect = new PDO("mysql:host=localhost;dbname=imdterest", "root", "");
} catch (Exception $exc) {
echo $exc->getMessage();
exit();
}
$postTags = $_POST['naam'];
$pdoQuery = "SELECT * FROM posts WHERE postTags = :tags";
$pdoResult = $pdoConnect->prepare($pdoQuery);
$pdoExec = $pdoResult->execute(array(":tags" => $postTags));
while ($row = $pdoResult->fetch(PDO::FETCH_ASSOC)) {
$postTags = $row['postImageUrl'];
//echo $postTags;
}
}
html code
<div class="search">
<img src="<?php echo $postTags; ?>">
</div>
the problem is that in your php code you have WHILE loop and you echo link for all found rows. That is why it prints all results. But also you don't store the values but overwrite it every while iteration. In your HTML you don't have while loop and you just print overwritten variable (probably last result).
You can either store the results in an array or move while loop to HTML location.
Storing into array:
$allResults = array();
while ($row = $pdoResult->fetch(PDO::FETCH_ASSOC)) {
$allResults[] = $row['postImageUrl'];
}
and then somewhere in your html code
<div class="search">
<?php
foreach ($allResults as $imageLink){
echo '<img src="' . $imageLink . '">";
}
?>
</div>
The variable $postTags is getting overwritten and will hold only last value of MySQL result set. Create an array and loop over it.
$postTags = array();
while ($row = $pdoResult->fetch(PDO::FETCH_ASSOC)) {
$postTags[] = $row['postImageUrl'];
}
In HTML:
foreach($postTags as $val)
{ ?>
<div class="search">
<img src="<?php echo $val; ?>">
</div>
<?php
} ?>
Change your while loop like this, As you are not using array next data will over write the previous and all you are left with one image link that is last image link. hence to prevent overriding use array.
$postTags=[];
while ($row = $pdoResult->fetch(PDO::FETCH_ASSOC)) {
$postTags[] = $row['postImageUrl'];
//echo $postTags;
}
And html code like this , As now you have multiple images you need to display all and for that you need to iterate and foreach is one method to iterate through array.
<?php
foreach ($postTags as $postTag) {
?>
<div class="search">
<img src="<?php echo $postTag; ?>">
</div>
<?php }?>

While loop inside for loop not working while fetching mysql rows

<?php
echo '<table>';
for($i=1;$i<=12;$i++)
{
echo '<tr>';
while($row5=mysql_fetch_array($result5))
{
if($row5[3]=='monthly')
echo '<td>'.$row5[3].'</td>';
else if($row5[3]=='quarterly')
echo '<td rowspan="3">'.$row5[3].'</td>';
else if($row5[3]=='halfyearly')
echo '<td rowspan=""="6">'.$row5[3].'</td>';
else
echo '<td rowspan="12">'.$row5[3].'</td>';
}
echo '</tr>';
}
echo '</table>';
?>
This code is printing only one row instead of 12 rows. Please help me. I am doing this for managing student fees. I am stuck at the logic.
Create an array with sql result before :
$data = array();
while( $row5 = mysql_fetch_array($result5) )
$data[] = $row5;
Then replace this : while($row5=mysql_fetch_array($result5))
foreach ( $data as $row5 ) {
if($row5[3]=='monthly')
echo '<td>'.$row5[3].'</td>';
// ...
}
PS : Use mysqli_* instead of mysql_* which is deprecated

PHP Execute array multple times on the one page

I want to run two seperate foreach loops on the one page, but only write my SQL once. For example see the below code, only the ul with the id of first runs, the second ul is empty.
<?php
$mylist = 'SELECT * FROM myTable';
$showlist = $pdo->prepare($mylist);
$showlist->execute();
?>
<ul id="first">
<?php foreach ($showlist as $rowid):;?>
<li><?php echo $rowid['id'] ?></li>
<?php endforeach; ?>
</ul>
<ul id="second">
<?php foreach ($showlist as $rowname):;?>
<li><?php echo $rowname['name'] ?></li>
<?php endforeach; ?>
</ul>
I thought renaming the as would allow me to use it again but this doesn't seem to be the case? What is the best approach here?
try:
<?php
$mylist = 'SELECT * FROM myTable';
$showlist = $pdo->prepare($mylist);
$showlist->execute();
$result = $showlist->fetchAll();
foreach ($result as $rowid) {
// do stuff
}
foreach ($result as $rowname) {
// do stuff
}
You'd need to stack your elements in an extra array first:
$mylist = 'SELECT * FROM myTable';
$showlist = $pdo->prepare($mylist);
$showlist->execute();
$rows = array();
foreach($showlist as $row) {
array_push($rows, $row);
}
echo "<ul>";
foreach($rows as $row) {
echo "<li>".$row['id']."</li>";
}
echo "</ul><ul>";
foreach($rows as $row) {
echo "<li>".$row['name']."</li>";
}
echo "</ul>";

foreach data while inside?

Good afternoon, everybody. I have a doubt.
I have a WHILE, and accurate list of the data within it FOREACH . Does anyone know how to do this?
I would be very grateful for the help.
Example code.
$UserIDS= array();
$query->execute();
while ($lista = $query->fetch()){
$mensagem = $lista['mensagem'];
$UserIDS[] = $lista['idUser'];
echo
'
//Data from Forech, was shown here.
<div class="avatar"></div>
<div class="text">
'.utf8_encode($mensagem).'
</div>
';
}
//FOREACH data has to list before the $message, if put into the forech WHILE not sure of the fact that I have an array inside.
foreach ($UserIDS as $idUsua) {
echo "<div class='avatar'>".box::avatar($idUsua)."</div>";
}
Anyone know how do I pull data from FOREACH and put inside the in WHILE? be very grateful for the help.
Referring to my earlier answer to your other question:
// fetch all the data in one go
$query->execute();
$data = $query->fetchAll();
// and then iterate it
foreach ($data as $lista) {
echo "<div id='avatar'>" . box::avatar($lista['idUser']) . "</div>";
echo "<div class='text'>" . utf8_encode($lista['mensagem']). "</div>";
}
Your existing box::avatar call is then still free (as before) to make separate PDO query calls.
why don't you take this part
foreach ($UserIDS as $idUsua) {
echo "<div class='avatar'>".box::avatar($idUsua)."</div>";
}
into a function like
function userId($UserIDS){
$userAvatarDivs="";
foreach ($UserIDS as $idUsua) {
$userAvatarDivs.= "<div class='avatar'>".box::avatar($idUsua)."</div>";
}
return $userAvatarDivs;
}
and call it on
while ($lista = $query->fetch()){
$mensagem = $lista['mensagem'];
$UserIDS[] = $lista['idUser'];
echo
'
//Data from Forech, was shown here.
<div class="avatar"></div>
<div class="text">
'.utf8_encode($mensagem).'
</div>
'.userId($UserIDS);
}

Categories