WebPillangó főoldal
Oldalak: 1 ... 22 23 [24] 25 26 ... 28   Le
  Nyomtatás  
Szerző Téma: PHP  (Megtekintve 62836 alkalommal)
spier
Tag
**
Nem elérhető Nem elérhető

Hozzászólások: 118


« Válasz #460 Dátum: 2010. 08. 13. - 19:49:28 »

Kezdjem nulláról, kuka?  Hááát
Naplózva
Tupacko
WebPillangó

Adminisztrátor
Törzstag
*****
Nem elérhető Nem elérhető

Hozzászólások: 958


WWW
« Válasz #461 Dátum: 2010. 08. 14. - 21:41:28 »

Nem, nem. Nem arra ertettem Mosolyog Csak arra valaszoltam, amit kerdeztel. Annak nincs ertelme, hogy beleeges a kodba a kapcsolodasi adatokat, majd a konstruktorban torold oket. Attol meg nem lesz altalanosan hasznalhato az osztaly, valtoztatas mentesen, mert ha a kapcsolodasi adatok bele vannak teve, akkor bizony azt at kell irni, ha mashova kell csatlakozz.

Udv,
Tupacko
Naplózva
pepe0521
Új tag
*
Nem elérhető Nem elérhető

Hozzászólások: 19


« Válasz #462 Dátum: 2010. 08. 16. - 17:03:40 »

spier köszi pont ilyet kerestem.
Naplózva
spier
Tag
**
Nem elérhető Nem elérhető

Hozzászólások: 118


« Válasz #463 Dátum: 2010. 08. 19. - 16:57:47 »

Nincs mit pepe.
--------------
Értem köszönöm, akkor ez lett a számomra végleges. Nem biztos, hogy 100%-ig megfelel a design pattern-nak de jól működik.
Elvileg akkor csak tovább kell kiegészíteni innen már. A singleton dolgot áttanulmányoztam.

index.php
Kód:
<?php
 
require('settings.inc.php');
 require(
'mysql.class.php');

 
error_reporting(ERR);

 
$db Database::getInstance();
 
$db->setConnection(DB_HOSTDB_USERDB_PASSDB_NAME);
 
$db->setCharset(DB_CHARSET);
 
$db->showError(true);

 
$q "SELECT * FROM user";
 
$r $db->Query($q);
 
$t "Nincs megjeleníthető elem!";

while ($result $db->fetchArray($r$t))
{
echo $result['id'] . '&nbsp;';
echo $result['name'] . '&nbsp;';
echo $result['email'] . '<br />';
}

 
// $name = "Test";
 // $email = "test@test.com";

 // $q = "INSERT INTO user (name, email) VALUES ('{$db->escapeString($name)}', '{$db->escapeString($email)}')";
 // $r = $db->Query($q);

 
$db->Disconnect();

?>

mysql.class.php
Kód:
<?php

 
class Database {

    private 
$db_host ''; // Database Host
    
private $db_user ''; // Username
    
private $db_pass ''; // Password
    
private $db_name ''; // Database
private $db_charset 'utf8'; // Default query character set is utf8

    
private $con false; // Checks to see if the connection is active
private $err false; // Default error messages is E
    
private $result = array(); // Results that are returned from the query

private static $instance null;

/*
 * Prevent constructing of Database
 */
private function __construct() {}

/*
 * Prevent destructing of Database
 */
private function __destruct() {}

/*
 * Prevent cloning of Database
 */
private function __clone() {}

/*
     * Set the database connection paramaters
     */
public function setConnection($db_host$db_user$db_pass$db_name)
{
$this->db_host $db_host;
$this->db_user $db_user;
$this->db_pass $db_pass;
$this->db_name $db_name;
}

/*
     * Set the database connection character set
     */
public function setCharset($db_charset)
{
$this->db_charset $db_charset;
}

/*
     * Connects to the database,
     * only one connection allowed
     */
    
protected function Connect()
{
        if(!
$this->con)
{
            
$MyConn = @mysql_connect($this->db_host,$this->db_user,$this->db_pass) or $this->getError(mysql_errno(), mysql_error(), 'E');
$SelectDb = @mysql_select_db($this->db_name$MyConn) or $this->getError(mysql_errno(), mysql_error(), 'E');

mysql_query("set character set {$this->db_charset}");
mysql_query("set names {$this->db_charset}");

$this->con true;
return true;
        }
else
{
return false;
}

$this->db_host '';
$this->db_user '';
$this->db_pass '';
$this->db_name '';
    }

    
/*
     * Executes query
     */
public function Query($QueryString)
{
if(!$this->con)
{
$this->Connect();
}

$Query = @mysql_query($QueryString) or $this->getError(mysql_errno(), mysql_error(), 'E');
return $Query;
}

    
/*
     * Changes the new database,
     * sets all current results to null
     */
    
public function setDatabase($Name)
{
        if(
$this->con)
{
            if(@
mysql_close())
{
                
$this->con false;
                
$this->result null;
                
$this->db_name $Name;
                
$this->Connect();
            }
        }
    }

    
/*
     * Checks to see if the table exists
     * when performing queries
     */
    
private function tableExists($Table)
{
        
$TablesInDb = @mysql_query('SHOW TABLES FROM '.$this->db_name.' LIKE "'.$Table.'"');
        if(
$TablesInDb)
{
            if(
$this->numRows($TablesInDb)==1)
{
                return 
true;
            }
else
{
                return 
false;
            }
        }
    }

    
/*
     * SQL fetch array query
     */
public function fetchArray($ResultArray$IsNullText 'E')
{
if ($this->numRows($ResultArray) > 0)
{
return @mysql_fetch_array($ResultArray);
}
else
{
echo $IsNullText;
$this->result null;
}
}

    
/*
     * SQL fetch assoc query
     */
public function fetchAssoc($ResultAssoc$IsNullText 'E')
{
if ($this->numRows($ResultAssoc) > 0)
{
return @mysql_fetch_assoc($ResultAssoc);
}
else
{
echo $IsNullText;
$this->result null;
}
}

    
/*
     * SQL fetch row query
     */
public function fetchRow($ResultRow$IsNullText 'E')
{
if ($this->numRows($ResultRow) > 0)
{
return @mysql_fetch_row($ResultRow);
}
else
{
echo $IsNullText;
$this->result null;
}
}

    
/*
     * SQL fetch object query
     */
public function fetchObject($ResultObject$IsNullText 'E')
{
if ($this->numRows($ResultObject) > 0)
{
return @mysql_fetch_object($ResultObject);
}
else
{
echo $IsNullText;
$this->result null;
}
}

    
/*
     * SQL num rows query
     */
public function numRows($QueryRows)
{
$RowNo = @mysql_num_rows($QueryRows);
return $RowNo;
}

    
/*
     * Get SQL last id
     */
public function lastId()
{
$LastId = @mysql_insert_id();
return $LastId;
}

    
/*
     * Get result
     */
public function freeResult($Result)
{
@mysql_free_result($Result);
return true;
}

    
/*
     * Returns the result set
     */
    
public function getResult()
{
        return 
$this->result;
    }

    
/*
 * Sanitizes data for safe execution in SQL query
     */
public function escapeString($Data)
{
if(get_magic_quotes_runtime())
{
$Data stripslashes($Data);
}

return @mysql_real_escape_string($Data);
}

    
/*
     * Show error messages (true or false)
     */
public function showError($Option)
{
$this->err $Option;
}

    
/*
     * Disconnect the connection
     */
public function Disconnect()
{
if($this->con)
{
if(@mysql_close())
{
$this->con false;
return true;
}
else
{
return false;
}
}
}

/*
 * Checks for errors
 */
protected function getError($MysqlErrorNum ''$MysqlError ''$ErrorText 'E') {
if($this->con)
{
$this->Disconnect();
}

if($this->err)
{
die ('Error Number: ' $MysqlErrorNum '<br />Description: ' $MysqlError);
}
else
{
die ($ErrorText);
}
}

/*
 * Creates and references the Database object
 */
public static function getInstance()
{
if(self::$instance == null)
{
self::$instance = new Database();
return self::$instance;
}
}
 }

?>

settings.inc.php
Kód:
<?php

 define
("ERR""0"); // Error reporting

 
define("DB_HOST""localhost"); // Database Host
 
define("DB_USER""admin"); // Username
 
define("DB_PASS""12345"); // Password
 
define("DB_NAME""test"); // Database
 
define("DB_CHARSET""utf8"); // Default query character set

?>
Naplózva
Tupacko
WebPillangó

Adminisztrátor
Törzstag
*****
Nem elérhető Nem elérhető

Hozzászólások: 958


WWW
« Válasz #464 Dátum: 2010. 08. 19. - 20:21:47 »

Na igy mar sokkal jobb Mosolyog

Gratulalok!
Naplózva
spier
Tag
**
Nem elérhető Nem elérhető

Hozzászólások: 118


« Válasz #465 Dátum: 2010. 09. 19. - 15:57:33 »

Szükséges lehet átállni mysql-ről mysqli-re?
Ezt a fenti script-et átírtam de már el sem indul úgy, szükséges lesz manual hozzá ahogy nézem. Valami változott....
Naplózva
spier
Tag
**
Nem elérhető Nem elérhető

Hozzászólások: 118


« Válasz #466 Dátum: 2010. 09. 21. - 15:21:07 »

Érti valaki mit szeretne ez - a mysql classnál van valami baja:
Kód:
Warning: Call to private Database::__destruct() from context '' during shutdown ignored in Unknown on line 0

nekem teljesen értelmetlen.  He
Naplózva
Tupacko
WebPillangó

Adminisztrátor
Törzstag
*****
Nem elérhető Nem elérhető

Hozzászólások: 958


WWW
« Válasz #467 Dátum: 2010. 09. 21. - 19:26:28 »

A MySQLi a MySQL Improved roviditese, vagyis egy feljavitott MySQL kapcsolodas a PHPbol. Erdemes utanaolvasni a php.net-en.
A __destruct() gond onnan jon, hogy az nem szabad private legyen, hanem public, mert hanem az objektumot nem lehet megsemmisiteni.
Naplózva
spier
Tag
**
Nem elérhető Nem elérhető

Hozzászólások: 118


« Válasz #468 Dátum: 2010. 09. 22. - 18:29:02 »

Értem, köszi!
Kipróbáltam, hogy public és úgy nem volt hiba, de mivel én magam nem hívom meg sehol így elvetettem ezt a megoldást/lehetőséget. hmmm

Hogy tudom azt megoldani, hogy a Database class-ban használt lekérdezést pl.:
Kód:
$q = "SELECT * FROM user";
 $r = $db->Query($q);
$result = $db->fetchArray($r);
stb. tudjam használni egy másik class-ban is (User class vagy Session), ami külön fájlban van?

Esetleg ez lenne a megoldás talán? Bár felvet némi problémát, mégpedig, hogy a kapcsolódási adatok nélkül nem fog menni amit pedig az instance miatt nem is adhatok meg minden class-ban meg nem is lenne elegáns. Lehet egyáltalán ilyen megoldást csinálni?

Kód:
<?php
include('mysql.class.php');

class 
User extends Database {
// kód...
}

Naplózva
Tas
Új tag
*
Nem elérhető Nem elérhető

Hozzászólások: 35


« Válasz #469 Dátum: 2010. 09. 23. - 18:34:53 »

Add át magát a Database objektumot az osztály konstruktorának.
Naplózva
spier
Tag
**
Nem elérhető Nem elérhető

Hozzászólások: 118


« Válasz #470 Dátum: 2010. 09. 23. - 21:42:25 »

Értem, köszi.
Megnézek pár nevesebb framework-ot is miként van megoldva.
Valahogy nem áll össze bennem a kép.
Naplózva
spier
Tag
**
Nem elérhető Nem elérhető

Hozzászólások: 118


« Válasz #471 Dátum: 2010. 09. 24. - 05:24:22 »

Sajnos az előző hozzászólásomat nem tudom módosítani... Az este még szögeltem kicsit a kódot, íme (mindenféle kritikát, hozzászólást szívesen veszek, spec. nekem jónak tűnik, megy is ahogy kell):
Kód:
<?php
 
class Database
 
{
    private 
$db_host     '';                        // Database Host
    
private $db_user     '';                        // Username
    
private $db_pass     '';                        // Password
    
private $db_name     '';                        // Database
    
private $db_charset 'utf8';                    // Default query character set is utf8

    
private $con         false;                    // Checks to see if the connection is active
    
private $err         false;                    // Default error messages is Error
    
private $myconn     false;
    private 
$result     = array();                    // Results that are returned from the query

    
private $log_file    'logs/mysqli-log.txt';    // Default log file dir

    
private static $instance null;

    
/**
     * Prevent constructing of Database
     */
    
private function __construct() {}

    
/**
     * Prevent cloning of Database
     */
    
private function __clone() {}

    
/**
     * Destructing the Database
     */
    
public function __destruct()
    {
        if (
$this->con)
        {
            
$this->Disconnect();
        }
    }

    
/**
     * Set the database connection character set
     */
    
public function setCharset($db_charset)
    {
        
$this->db_charset $db_charset;
    }

    
/**
     * Set the database connection paramaters
     */
    
public function setConnection($db_host$db_user$db_pass$db_name)
    {
        if (empty(
$db_host) || empty($db_user) || empty($db_pass) || empty($db_name))
        {
            die (
'Cannot continue, login details not filled out!');
        }

        
$this->db_host $db_host;
        
$this->db_user $db_user;
        
$this->db_pass $db_pass;
        
$this->db_name $db_name;
    }

    
/**
     * Connects to the database,
     * only one connection allowed
     */
    
protected function Connect()
    {
        if (!
$this->con)
        {
            
$this->myconn = new mysqli($this->db_host$this->db_user$this->db_pass$this->db_name);

            if (!
mysqli_connect_error())
            {
                
$this->con true;
                
$this->myconn->query("set names {$this->db_charset}");
                
$this->myconn->query("set character set {$this->db_charset}");
                return 
true;
            }
            else
            {
                
$this->con false;
                
$this->setError(mysqli_connect_error(), mysqli_connect_errno());
                return 
false;
            }
        }
        else
        {
            return 
false;
        }
    }

    
/**
     * Executes query
     */
    
public function Query($qstring)
    {
        if (!
$this->con)
        {
            
$this->Connect();
        }

        
$q $this->myconn->query($qstring) or $this->setError($this->myconn->error$this->myconn->errno);
        return 
$q;
    }

    
/**
     * Changes the new database,
     * sets all current results to null
     */
    
public function setDatabase($name)
    {
        if (
$this->con)
        {
            if (
$this->myconn->close())
            {
                
$this->con false;
                
$this->result null;
                
$this->db_name $name;
                
$this->Connect();
            }
        }
    }

    
/**
     * Checks to see if the table exists
     * when performing queries
     */
    
private function tableExists($table)
    {
        
$tables_in_db $this->myconn->query('SHOW TABLES FROM '.$this->db_name.' LIKE "'.$table.'"');

        if (
$tables_in_db)
        {
            if (
$this->numRows($tables_in_db)==1)
            {
                return 
true;
            }
            else
            {
                return 
false;
            }
        }
    }

    
/**
     * SQL fetch array query
     */
    
public function fetchArray($query_array)
    {
        if (
$query_array)
        {
            return @
mysqli_fetch_array($query_array);
        }
    }

    
/**
     * SQL fetch assoc query
     */
    
public function fetchAssoc($query_assoc)
    {
        if (
$query_assoc)
        {
            return @
mysqli_fetch_assoc($query_assoc);
        }
    }

    
/**
     * SQL fetch row query
     */
    
public function fetchRow($query_row)
    {
        if (
$query_row)
        {
            return @
mysqli_fetch_row($query_row);
        }
    }

    
/**
     * SQL fetch object query
     */
    
public function fetchObject($query_object)
    {
        if (
$query_object)
        {
            return @
mysqli_fetch_object($query_object);
        }
    }

    
/**
     * SQL num rows query
     */
    
public function numRows($query_rows)
    {
        if (
$query_rows)
        {
            
$row_no = @mysqli_num_rows($query_rows);
            return 
$row_no;
        }
    }

    
/**
     * Get SQL last id
     */
    
public function lastID()
    {
        
$last_id = @mysqli_insert_id();
        return 
$last_id;
    }

    
/**
     * Get result
     */
    
public function freeResult($query_result)
    {
        if (
$query_result)
        {
            @
mysqli_free_result($query_result);
            return 
true;
        }
    }

    
/**
     * Returns the result set
     */
    
public function getResult()
    {
        return 
$this->result;
    }

    
/**
     * Sanitizes value for safe execution in SQL query
     */
    
public function escapeString($value)
    {
        if (
get_magic_quotes_gpc())
        {
            
$value stripslashes($value);
        }
        return @
mysqli_real_escape_string($value);
    }

    
/**
     * Show error messages (true or false)
     */
    
public function showError($option)
    {
        if (
$option)
        {
            
$this->err $option;
        }
    }

    
/**
     * Set the log file
     */
    
public function logDirectory($dir)
    {
        if (
$dir)
        {
            
$this->log_file $dir;
        }
    }

    
/**
     * Disconnect the connection
     */
    
public function Disconnect()
    {
        if (
$this->con)
        {
            if (
$this->myconn->close())
            {
                
$this->con false;
                return 
true;
            }
            else
            {
                return 
false;
            }
        }
    }

    
/**
     * Checks for errors
     */
    
protected function setError($mysqli_error ''$mysqli_errno '')
    {
        if (
$this->con)
        {
            
$this->Disconnect();
        }

        if (
$this->err)
        {
            die (
'Description: ' $mysqli_error '<br />Error Number: ' $mysqli_errno);
        }
        else
        {
            
// Write mysqli error messages in log file
            
if (is_file($this->log_file) && is_writable($this->log_file))
            {
                
$fh fopen($this->log_file'a');
                
$fh_date date('Y-m-d H:i:s');

                
fwrite($fh$fh_date " Description: " $mysqli_error " Error Number: " $mysqli_errno "\r\n");
                
fclose($fh);
            }

            die (
'Error');
        }
    }

    
/**
     * Creates and references the Database object
     */
    
public static function getInstance()
    {
        if (
self::$instance == null)
        {
            
self::$instance = new Database();
            return 
self::$instance;
        }
    }
 }
?>
Naplózva
Tupacko
WebPillangó

Adminisztrátor
Törzstag
*****
Nem elérhető Nem elérhető

Hozzászólások: 958


WWW
« Válasz #472 Dátum: 2010. 09. 25. - 11:47:32 »

Szia!

Szerintem ket dolognak meg erdemes utanaolvass: try-catch hasznalata es az SQL injection kivedese.

Udv,
Tupacko
Naplózva
lowert
Tag
**
Nem elérhető Nem elérhető

Hozzászólások: 111


« Válasz #473 Dátum: 2010. 09. 25. - 18:36:01 »

En azt gondolom, hogy ahhoz, hogy valakibol jo programozo valjek, nem feltetlen kell az egyetemen informatika szakra jarnia... Rengeteg olyan kivalo programozot ismerek, aki fizika szakon vegzett, es kozben, illetve utana tanult programozni. Mellesleg engem az utobbi idoben nagyon erdekel az elmeleti fizika, foleg a kvantumfizika, ugyhogy meg az is lehet, hogy az egyetemen fizikat fogok tanulni. Egyik celom, hogy valamelyik amerikai egyetemen tanulhassak.
Naplózva
spier
Tag
**
Nem elérhető Nem elérhető

Hozzászólások: 118


« Válasz #474 Dátum: 2010. 09. 26. - 03:30:09 »

Tupacko,
aham, egy fapados mysqli_real... már van benne de még utána nézek az összes ilyen lehetőségnek.
Utána olvasok a try catch-nek, ez ugye a kivétel kezelés?

Tas,
sehogy sem sikerül másik class-ba beleszögelnem a Database-t. Mindig fatal error-t kapok az instance miatt.
Csak próbaképpen a $db-t globálissá tettem úgy hibátlanul működött de ha jól emlékszem akkor ez nem valami jó megoldás, fölülírható bárhonnan stb... Kemény dió...  Mosolyog
Naplózva
Tas
Új tag
*
Nem elérhető Nem elérhető

Hozzászólások: 35


« Válasz #475 Dátum: 2010. 09. 26. - 19:48:39 »

Itt egy egyszerű példa. Elsőként létrehozod az adatbázis objektumot, utána átadod egy másik osztály konstruktorának. Innentől kezdve az adatbázis kapcsolat elérhető lesz az adott osztályban is.
Kód:
<?php
require 'config.php';
require 
'database.class.php';
require 
'users.class.php';

// adatbazis beallitas
$db Database::GetInstance();
$db->setConnection(DBHOSTDBUSERDBPASSDBNAME);

// users osztaly peldanyositas
$users = new Users($db);

// user adatok
$data = array(
'name' => 'user',
'email' => 'user@user.hu',
'added' => date('Y-m-d H:i:s')
);

// insert user
$users->add($data);
?>


<?php
// pelda a Users osztalyra
class Users {

private $db null;

public function __construct(Database $db) {
$this->db $db;
}

function add(array $data) {
$this->db->Connect();
$sql "INSERT INTO users(
name, email, added

VALUES (
'"
.$data['name']."',
'"
.$data['email']."',
'"
.$data['added']."'
)"
;
$this->db->Query($sql);

$this->db->Disconnect();
}
}

?>
Naplózva
spier
Tag
**
Nem elérhető Nem elérhető

Hozzászólások: 118


« Válasz #476 Dátum: 2010. 09. 28. - 22:06:58 »

Sikeres Vigyorog, köszi. Az életbe nem jöttem volna rá magamtól, hogy itt is lehet átadni paramétereket és miegymást mint a funkcióknál ($users = new Users($db)Kacsint.
Naplózva
Tas
Új tag
*
Nem elérhető Nem elérhető

Hozzászólások: 35


« Válasz #477 Dátum: 2010. 09. 28. - 22:37:54 »

Igazából nem magadnak kéne rájönni, hanem inkább valami PHP-vel vagy objektum orientált programozással foglalkozó könyv segítségével Kacsint
Naplózva
spier
Tag
**
Nem elérhető Nem elérhető

Hozzászólások: 118


« Válasz #478 Dátum: 2010. 09. 29. - 21:38:13 »

Igen, szükséges lesz.
Még egyszer thx.
Naplózva
kovger

Új tag
*
Nem elérhető Nem elérhető

Hozzászólások: 89


WWW
« Válasz #479 Dátum: 2010. 10. 01. - 18:10:16 »

Üdv, jó régen jártam már itt.

Mivel a prog.hu-s tagok szokásukhoz híven megint leugattak a kérdésem miatt, ezért újra hozzátok fordulok segítségért.
Természetesen használtam a keresőt, de hiába.
Egy olyan oldalt készítek, amit rajtam kívül, csak pár ember olvashat, ezért nem szeretném, ha a google rátalálna az oldalra. Milyen módon lehetne távol tartani a kereső oldalakat?
Naplózva
Oldalak: 1 ... 22 23 [24] 25 26 ... 28   Fel
  Nyomtatás  
 
Ugrás: