Work with a BD on SMF?

Started by Ikillnukes, April 13, 2013, 03:33:29 PM

Previous topic - Next topic

Ikillnukes

Hi, I'm new in MySQL and SMF, and I don't know how to adapt Normal MySQL to smcFuncs...

Well, I tried something, but it doesn't work:

Juego.template.php

<?php

function template_main()
{

// Make sure we have all the global variables we need
global $txt, $user_info, $sourcedir, $modSettings, $context, $settings, $scripturl, $smcFunc;

$query3 = $smcFunc['db_query']('', "SELECT COUNT(*) FROM juegos");
$result3 = $smcFunc['db_free_result']($query3);
$num_rows = $smcFunc['db_fetch_row']($result3);
$form_query = $smcFunc['db_query']('', 'SELECT DISTINCT categoria,cat2 FROM juegos ORDER BY categoria DESC');
$form_result = $smcFunc['db_free_result']($form_query);
$query = $smcFunc['db_query']('', "SELECT * FROM juegos WHERE cat2 = '$_GET[cat]' ORDER BY id DESC $pages->limit");
$result = $smcFunc['db_free_result']($query);
$query2 = $smcFunc['db_query']('', "SELECT * FROM juegos ORDER BY id DESC $pages->limit");
$result2 = $smcFunc['db_free_result']($query2);

$pages = new Paginator;
$pages->items_total = $num_rows[0];
$pages->mid_range = 9; // Number of pages to display. Must be odd and > 3
$pages->paginate();

echo '<div class="cat_bar">
  <h3 class="catbg">&Uacute;ltimos juegos:</h3>
</div>'
;

// Windowbg2 Content
echo '<div class="windowbg2">
  <span class="topslice"><span></span></span>
    <div class="content">
<table align="center" id="content">'
;

if(empty(
$_GET['cat'])) {
while(
$rs2=$smcFunc['db_fetch_array']($result2))  {

   echo
'
<tr><td class="txt_desc" bgcolor="#FFFFFF"><img src="'
.$rs2['miniatura'].'" width="104" height="70" align="left"><span class="titulos"><a href="http://ikillcraft.a0001.net/test.php?id='.$rs2['id'].'">'.$rs2['nombre'].'</a></span><br>'.$rs2['descripcion'].'</tr><tr><td><hr width="98%" color="#000000" size="2"></td></tr>
<tr>'
;

}
}

while(
$rs=$smcFunc['db_fetch_array']($result))
 {

   echo
'
<tr><td class="txt_desc" bgcolor="#FFFFFF"><img src="'
.$rs['miniatura'].'" width="104" height="70" align="left"><span class="titulos"><a href="http://ikillcraft.a0001.net/test.php?id='.$rs['id'].'">'.$rs['nombre'].'</a></span><br>'.$rs['descripcion'].'</tr><tr><td><hr width="98%" color="#000000" size="2"></td></tr>
<tr>'
;
 }

echo
'
</tr><tr><td>'
;

echo
$pages->display_pages();
echo
"<span class=\"\">".$pages->display_jump_menu().$pages->display_items_per_page()."</span><br>";

echo
' <form method="get" action=""> <select name="cat" onchange="this.form.submit()"> <option>Please select a continent</option>';

while(
$row = $smcFunc['db_fetch_assoc']($form_result))
{
echo "<option value=$row[cat2]>$row[categoria]</option>";
}


echo
'</table></div>
  <span class="botslice"><span></span></span>
</div><br />'
;

}

?>


juegos.php (Source)

<?php

// First of all, we make sure we are accessing the source file via SMF so that people can not directly access the file.
if (!defined('SMF'))
die('Hack Attempt...');

function
Juego()
{

// Second, give ourselves access to all the global variables we will need for this action
global $txt, $user_info, $sourcedir, $modSettings, $context, $settings, $scripturl, $smcFunc;

// Third, Load the specialty template for this action.
loadTemplate('Juego');

//Fourth, Come up with a page title for the main page
$context['page_title'] = $txt['juego_PageTitle'];
$context['page_title_html_safe'] = $smcFunc['htmlspecialchars'](un_htmlspecialchars($context['page_title']));


//Fifth, define the navigational link tree to be shown at the top of the page.
$context['linktree'][] = array(
 
'url' => $scripturl. '?action=juegos',
'name' => $txt['juego'],
);

//Sixth, begin doing all the stuff that we want this action to display
//    Store the results of this stuff in the $context array.  
//    This action's template(s) will display the contents of $context.
$context['juego_Head'] = $txt['juego'];
$context['juego_Body'] = '';
             
}

/*
* PHP Pagination Class
* @author [email protected] - http://www.catchmyfame.com
* @version 2.0.0
* @date October 18, 2011
* @copyright (c) [email protected] (www.catchmyfame.com)
* @license CC Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0) - http://creativecommons.org/licenses/by-sa/3.0/
*/
class Paginator{
var $items_per_page;
var $items_total;
var $current_page;
var $num_pages;
var $mid_range;
var $low;
var $limit;
var $return;
var $default_ipp;
var $querystring;
var $ipp_array;

function Paginator()
{
$this->current_page = 1;
$this->mid_range = 7;
$this->ipp_array = array(10,25,50,100,'All');
$this->items_per_page = (!empty($_GET['ipp'])) ? $_GET['ipp']:$this->default_ipp;
}

function paginate()
{
if(!isset($this->default_ipp)) $this->default_ipp=10;
if($_GET['ipp'] == 'All')
{
$this->num_pages = 1;
// $this->items_per_page = $this->default_ipp;
}
else
{
if(!is_numeric($this->items_per_page) OR $this->items_per_page <= 0) $this->items_per_page = $this->default_ipp;
$this->num_pages = ceil($this->items_total/$this->items_per_page);
}
$this->current_page = (isset($_GET['page'])) ? (int) $_GET['page'] : 1 ; // must be numeric > 0
$prev_page = $this->current_page-1;
$next_page = $this->current_page+1;
if($_GET)
{
$args = explode("&",$_SERVER['QUERY_STRING']);
foreach($args as $arg)
{
$keyval = explode("=",$arg);
if($keyval[0] != "page" And $keyval[0] != "ipp") $this->querystring .= "&" . $arg;
}
}

if($_POST)
{
foreach($_POST as $key=>$val)
{
if($key != "page" And $key != "ipp") $this->querystring .= "&$key=$val";
}
}
if($this->num_pages > 10)
{
$this->return = ($this->current_page > 1 And $this->items_total >= 10) ? "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$prev_page&ipp=$this->items_per_page$this->querystring\">&laquo; Previous</a> ":"<span class=\"inactive\" href=\"#\">&laquo; Previous</span> ";

$this->start_range = $this->current_page - floor($this->mid_range/2);
$this->end_range = $this->current_page + floor($this->mid_range/2);

if($this->start_range <= 0)
{
$this->end_range += abs($this->start_range)+1;
$this->start_range = 1;
}
if($this->end_range > $this->num_pages)
{
$this->start_range -= $this->end_range-$this->num_pages;
$this->end_range = $this->num_pages;
}
$this->range = range($this->start_range,$this->end_range);

for($i=1;$i<=$this->num_pages;$i++)
{
if($this->range[0] > 2 And $i == $this->range[0]) $this->return .= " ... ";
// loop through all pages. if first, last, or in range, display
if($i==1 Or $i==$this->num_pages Or in_array($i,$this->range))
{
$this->return .= ($i == $this->current_page And $_GET['page'] != 'All') ? "<a title=\"Go to page $i of $this->num_pages\" class=\"current\" href=\"#\">$i</a> ":"<a class=\"paginate\" title=\"Go to page $i of $this->num_pages\" href=\"$_SERVER[PHP_SELF]?page=$i&ipp=$this->items_per_page$this->querystring\">$i</a> ";
}
if($this->range[$this->mid_range-1] < $this->num_pages-1 And $i == $this->range[$this->mid_range-1]) $this->return .= " ... ";
}
$this->return .= (($this->current_page < $this->num_pages And $this->items_total >= 10) And ($_GET['page'] != 'All') And $this->current_page > 0) ? "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$next_page&ipp=$this->items_per_page$this->querystring\">Next &raquo;</a>\n":"<span class=\"inactive\" href=\"#\">&raquo; Next</span>\n";
$this->return .= ($_GET['page'] == 'All') ? "<a class=\"current\" style=\"margin-left:10px\" href=\"#\">All</a> \n":"<a class=\"paginate\" style=\"margin-left:10px\" href=\"$_SERVER[PHP_SELF]?page=1&ipp=All$this->querystring\">All</a> \n";
}
else
{
for($i=1;$i<=$this->num_pages;$i++)
{
$this->return .= ($i == $this->current_page) ? "<a class=\"current\" href=\"#\">$i</a> ":"<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$i&ipp=$this->items_per_page$this->querystring\">$i</a> ";
}
$this->return .= "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=1&ipp=All$this->querystring\">All</a> \n";
}
$this->low = ($this->current_page <= 0) ? 0:($this->current_page-1) * $this->items_per_page;
if($this->current_page <= 0) $this->items_per_page = 0;
$this->limit = ($_GET['ipp'] == 'All') ? "":" LIMIT $this->low,$this->items_per_page";
}
function display_items_per_page()
{
$items = '';
if(!isset($_GET[ipp])) $this->items_per_page = $this->default_ipp;
foreach($this->ipp_array as $ipp_opt) $items .= ($ipp_opt == $this->items_per_page) ? "<option selected value=\"$ipp_opt\">$ipp_opt</option>\n":"<option value=\"$ipp_opt\">$ipp_opt</option>\n";
return "<span class=\"paginate\">Items per page:</span><select class=\"paginate\" onchange=\"window.location='$_SERVER[PHP_SELF]?page=1&ipp='+this[this.selectedIndex].value+'$this->querystring';return false\">$items</select>\n";
}
function display_jump_menu()
{
for($i=1;$i<=$this->num_pages;$i++)
{
$option .= ($i==$this->current_page) ? "<option value=\"$i\" selected>$i</option>\n":"<option value=\"$i\">$i</option>\n";
}
return "<span class=\"paginate\">Page:</span><select class=\"paginate\" onchange=\"window.location='$_SERVER[PHP_SELF]?page='+this[this.selectedIndex].value+'&ipp=$this->items_per_page$this->querystring';return false\">$option</select>\n";
}
function display_pages()
{
return $this->return;
}
}

?>


Heeelp!

The page: http://ikillcraft.a0001.net/?action=juegos
Original File: http://pastebin.com/Vhr7uFVM

Bye. ;)

Arantor

Firstly, there should never be database calls in a template unless you have *extremely* good reasons for doing so.

I have no idea what you're actually trying to do though I can tell you that freeing a result before pulling rows from it isn't going to work...
Holder of controversial views, all of which my own.


Ikillnukes

I'm overwhelmed Idk to do... Can you help me, to adapt it? I try 3000 things, but It doesn't work... ;)

If I doesn't put the SmcFuncs, the template charges nothing... (Blank)

So.... I tried some silly things, to try luck.

Arantor

It might be helpful if you started by explaining what you were trying to do.
Holder of controversial views, all of which my own.


emanuele

$query3 = $smcFunc['db_query']('', "SELECT COUNT(*) FROM juegos"); // do the query
$num_rows = $smcFunc['db_fetch_row']($query3); // read the results
$smcFunc['db_free_result']($query3); // free memory


That is basically what you do with "pure" mysql (or whatever) calls. ;)

Of course that's just one example, you have to take care of all the others.

And of course, as Arantor said: queries should never stay in a template (and that include write the code not in the template and then call functions with queries from the template :P).
The "good" way is (well, simplifying): do queries and logic in a file that resides in the "Sources" directory, put the data you need in the variable $context, and then use grab what you need in the template from $context.


Take a peek at what I'm doing! ;D




Hai bisogno di supporto in Italiano?

Aiutateci ad aiutarvi: spiegate bene il vostro problema: no, "non funziona" non è una spiegazione!!
1) Cosa fai,
2) cosa ti aspetti,
3) cosa ottieni.

Ikillnukes

Quote from: emanuele on April 13, 2013, 04:15:58 PM
$query3 = $smcFunc['db_query']('', "SELECT COUNT(*) FROM juegos"); // do the query
$num_rows = $smcFunc['db_fetch_row']($query3); // read the results
$smcFunc['db_free_result']($query3); // free memory


And If want to use it in a PHP While function?




Somebody can explain it to me? Or make the code for me? :)

Arantor

$request = $smcFunc['db_query']('', 'query'...);

while ($row = $smcFunc['db_fetch_assoc']($request))
{
  // do something with the DB rows
}

$smcFunc['db_free_result']($request);
Holder of controversial views, all of which my own.


Ikillnukes

Quote from: Arantor on April 13, 2013, 04:47:38 PM
$request = $smcFunc['db_query']('', 'query'...);

while ($row = $smcFunc['db_fetch_assoc']($request))
{
  // do something with the DB rows
}

$smcFunc['db_free_result']($request);


And I have to put the code into the source... But inside, Juego() Function or outside?

Arantor

Into the Juego function.

You NEVER put stuff outside functions in SMF. EVER.
Holder of controversial views, all of which my own.


Ikillnukes

Quote from: Arantor on April 13, 2013, 04:52:31 PM
Into the Juego function.

You NEVER put stuff outside functions in SMF. EVER.

And Can I put classes in the source?

Arantor

You could even skip that entirely and reuse SMF's function that seems to do the same thing (constructPageIndex)

Good luck.
Holder of controversial views, all of which my own.


Ikillnukes

Well, this is the code:

<?php

function template_main()
{

// Make sure we have all the global variables we need
global $txt, $user_info, $sourcedir, $modSettings, $context, $settings, $scripturl, $smcFunc;

$pages = new Paginator;
$pages->items_total = $num_rows[0];
$pages->mid_range = 9; // Number of pages to display. Must be odd and > 3
$pages->paginate();

echo '<div class="cat_bar">
  <h3 class="catbg">&Uacute;ltimos juegos:</h3>
</div>'
;

// Windowbg2 Content
echo '<div class="windowbg2">
  <span class="topslice"><span></span></span>
    <div class="content">
<table align="center" id="content">'
;

if(empty(
$_GET['cat'])) {
while(
$rs2=$smcFunc['db_fetch_array']($query2))  {

   echo
'
<tr><td class="txt_desc" bgcolor="#FFFFFF"><img src="'
.$rs2['miniatura'].'" width="104" height="70" align="left"><span class="titulos"><a href="http://ikillcraft.a0001.net/test.php?id='.$rs2['id'].'">'.$rs2['nombre'].'</a></span><br>'.$rs2['descripcion'].'</tr><tr><td><hr width="98%" color="#000000" size="2"></td></tr>
<tr>'
;

}
}

while(
$rs=$smcFunc['db_fetch_array']($query))
 {

   echo
'
<tr><td class="txt_desc" bgcolor="#FFFFFF"><img src="'
.$rs['miniatura'].'" width="104" height="70" align="left"><span class="titulos"><a href="http://ikillcraft.a0001.net/test.php?id='.$rs['id'].'">'.$rs['nombre'].'</a></span><br>'.$rs['descripcion'].'</tr><tr><td><hr width="98%" color="#000000" size="2"></td></tr>
<tr>'
;
 }

echo
'
</tr><tr><td>'
;

echo
$pages->display_pages();
echo
"<span class=\"\">".$pages->display_jump_menu().$pages->display_items_per_page()."</span><br>";

echo
' <form method="get" action=""> <select name="cat" onchange="this.form.submit()"> <option>Please select a continent</option>';

while(
$row = $smcFunc['db_fetch_assoc']($form_query))
{
echo "<option value=$row[cat2]>$row[categoria]</option>";
}


echo
'</table></div>
  <span class="botslice"><span></span></span>
</div><br />'
;

$smcFunc['db_free_result']($query);
$smcFunc['db_free_result']($query2);
$smcFunc['db_free_result']($form_query);

}

?>


And:


global $txt,....

$query3 = $smcFunc['db_query']('', "SELECT COUNT(*) FROM juegos");
$num_rows = $smcFunc['db_fetch_row']($query3);
$form_query = $smcFunc['db_query']('', 'SELECT DISTINCT categoria,cat2 FROM juegos ORDER BY categoria DESC');
$query = $smcFunc['db_query']('', "SELECT * FROM juegos WHERE cat2 = '$_GET[cat]' ORDER BY id DESC $pages->limit");
$query2 = $smcFunc['db_query']('', "SELECT * FROM juegos ORDER BY id DESC $pages->limit");

loadTemplate(....

Arantor

constructPageIndex is documented in the function database, and there are literally dozens and dozens of examples in the source of actually using it.

You STILL have $smcFunc calls in the template, which is not how SMF works.

You also have invalid XHMTL, not to mention like XSS-vulnerable code with things like:
<option value=$row[cat2]>$row[categoria]</option>

But I just feel like I'm wasting my time. I wanted to know what you were trying to do, rather than just having some code shoved under my nose and effectively being asked to decipher it, so I won't spend too much more effort on it. There are many hundreds of examples in SMF alone of doing it correctly. Pick almost any page you care to name to see examples of separating logic from presentation.
Holder of controversial views, all of which my own.


Ikillnukes

Where I can see these examples? Can you make me an example code? plz ;)

emanuele

Open any SMF file, or take a mod, you will find plenty of examples: some easy, some more difficult.

This is something I wrote a while ago on the argument:
http://www.simplemachines.org/community/index.php?topic=486179.msg3404221#msg3404221


Take a peek at what I'm doing! ;D




Hai bisogno di supporto in Italiano?

Aiutateci ad aiutarvi: spiegate bene il vostro problema: no, "non funziona" non è una spiegazione!!
1) Cosa fai,
2) cosa ti aspetti,
3) cosa ottieni.

Ikillnukes

#15
Well, I choose the paginator class... The funny thing here, is that If I call the smcFunc it doesn't work, but If write the original code it's works.... :) LOL

Kindred

and you STILL have not answered the question...
WHAT ARE YOU TRYING TO ACCOMPLISH?

What is your final goal in doing this code.

Seriously, you have two developers in this thead who could probably point you to the correct code in minutes if you actually told us what the actual GOAL was instead of insisting on posting incorrect code and trying to insist that you know better.
Слaва
Украинi

Please do not PM, IM or Email me with support questions.  You will get better and faster responses in the support boards.  Thank you.

"Loki is not evil, although he is certainly not a force for good. Loki is... complicated."

Ikillnukes

Well, I'm trying to make a web like Minijuegos.com

I have a "wrong" code, but It works ;)
You can see, the example: http://ikillcraft.a0001.net/index.php?action=juegos

And you can add games here: http://ikillcraft.a0001.net/formulario.php

In other webs people dont code for me. I have to get a life (I'm Spanish, and idk the expression, In spanish is Buscarse la vida)
Well, I'm trying to learn If have a trouble, I will ask for help ;)

All Colours Sam

You're still not telling them what do you want to do. They don't know what minijuegos.com is or what it does.

Having wrong code equals having wrong code as simple as that, there is no wrong that that works, if its wrong it is wrong.

BTW your term "buscarse la vida" does not apply here, if you want help, then yo must be prepare to respond the questions of those who want to help you.


Todavía no has dicho lo que intentas hacer, nosotros no sabemos que es o que hace minujuegos.com, deberás de explicar exctamente que es lo que quieres lograr.

No existe tal cosa como mal código que funcione, si está mal entonces no funciona, así de simple.

Por cierto, el termino que utlizas "buscarse la vida" no tiene nada que ver en esto.
Oh, wouldn't it be great if I *was* crazy? ...then the world would be okay
Suki

Ikillnukes

Suki, tu hablas español? xD

I'm trying to put the DB results on the table, and the results, are the games of the web. ;)

This is that you want? :)

Advertisement: