MYSQL in while array, print first result different from the others - php

I need the following, this is my function:
function i_iframe( $cadena ) {
$x = #mysql_query("SELECT * FROM videos WHERE id_peli = '$cadena' LIMIT 3");
while ( $i = mysql_fetch_array( $x ) ) {
$option = adios( $i['idioma'] );
echo "<li>".$option."</li>";
}
#mysql_free_result( $x );
}
this code outputs:
<li>option name 1</li>
<li>option name 2</li>
<li>option name 3</li>
I need the outputs should be like this:
<li class="selected">option name 1</li>
<li>option name 2</li>
<li>option name 3</li>
the first result from thee loop should print <li class="selected"> and rest should be <li>

function i_iframe($cadena) {
$x=#mysql_query("SELECT * FROM videos WHERE id_peli = '$cadena' LIMIT 3");
bool $first = true;
while($i=mysql_fetch_array($x)) {
$option = adios($i['idioma']);
if($first)
{
echo "<li class=\"selected\">".$option."</li>";
$first = false;
} else {
echo "<li>".$option."</li>";
}
}
#mysql_free_result($x);
}
Shoud do the trick

Call mysql_fetch_array once for your first element:
function i_iframe($cadena){
$x=#mysql_query("SELECT * FROM videos WHERE id_peli = '$cadena' LIMIT 3");
if($i=mysql_fetch_array($x)){
$option = adios($i['idioma']);
echo '<li class="selected">', $option, '</li>';
while($i=mysql_fetch_array($x)){
$option = adios($i['idioma']);
echo "<li>".$option."</li>";
}
}
#mysql_free_result($x);
}
Now format your code:
function i_iframe($cadena) {
$x = #mysql_query("SELECT * FROM videos WHERE id_peli = '$cadena' LIMIT 3");
if($i = mysql_fetch_array($x)) {
$option = adios($i['idioma']);
echo '<li class="selected">', $option, '</li>';
while($i = mysql_fetch_array($x)) {
$option = adios($i['idioma']);
echo '<li>', $option, '</li>';
}
}
#mysql_free_result($x);
}
Stop ignoring errors and use clearer names:
function i_iframe($cadena) {
$query = mysql_query("SELECT * FROM videos WHERE id_peli = '$cadena' LIMIT 3");
if($item = mysql_fetch_array($query)) {
$option = adios($item['idioma']);
echo '<li class="selected">', $option, '</li>';
while($item = mysql_fetch_array($query)) {
$option = adios($item['idioma']);
echo '<li>', $option, '</li>';
}
}
mysql_free_result($x);
}
Escape your inputs where they’re used, especially if you weren’t already:
function i_iframe($cadena) {
$cadena = mysql_real_escape_string($cadena);
$query = mysql_query("SELECT * FROM videos WHERE id_peli = '$cadena' LIMIT 3");
if($item = mysql_fetch_array($query)) {
$option = adios($item['idioma']);
echo '<li class="selected">', $option, '</li>';
while($item = mysql_fetch_array($query)) {
$option = adios($item['idioma']);
echo '<li>', $option, '</li>';
}
}
mysql_free_result($x);
}
Now stop using that deprecated extension and enjoy a life of PDO:
function i_iframe($cadena) {
global $db;
$query = $db->prepare('SELECT idioma FROM videos WHERE id_peli = :cadena LIMIT 3');
$query->execute([':cadena' => $cadena]);
$videos = $query->fetchAll(PDO::FETCH_OBJ);
$first = array_shift($videos);
echo '<li class="selected">', htmlspecialchars(adios($first->idioma)), '</li>';
foreach($videos as $video) {
echo '<li>', htmlspecialchars(adios($first->idioma)), '</li>';
}
}

Related

Warp two row with a class after query

I want to warp every two row with a class. So I saw some guideline from here and googling and found foreach array_chunk to do this. And I tried as below which can't display any result. Without foreach its work well. Were is my wrong here please?
In the above picture that I want to do; my every two category warp with a class. And add a divider after each top category.
Here is my tried:
echo '<ul class="dropdown-menu dropdown-menu-large row">';
$sql = "SELECT id,name FROM main_cata ORDER BY id ASC";
$execute = $dbh->query("$sql");
$rowcount = $execute->num_rows ;
$row = $dbh->query($sql) ;
while ($row = $execute->fetch_assoc()) {
foreach (array_chunk($row, 2, true) as $array){
echo'<li class="col-sm-3">';
foreach($array as $rows){
echo '<ul><li class="dropdown-header">'.$rows->name.'</li>';
$sql2 = "SELECT id,name,page FROM catagory WHERE m_cata = '".$rows->id."' ORDER BY id ASC";
$execute2 = $dbh->query("$sql2");
$rowcount2 = $execute2->num_rows ;
$row = $dbh->query($sql) ;
while ($row = $execute2->fetch_assoc()) {
$cid = $row['id'];
$cname = $row['name'];
$page = $row['page'];
echo '<li>'.$cname.'</li>';
}
echo '<li class="divider"></li></ul>';
}
echo '</li>';
}
}
echo '</ul>';
while ($row = $execute->fetch_assoc()) {
fetch_assoc returns 1 row (id, name) from the query, then you are using the result and spliting in 2 (https://secure.php.net/manual/pt_BR/mysqli-result.fetch-assoc.php), What you can do is, make a counter instead of the array chunk that resets every time it reachs 2.
foreach (array_chunk($row, 2, true) as $array){
The content of $row is, for example, array('id' => 1, 'name' => 'Category 1').
foreach($array as $rows){
You are iterating again without needing to.
A simple version:
counter = 0;
echo "<ul>";
while (row = execute->fetch_assoc()) {
if (counter == 0) {
echo "init li";
}
echo "subinit li";
get subcategories
while (row2 = execute2->fetch_assoc()) {
print content
}
echo "subend li";
if (counter == 2) {
counter == 0;
echo "end li";
} else {
counter++;
echo "divider";
}
}
echo "</ul>";

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>';
}

Create dynamic PHP / HTML category tree

I've figured out how to fetch each parent/child with ul > li structure but now I'm stuck, the sub category ul's need a class 'dropdown' but can't figure this out.
My goal is to create an infinite dynamic ul menu with Foundation nav markup.
PHP
function fetchCategoryTreeList($parent = 0, $user_tree_array = '') {
$isParent = '';
if (!is_array($user_tree_array))
$user_tree_array = array();
$sql = "SELECT id,name,parent FROM `categories` WHERE 1 AND parent=$parent ORDER BY id ASC" or die(mysql_error);
if (database_querySelect($sql,$rows)) {
$user_tree_array[] = "<ul>";
foreach ($rows as $row) {
if ($row["parent"] == "0") { $isParent = "has-dropdown"; }
$user_tree_array[] = "<li class='".$isParent."'>". $row["name"]. "</li>";
$user_tree_array = fetchCategoryTreeList($row["id"], $user_tree_array);
}
$user_tree_array[] = "</ul>";
}
return $user_tree_array;
Code to display cat's
<?php
$res = fetchCategoryTreeList();
foreach ($res as $r) {
echo $r;
}
?>
Output
<ul>
<li class='has-dropdown'>Golf Equipment</li>
<ul>
<li class=''>Manual Golf Trolleys</li>
<li class=''>Electric Golf Trolleys</li>
</ul>
<li class='has-dropdown'>Weight Training</li>
<ul>
<li class=''>Weight Benches</li>
<li class=''>Weights</li>
</ul>
</li>
</ul>
My be it help .. I dont know (need a class 'dropdown') for what... you can give the main ul a Class
$user_tree_array[] = "<ul class='main_ul'>";
and then you can use selector in css and jquery
.main_ul .has-dropdown ul {
}
function:
<?php
function fetchCategoryTreeList( $parent = 0, $user_tree_array = "" ) {
if ( ! is_array($user_tree_array))
$user_tree_array = array();
$sql = "SELECT id,name,parent ";
$sql .= "FROM `categories` ";
$sql .= "WHERE 1 AND parent = {$parent} ";
$sql .= "ORDER BY id ASC";
if ( database_querySelect( $sql, $rows) )
{
foreach ( $rows as $row )
{
$user_tree_array[] = "<li class='' >{$row["name"]}</li>";
if ( $parent != $row["id"] )
{
$user_tree_array[] = "<ul>";
$user_tree_array = fetchCategoryTreeList( $connection, $row["id"], $user_tree_array );
$user_tree_array[] = "</ul>";
}
else
{
$user_tree_array = fetchCategoryTreeList( $row["id"], $user_tree_array );
}
}
}
return $user_tree_array;
}
?>
Call:
<?php
$arrays = fetchCategoryTreeList();
foreach ( $arrays as $list)
{
echo $list;
}
?>

Convert PDO::FETCH_ASSOC to SQLite

I am hoping to convert some of my basic settings like my navigation, mysql settings (host, username, password) to SQLite but it seems from something I read this morning there is no equivalent for the command PDO::FETCH_ASSOC. Is there another way for me to do this query that would be compatible with SQLite?
<?
$sql = "SELECT * FROM menu_items WHERE status = 'ACTIVE' ORDER BY menu_parent_id ASC, sortorder ASC, menu_item_name ASC";
$query = $db->query($sql);
$menu_items = array();
while($data = $query->fetch(PDO::FETCH_ASSOC)) {
if($data['menu_parent_id'] == 0) {
$menu_items[$data['menu_item_id']] = array();
$menu_items[$data['menu_item_id']]['menu_item_id'] = $data['menu_item_id'];
$menu_items[$data['menu_item_id']]['name'] = $data['menu_item_name'];
$menu_items[$data['menu_item_id']]['url'] = $data['menu_url'];
$menu_items[$data['menu_item_id']]['fontawesome'] = $data['fontawesome'];
$menu_items[$data['menu_item_id']]['children'] = array();
} else if($data['menu_parent_id'] != 0) {
$tmp = array();
$tmp['menu_item_id'] = $data['menu_item_id'];
$tmp['name'] = $data['menu_item_name'];
$tmp['url'] = $data['menu_url'];
$tmp['fontawesome'] = $data['fontawesome'];
array_push($menu_items[$data['menu_parent_id']]['children'],$tmp);
unset($tmp);
}
}
function create_list($arr)
{
$html = "";
foreach($arr as $key => $value) {
//Here the menu item has children
if(count($value['children']) > 0) {
$html .= '<!-- PARENT --> <li class="mm-dropdown"> <i class="menu-icon fa '. $value['fontawesome']. '"></i><span class="mm-text">'.$value['name'].'</span>
<ul>';
// Here it is the child
foreach($value['children'] AS $child) {
$html .= '
<!-- child --><li><i class="menu-icon fa '. $child['fontawesome']. '"></i>'.$child['name'].'</li>';
}
$html .= ' </ul>
';
} else{
$html .= ' <a class="menu-icon fa '.$value['fontawesome'].'" id="'.$value['menu_item_id'].'" >'.$value['name'].'</a>';
}
}
return $html;
}
?>
So your $query is SQLite3Result ??
try this way then:
while($data = $query->fetchArray(SQLITE3_ASSOC)) {

Using Pagination on product view using Category ID

I feel I have asked alot of questions recently and Im sorry if this is relatively simple but I am struggling to get this working correctly.
I want to add pagination to my product view but when I add the pagination numbers code as seen at the bottom of the page they do not show.
I'm also aware that I should be using mysqli but I want to get this working first before moving over.
Thanks.
Show Product
<div class="link" style="width:100%; height:100%; background-color: white">
<?php
include("../script/dbconnect.php");
include("../script/get_product.php");
$posts = get_posts(null, $_GET['id']);
foreach ( $posts as $post ) {
if ( ! category_exists('name', $post['name']) ) {
$post['name'] = 'Uncategorised';
}
?>
<ul class='featured'>
<li class='headhighlight'><?php echo $post['title']; ?></li>
<li class='pricehigh'><?php echo $post['price']; ?></li>
<li class='imagefeat'><img class='imagelink' src='<?php echo $post['picture']; ?>' alt='$name'></li>
</ul>
<?php
}
?>
</div>
get_product.php
<?php
function get_posts($id = null, $cat_id = null) {
$posts = array();
//Pagination Code
$perpage = 10;
if(isset($_GET["page_num"]))
{
$page_num = intval($_GET["page_num"]);
}
else
{
$page_num = 1;
}
if ($page_num < 1)
{
$page_num = 1;
}
$calc = $perpage * $page_num;
$start = $calc - $perpage;
//End pagination code
$query ="SELECT `products`.`id` AS `name` , `products_cat`.`id` AS `category_id` , `products`.`name` AS `title` , `description` , `price` , `sale` , `picture`
FROM `products`
INNER JOIN `products_cat` ON `products`.`prod_id` = `products_cat`.`id` ";
if ( isset($id) ) {
$id = (int) $id;
$query .= " WHERE `products`.`id` = {$id}";
}
if ( isset($cat_id) ) {
$cat_id = (int) $cat_id;
$query .= " WHERE `products_cat`.`id` = {$cat_id}";
}
$query .= " ORDER BY `products`.`price` DESC Limit $start, $perpage";
$query = mysql_query($query);
echo mysql_error();
while ( $row = mysql_fetch_assoc($query) ) {
$posts[] = $row;
}
return $posts;
}
Pagination Code - to add page numbers - would be placed in showproduct.php
<p class="pagination">
<?php
if(isset($page_num))
{
$result = mysql_query("SELECT COUNT(*) As Total FROM products");
$rows = mysql_num_rows($result);
if($rows)
{
$rs = mysql_fetch_array($result);
$total = $rs["Total"];
}
$totalPages = ceil($total / $perpage);
if($page_num <=1 )
{
echo '<span id="page_links" style="font-weight:bold;"> < </span>';
}
else
{
$j = $page_num - 1;
echo '<span><a id="page_a_link" href="../admin/admin.master.php?page=list_products.php&page_num=' . $j . '"> < </a></span>';
}
for($i=1; $i <= $totalPages; $i++)
{
if($i<>$page_num)
{
echo '<span>' . $i . '</span>';
}
else
{
echo '<span id="page_links" style="font-weight:bold;">' . $i . '</span>';
}
}
if($page_num == $totalPages )
{
echo '<span id="page_links" style="font-weight:bold;">Next ></span>';
}
else
{
$j = $page_num + 1;
echo '<span> > </span>';
}
}
?>
</p>
$posts = get_posts(null, $_GET['id']);
$result = mysql_query($posts);
In the get_posts function you declare this variable as an array, fill it from a query result and then you return it... so it will never work. What were you trying to do here? You have to pass a string to the mysql_query function with correct MySQL query structure.
EDIT: adding the part of the code that is giving problems, and a possible fix.
$posts = get_posts(null, $_GET['id']);
$i = 0;
foreach ($posts as $post){
....
does it work this way? You already did the query with the LIMIT inside the get_posts function and returned the data.
$posts = get_posts(null, $_GET['id']);
returns array, of something. After it you trying to make mysql_query(array); Try to make
var_dump($posts); and copy print here. Or try next:
$posts = get_posts(null, $_GET['id']);
foreach($posts as $post){
$result[] = mysql_query($posts);
}

Categories