php/mysql array or query with some values - php

Hello I have this query
$upit = "SELECT id from usluga";
$rezultat = mysql_query($upit);
while($red = mysql_fetch_object($rezultat))
{
echo "<li>{$red->id}</li>";
}
I want on exit to get this:
<li>1,2,3,4,5,6</li>
<li>7,8,9,10,11,12</li>
<li>13,14,15,16,17,18</li>
<li>19,20,21,22,23,24</li>
and so on..
Any help?

You can use the mod operator(%) or use array functions to achive this
$upit = "SELECT id from usluga";
$rezultat = mysql_query($upit);
while ($red=mysql_fetch_object ($rezultat)) {
$t[] = $red->id;
}
$chunks = array_chunk($t, 6);
foreach ($chunks as $chunk) {
echo "<li>" . join(",", $chunk) . "</li>";
}

try this..
$upit="SELECT id from usluga";
$rezultat=mysql_query($upit);
$i=0;
$liflag=0;
while ($red=mysql_fetch_assoc($rezultat))
{
if($i<6)
{
$liflag=1;
if($i==0)
{
echo "<li>$red->id";
$i++;
continue;
}
else
{
echo ",$red->id";
$i++;
continue;
}
}
else
{
echo ",$red->id</li>";
$i=0;
$liflag=0;
continue;
}
}
if($liflag==1)
{
echo "</li>";
}

Related

I'm trying to convert an array to XML but I am failing to get it 100% correct

I need to output the response from the database in XML. So far I have gotten it to output this:
The outermost tag needs to match the name of the action query, it'll either be <courses> or <students>.
Here is my code:
<?php
require_once('./database.php');
if (isset($_GET['format'])) {
$format = filter_var($_GET['format']);
}
if (isset($_GET['action'])) {
$action = filter_var($_GET['action'], FILTER_SANITIZE_STRING);
$tableName = "sk_$action";
}
$query = "SELECT * FROM $tableName";
if (isset($_GET['course'])) {
$course = filter_input(INPUT_GET, 'course');
$query .= " WHERE courseID = :course";
}
function arrayToXml($arr, $i = 1, $flag = false)
{
$sp = "";
for ($j = 0; $j <= $i; $j++) {
$sp .= " ";
}
foreach ($arr as $key => $val) {
echo "$sp<" . $key . ">";
if ($i == 1) echo "\n";
if (is_array($val)) {
if (!$flag) {
echo "\n";
}
arrayToXml($val, $i + 5);
echo "$sp</" . $key . ">\n";
} else {
echo "$val" . "</" . $key . ">\n";
}
}
}
$statement = $db->prepare($query);
$statement->bindValue(':course', $course);
$statement->execute();
$response = $statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
if ($format == 'json') {
echo json_encode($response);
}
if ($format == 'xml') {
arrayToXml($response, 1, true);
}
I'm pretty new to PHP and have never worked with XML. All help is appreciated. Thanks.
function arrayToXml($arr, $collectionTag, $singleTag) {
$collection = new SimpleXMLElement("<$collectionTag/>");
foreach ($arr as $row) {
$element = $root->addChild($singleTag);
foreach ($row as $tag => $value) {
$element->addChild($tag, $value);
}
}
return $collection;
}
$courses = arrayToXml($response, 'courses', 'course');
echo $courses->asXML();
Tested with PHP 7.1.23. Output:
<?xml version="1.0"?>
<courses>
<course><courseID>cs601</courseID><courseName>Web Application Development</courseName></course>
<course><courseId>cs602</courseId><courseName>Server-Side Application Development</courseName></course>
<course><courseId>cs701</courseId><courseName>Rich Internet Application Development</courseName></course>
</courses>
(I added newlines because by default it doesn't add any.)

PHP mysql display query in 4 columns

How to display this query result in 4 columns
<?php
$direction = $_POST['direction'];
$sumword = $_POST['sumword'];
$length = $_POST['length'];
$con = mysql_connect("localhost","elsha","12q(5PSZ.");
$db = mysql_select_db("elsha",$con);
$query = "SELECT answer FROM words WHERE direction = '$direction' AND sumword = '$sumword' AND sumletter = '$length'";
$result = mysql_query($query);
if(mysql_error()) {
//check that no error has occurred first; take this out in production or make more graceful handling
die(mysql_error());
}
if(mysql_num_rows($result) == 0) {
echo "No Results";
} else {
while($row = mysql_fetch_array($result)) {
echo '<img src="/images/'. $row['0'].'.jpg"><br> '. $row['0'].'<br>';
}
}
?>
like this :
result1 result2 result3 result4
result5 result6 result7 result8
Try this
$i = 0;
while($row = mysql_fetch_array($result)) {
echo '<img src="/images/'. $row['0'].'.jpg"> ';
$i++;
if($i % 4 == 1 && $i!=1){
echo '<br>';
}
}
Use flag like
$flag=0;
while($row = mysql_fetch_array($result)) {
if(($flag%4)==0) {
echo '<tr>';
}
echo '<td><img src="/images/'. $row['0'].'.jpg"><br> '. $row['0'].'</td>';
if(($flag%4)==3) {
echo '</tr>';
$flag=-1;
}
$flag++;
}
replace your while with the following code. try this
$a=1;
while($row = mysql_fetch_array($result)) {
if($a%4==0) {
echo '<img src="/images/'. $row['0'].'.jpg">'. $row['0'].'<br>';
} //4th line with break
else {
echo '<img src="/images/'. $row['0'].'.jpg"> '. $row['0'].' '; // prints first 3 lines
}
$a=$a+1;
}
I think you are trying to display the image name too below the image. Try this:
$i = 1;
while($row = mysql_fetch_array($result)) {
echo '<div class="imgs">';
echo '<img src="/images/'. $row['0'].'.jpg"><br> '. $row['0'];
echo '</div>';
if ($i === 4) {
echo '<div class="clear"></div>';
$i = 1;
} else {
$i++;
}
}
and then style div's
.imgs {
float: left;
/* other styles */
}
.clear {
clear: both;
}

Group MySQL results into blocks of A-Z in PHP

I have a list of thousands of results and I want to group them alphanumerically for example, I need it to be like this:
<h1>0-9</h1>
<ul>
<li>011example</li>
<li>233example</li>
<li>65example</li>
</ul>
<h1>A</h1>
<ul>
<li>albert</li>
<li>alfred</li>
<li>annie</li>
</ul>
<h1>B</h1>
<ul>
<li>ben</li>
<li>bertie</li>
<li>burt</li>
</ul>
But I can't work out how to split or group my results into 0-9 and A-Z.
Currently I have:
<?php
$get_az = mysql_query("SELECT custom_22 FROM db_table1");
echo '<ul>';
while ($row = mysql_fetch_assoc($get_az)) {
$getfirstletter = substr($row['custom_22'], 0,1);
$name = $row['custom_22'];
echo '<h1>'.$getfirstletter.'</h1>';
echo '<li>'.$name.'</li>';
}
echo '</ul>';
?>
Order by the name and handle each letter one by one.
$get_az = mysql_query("SELECT custom_22 FROM db_table1 ORDER BY custom_22 ASC");
$current_first_letter = null;
while ($row = mysql_fetch_assoc($get_az)) {
$first_letter = strtolower(substr($row['custom_22'], 0, 1));
if (preg_match("/[0-9]/", $first_letter)) { // detect digits
$first_letter = "0-9";
}
if ($first_letter !== $current_first_letter) {
if ($current_first_letter !== null) {
echo '</ul>';
}
echo '<h1>' . $first_letter . '</h1>';
echo '<ul>';
}
$current_first_letter = $first_letter;
echo '<li>' . htmlentities($row['custom_22']) . '</li>';
}
if ($current_first_letter !== null) {
echo '</ul>';
}
I would do it this readable way:
$get_az = mysql_query('SELECT custom_22 FROM db_table1 ORDER BY custom_22');
$groups = array();
split results to groups
while ($row = mysql_fetch_assoc($get_az)) {
$firstLetter = strtolower(substr($row['custom_22'], 0, 1));
check for digits
if (is_numeric($firstLetter)) {
$firstLetter = '0-9';
}
if (isset($groups[$firstLetter]) === false) {
$groups[$firstLetter] = array();
}
$groups[$firstLetter][] = $row['custom_22'];
}
simply iterate over groups and echoes it
foreach ($groups as $h1 => $items) {
echo sprintf('<h1>%s</h1>', strtoupper(htmlspecialchars($h1)));
echo '<ul>';
foreach ($items as $item) {
echo sprintf('<li>%s</li>', htmlspecialchars($item));
}
echo '</ul>';
}

How can I check the value of the Next Row while looping using PHP/MYSQL?

I got previousRow of record using this code
<?php
$previousRow = array();
while ($temp = mysql_fetch_row($res2))
{
echo "<br>currentRow:".$temp[1];
echo "previousRow:".$previousRow[1];
$previousRow = $temp;
}
?>
oupout
currentRow:1previousRow:
currentRow:5previousRow:1
currentRow:6previousRow:5
currentRow:7previousRow:6
currentRow:8previousRow:7
How can I check the value of the next row replaced by Previous Row ?
Any help would be grateful.
If I get you correctly, then something like this would help?
$previousRow = array();
$currentRow = mysql_fetch_row($res2);
while ($currentRow) {
$nextRow = mysql_fetch_row($res2);
echo "<br>currentRow:".$currentRow[1];
echo "previousRow:".$previousRow[1];
echo "nextRow:".$nextRow[1];
$previousRow = $currentRow;
$currentRow = $nextRow;
}
Please try code given below.
$res = array();
while ($result = mysql_fetch_row($r)) {
$res[] = $result;
}
echo "<pre>";
foreach($res AS $index=>$res1){
echo "Current".$res1[1];
echo " Next" . $res[$index+1][1];
echo " Prev" . $res[$index-1][1]; echo "<br>";
}
thanks
I'd collect all the rows first, then walk through them with a for:
<?php
$rows = array();
while ($temp = mysql_fetch_row($res2))
{
$rows[] = $temp;
}
$rowCount = count($rows);
for ($i = 0; $i < $rowCount; $i++) {
echo "<br>currentRow:".$rows[$i][1];
if ($i > 0) {
echo "previousRow:".$rows[$i - 1][1];
}
if ($i + 1 < $rowCount - 1) {
echo "nextRow:".$rows[$i + 1][1];
}
}
?>

php mysql_fetch_array every 25 items wrap a div

I want to mysql_fetch_array 100 items from mysql database. then every 25 items wrap a div.
also, I make a total items result check.
My code as below, but it will add <div> to every item, no as my require. So how to make it easier? Thanks.
if (mysql_num_rows($result) != 0) {
$total = mysql_num_rows($result);
$num = 1;
while ($row = mysql_fetch_array($result)) {
if ($num === 1) {
echo '<div>';
}
echo $row['title'] . '<br />';
if ($total < 26) {
echo '</div>';
}
else {
if ($num === 26) {
echo '<div>';
}
if ($total < 51) {
echo '</div>';
}
else {
if ($num === 51) {
echo '<div>';
}
if ($total < 76) {
echo '</div>';
}
else {
if ($num === 75) {
echo '<div>';
}
if ($total < 101) {
echo '</div>';
}
}
}
}
$num++;
}
}
You can use the mod operator.
See: http://php.net/manual/en/internals2.opcodes.mod.php
echo '<div>';
while($row = mysql_fetch_array($result)){
....
if (($num % 25) === 1) { echo '</div><div>' }
$num++;
}
echo '</div>';
Try This...
if(mysql_num_rows($result)!=0){
$total = mysql_num_rows($result);
$num=1;
while($row = mysql_fetch_array($result)){
if($num===1)
echo '<div>';
echo $row['title'].'<br />';
if($num==25){
echo '</div>';
$num=1;
}
$num++;
}
}
use the mod operator.
$num =1;
while($row = mysql_fetch_array($result)){
if (($num % 25) === 1) { echo '<div>' }
-------here data ----
if (($num % 25) === 0) { echo '</div>' }
$num++;
}
My advice is to separate your concerns... Give it a shot more like this:
// first get all your data.
$results = array();
while($row = mysql_fetch_array($result)){
$results[] = $row;
}
// now you have an array of all of your records.
if (!empty($results)) {
// total count of the array up front.
$total = count($results);
$interval = 0;
// save the data in a buffer for echoing later.
$buffer = array('<div>');
foreach($results as $row) {
$buffer[] = $row['title'] . '<br />';
if (++$interval === 24) { // notice the prefix ++
$interval = 0;
// close and re-open divs
$buffer[] = '</div><div>';
}
}
// one final close tag
$buffer[] = '</div>';
// now we zip it up and echo the content.
echo implode('', $buffer);
}
Here is how I do it...
$count = 0;
while($row = mysql_fetch_array($result)){
if ($count%$25 == 0)
{
echo "<div>";
}
//whatever your data goes here
count++
if ($count%$25 == 0)
{
echo "</div>";
}
}

Categories