Sibin Grasic
Sibin Grasic

Reputation: 714

PHP functions and SQL access layering

I am rewriting a php file which gets persons and their details from an MYSQL DB and layering it (to protect from hacking, etc...)

PHP file that I'm editing currently goes like this:

<div id='idLeft'>
<?php
@session_start();
$_SESSION['auth'] = 'ok';
$db_server = "localhost";
$db_user = "username";
$db_pass = "******";
$db_database = "mydatabase";
    $db_con = @mysql_connect($db_server, $db_user, $db_pass);
if(!$db_con) die("Database error!");
if(!@mysql_select_db($db_database, $db_con)) die("Database error!");
mysql_query("SET NAMES UTF8");

$query = "SELECT osobaID,ime,prezime FROM ssa_osoba";
$rs = mysql_query($query);
$i=0;
while( $row = mysql_fetch_assoc($rs)) {
?>
<div class='osoba'>
    <div class="brojosobe">
    <span class="otekst"><?php echo $i++.'.'; ?></span>
    </div>
    <div class ="imeprezime">
    <span class="otekst"><?php echo $row['ime'].' '.$row['prezime'];?></span>
    </div>
        <div class='hidden'><?php echo $row['osobaID'];?></div>
</div>
<?php
}
?>

I rewrote it like this:

 <?php
@session_start();
try
{   
    require "inc/func.php"; 
    require_once("db/db.php");
    $db = db_layer::get();
    $DBCONNECTION = $db->getHandle();
}
catch( Exception $Ex )
{
    exit();
    //die ( $Ex->getMessage() );
    //echo $Ex;
}

And the part that should output it goes like this.

    <?php
    $i=0;
while( $row = get_osoba() ) {
    ?>
<div class='osoba'>
    <div class="brojosobe">
    <span class="otekst"><?php echo$i++.'.'; ?></span>
    </div>
    <div class ="imeprezime">
    <span class="otekst"><?php echo $row['ime'].' '.$row['prezime'];?></span>
    </div>
<?php
}
?>

My functions are in /inc folder (one file functions.php) I have these functions in it:

function osoba_query()
{
$query ="SELECT osobaID,ime,prezime FROM ssa_osoba";
return mysql_query($query);
}
function get_osoba()
{
$rs =  osoba_query();
static $row = mysql_fetch_assoc($rs);
return $row;
}

But it always outputs only the first row. mysql_fetch_assoc should move the pointer to the next row, but in this case it doesn't.

What should I do?

EDIT1:

If i do this:

$query ="SELECT osobaID,ime,prezime FROM ssa_osoba";
$rs = mysql_query($query);
function get_osoba()
{
global $rs;
$row = mysql_fetch_assoc($rs);
return $row;
}

PHP outputs: Warning: mysql_fetch_assoc() expects parameter 1 to be resource, null given in D:\Xampp\htdocs\ssa\ilayer\inc\func.php on line 7

Upvotes: 1

Views: 163

Answers (1)

Amber
Amber

Reputation: 527558

You're re-running the query every time osoba_query() is called, which resets everything.

Don't do that.

Upvotes: 2

Related Questions