1. Post #1441
    zhed+redball.jpg
    xmariusx's Avatar
    May 2010
    1,367 Posts
    I could need some help over here: http://venator.zxq.net/

    I would like the boxes to stretch to the bottom. the min-height is set to 460px.
    height:100%; won't work.

    Also, under the What people say, and after pressed the button Comment yourself, the close button doesn't work. Ideas? (take a look at the source code)

    |-- Edited: --|
    I have a problem where to navigation tiles randomly generates horizontaly or verticaly.
    |-- --------- --|


    Feedback at: http://facepunch.com/threads/1152034...1#post35345725 :)
    Reply With Quote Edit / Delete Windows 7 Norway Show Events

  2. Post #1442
    -Kesil-'s Avatar
    February 2012
    87 Posts
    Cool stuff I found.
    http://developer.mozilla.org/media/u...ge/index.html#

    Gonna start working on kinetic websites like this... but with purpose. It will be hard to find a good purpose.

    How am I defining kinetic? Sites with ambient motion.
    Reply With Quote Edit / Delete Mac United States Show Events

  3. Post #1443
    http://lesscss.org/
    ^why isn't CSS like this by default?
    Is it just because they didn't think of it?
    SASS and SCSS are a little more powerful than LESS (or at least they were when I last checked the differences between them) check those out.
    Reply With Quote Edit / Delete Mac United States Show Events Agree Agree x 1 (list)

  4. Post #1444
    Gold Member
    Bambo.'s Avatar
    April 2011
    485 Posts
    Hey guys, quick noob PHP question. I'm handling registrations like this:

    Code:
    <?php
    
    $data = $data["data"];
    
    Register( $data["title"], $data["tagline"], $data["password"], $data["email"], $data["twitter"], $data["linkedin"], $data["blogger"] );
    
    function Register( $title, $tagline, $password, $email, $twitter, $linkedin, $blogger )
    {
    	$con = mysql_connect("localhost", "root", "root");
    	if(!$con)
    	{
    		die('Could not connect');
    	}
    
    	mysql_select_db("SocialProject", $con);
    
    	$password = mysql_real_escape_string(strip_tags($password));
    	$password = Crypter::encrypt($password);
    
    	$title = mysql_real_escape_string(strip_tags($title));
    	$tagline = mysql_real_escape_string(strip_tags($tagline));
    
    	$email = mysql_real_escape_string(strip_tags($email));
    	$twitter = mysql_real_escape_string(strip_tags($twitter));
    	$linkedin = mysql_real_escape_string(strip_tags($linkedin));
    	$blogger = mysql_real_escape_string(strip_tags($blogger));
    
    	if( mysql_query("INSERT INTO users (title, tagline, password, email, twitter, linkedin, blogger) VALUES ('$title', '$tagline', '$password', '$email', '$twitter', '$linkedin', '$blogger');") )
    	{
    		$id = getID( $password );
    		echo "<meta http-equiv='REFRESH' content='0;url=profile/$id'>";
    	} else {
    		echo "Something has gone terribly wrong! please hang in there as we try to resolve this problem. Email us at admin@LOLLOL.com to inform us about this error.";
    	}
    	die( mysql_error() );
    
    	mysql_close($con);
    }
    
    function getID( $password )
    {
    	$con = mysql_connect("localhost","root","root");
    	if (!$con)
      	{
      		die('Could not connect: ' . mysql_error());
      	}
    
    	mysql_select_db("SocialProject", $con);
    
    	$result = mysql_query("SELECT * FROM users WHERE password='$password'");
    
    	while($row = mysql_fetch_array($result))
     	{
      		$id = $row['id'];
      	}
    
      	return $id;
    
    	mysql_close($con);
    }
    ?>
    In my registrations there will be a lot more options added onto it ( facebook.etc ) and I'm wondering whether there is a better way to add them all without hard coding(?) then in. Also any suggestions to improve the code is appreciated.
    Reply With Quote Edit / Delete Mac United Kingdom Show Events

  5. Post #1445
    Gold Member
    StinkyJoe's Avatar
    June 2006
    2,194 Posts
    In my registrations there will be a lot more options added onto it ( facebook.etc ) and I'm wondering whether there is a better way to add them all without hard coding(?) then in. Also any suggestions to improve the code is appreciated.
    Use a separate table for the different services. For example, represented as a pseudo-schema:

    ▤ table user :
    ╠ id
    ╠ name
    ╠ password
    ╠ password_schema
    ╚ etc

    ▤ table services :
    ╠ user_id
    ╠ service_id
    ╚ etc


    The service_id can also be used to join with a services table, or just a constant value that you use to identify the service. This isn't a 100% flexible solution as you'll still have to settle with a schema for how individual service data is stored, but it's a good middle-ground that doesn't go off into the more complex end of things.
    Reply With Quote Edit / Delete Linux Portugal Show Events Artistic Artistic x 2 (list)

  6. Post #1446
    Meow :3
    Ac!dL3ak's Avatar
    July 2005
    6,045 Posts
    // code snip
    This produces this:

    Whereas it SHOULD be random pixels all over?
    both $x and $y should start at 0, and the loops should be until $y > $height or $x > $width

    why don't you pick three random numbers between 0 and 255 instead of picking random characters, though?
    Reply With Quote Edit / Delete Linux United Kingdom Show Events

  7. Post #1447
    Gold Member
    Bambo.'s Avatar
    April 2011
    485 Posts
    Use a separate table for the different services. For example, represented as a pseudo-schema:

    ▤ table user :
    ╠ id
    ╠ name
    ╠ password
    ╠ password_schema
    ╚ etc

    ▤ table services :
    ╠ user_id
    ╠ service_id
    ╚ etc


    The service_id can also be used to join with a services table, or just a constant value that you use to identify the service. This isn't a 100% flexible solution as you'll still have to settle with a schema for how individual service data is stored, but it's a good middle-ground that doesn't go off into the more complex end of things.
    Neat. Thanks!
    Reply With Quote Edit / Delete Mac United Kingdom Show Events

  8. Post #1448
    Gold Member
    Snakess's Avatar
    July 2005
    3,013 Posts
    Maybe I should start learning something about server stuff... I have no idea what to do to make a VPS working and host websites on it with features I can't do with shared hosting. But I don't see any way of learning it without first renting one, and it feels kinda stupid to spend money on something alien to me.
    PM me if you like, I have a VPS I'm not using currently that you can have a play on if you like, I'll give you some help if you need any, not that I know loads about VPS' myself
    Reply With Quote Edit / Delete Windows 7 United Kingdom Show Events Friendly Friendly x 1 (list)

  9. Post #1449
    RUBY OVERLORD
    swift and shift's Avatar
    November 2011
    2,115 Posts
    I completely agree with you, it doesn't.

    Here it is:
    Code:
    ActiveRecord::Schema.define(:version => 20120321200514) do
    
      create_table "posts", :force => true do |t|
        t.string   "title"
        t.text     "description"
        t.datetime "created_at",  :null => false
        t.datetime "updated_at",  :null => false
        t.string   "user"
        t.integer  "user_id"
        t.integer  "time"
      end
    
      create_table "users", :force => true do |t|
        t.string   "name"
        t.text     "password"
        t.text     "pin"
        t.datetime "created_at", :null => false
        t.datetime "updated_at", :null => false
        t.text     "salt"
      end
    
    end
    P.S.: Yeah, I know some fields in "posts" table are not necessary, but I'm still learning, so didn't knew about some stuff.
    A couple of hints here: the 'text' type is designed for storing data that's several kilobytes long, you probably shouldn't use it for the password, pin, or salt. It's fine to use it for the post description though. Secondly, (this is just stylistic though) you should prefer to use symbols rather than strings in migrations. Thirdly, why have you got a string column called 'user' in your posts table?

    Anyway, with regard to your actual problem, can you see if something like this works as expected:

    User.where("pin = ?", "753e345a113471a6775e242f444704fe")
    Reply With Quote Edit / Delete Mac Australia Show Events

  10. Post #1450
    Gibo990's Avatar
    January 2008
    281 Posts
    Probably a basic question but i've just started learning HTML and CSS.

    I want to have a background image similar to how www.ebuyer.com have theirs. I was just wondering how they went about doing that?

    Here's my CSS file:

    Code:
    * { padding: 0; margin: 0; }
    
    body {
     font-family: Verdana, Arial, Helvetica, sans-serif;
     font-size: 13px;
     
    }
    
    p {
     padding: 10px;
    }
    
    #wrapper { 
     margin: 0 auto;
     width: 50%;
    }
    
    /* Content is where the main items go */
    #content { 
     float: left;
     color: #333;
     background: #FFFFFF;
     height: 1024px;
     width: 100%;
     display: inline;
    }
    
    /* Header is the top of the page banner (holds items in it below) */
    #header {
     background: url(../images/headerBackground.png);
     width: 100%;
     float: left;
     background-position: top;
     height: 120px;
    }
    
    /* Items used in the HEADER */
    #logo {
    margin-left: auto;
    margin-right: auto;
    }
    
    /* Facebook follow button */
    #facebook {
    margin-left: auto;
    margin-right: auto;
    margin-top: 25px;
    }
    
    /*Twitter follow button */
    #twitter {
    margin-left: auto;
    margin-right: auto;
    margin-top: 25px;
    }
    
    #footer { 
     width: 100%;
     height: 100px;
     clear: both;
     color: #333;
     background: #FFA840;
    }
    
    #navigation {
     float: left;
     width: 100%;
     height: 25px;
     color: #333;
     background: #3C9DD0;
    }
    So I've changed the #wrapper width to 50% and it now looks like ebuyers where there is two gaps either side and a middle part where the content goes. I have a feeling I shouldn't be doing this so any help would be very appreciated. If it's right do I just use a background: url...... in the wrapper?
    Reply With Quote Edit / Delete Windows 7 United Kingdom Show Events

  11. Post #1451
    Gold Member
    jaybuz's Avatar
    May 2006
    5,516 Posts
    Wrapper needs a set width of 980px and then the background needs to be attachment fixed. The background image itself is just a 1920x1080 graphic with a 1020px white section in the center.
    Reply With Quote Edit / Delete Mac United Kingdom Show Events Winner Winner x 1Agree Agree x 1 (list)

  12. Post #1452
    Upload Images
    kragmars102's Avatar
    April 2011
    727 Posts
    Probably a basic question but i've just started learning HTML and CSS.

    I want to have a background image similar to how www.ebuyer.com have theirs. I was just wondering how they went about doing that?

    // code.

    So I've changed the #wrapper width to 50% and it now looks like ebuyers where there is two gaps either side and a middle part where the content goes. I have a feeling I shouldn't be doing this so any help would be very appreciated. If it's right do I just use a background: url...... in the wrapper?
    http://ezyimg.info/v/2L43HBcPBev.jpg basic template that you can use, the white is where the content comes ( I'm guesing your content is 1000px in width ). To save filesize on the background you can delete the part of the image that the content is covering.
    Reply With Quote Edit / Delete Windows 7 Australia Show Events Winner Winner x 1 (list)

  13. Post #1453
    Gold Member
    CBastard's Avatar
    April 2011
    410 Posts
    You could also add these so that the background dynamically re-sizes and maintains its aspect ratio:

    Code:
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    Reply With Quote Edit / Delete Windows 7 United Kingdom Show Events

  14. Post #1454
    Gold Member
    jaybuz's Avatar
    May 2006
    5,516 Posts
    Not for fixed size content thought. Like above.
    Reply With Quote Edit / Delete Mac United Kingdom Show Events Agree Agree x 1 (list)

  15. Post #1455
    Gold Member
    Crhem van der B's Avatar
    January 2010
    1,690 Posts
    A couple of hints here: the 'text' type is designed for storing data that's several kilobytes long, you probably shouldn't use it for the password, pin, or salt. It's fine to use it for the post description though. Secondly, (this is just stylistic though) you should prefer to use symbols rather than strings in migrations. Thirdly, why have you got a string column called 'user' in your posts table?

    Anyway, with regard to your actual problem, can you see if something like this works as expected:

    User.where("pin = ?", "753e345a113471a6775e242f444704fe")
    Thanks for the info regarding the table. And I have a user column because I forgot about user_id..
    Anyhow, the method you posted doesn't seem to work as expected..

    Code:
    	def check_user
    		user = User.where("pin = ?", "753e345a113471a6775e242f444704fe")
    
    		if user.nil?
    			'nil'
    		else
    			'not nil'
    		end
    	end
    returns "not nil", however if I do user.name, it returns just "User".
    And if I do user.pin, it throws an error:
    Code:
     undefined method `pin' for []:ActiveRecord::Relation
    Yeah... I don't know anymore..
    Reply With Quote Edit / Delete Windows 7 United States Show Events

  16. Post #1456
    Gold Member
    hexpunK's Avatar
    August 2008
    15,140 Posts
    On my acer laptop that overheats when I start up windows media player?
    I think something like this would lend itself to a platform like the Raspberry Pi You could easily install a Linux OS that supports ARM, and install a web server that supports ARM on it to just learn how to configure the servers. Then connect the Pi to your network and play around with web development.
    Reply With Quote Edit / Delete Windows 7 United Kingdom Show Events

  17. Post #1457
    quality poster
    Dennab
    August 2009
    12,242 Posts
    -useless question-
    Reply With Quote Edit / Delete Windows 7 United States Show Events

  18. Post #1458
    Gold Member
    hexpunK's Avatar
    August 2008
    15,140 Posts
    Code:
    border-collapse: collapse
    Stick that in your CSS for the cells and see if it goes away. This is assuming it isn't there already seeing as you didn't give us any idea what the CSS is like currently.
    Reply With Quote Edit / Delete Windows 7 United Kingdom Show Events

  19. Post #1459
    RUBY OVERLORD
    swift and shift's Avatar
    November 2011
    2,115 Posts
    Thanks for the info regarding the table. And I have a user column because I forgot about user_id..
    Anyhow, the method you posted doesn't seem to work as expected..

    Code:
    	def check_user
    		user = User.where("pin = ?", "753e345a113471a6775e242f444704fe")
    
    		if user.nil?
    			'nil'
    		else
    			'not nil'
    		end
    	end
    returns "not nil", however if I do user.name, it returns just "User".
    And if I do user.pin, it throws an error:
    Code:
     undefined method `pin' for []:ActiveRecord::Relation
    Yeah... I don't know anymore..
    If you like I can take a look over TeamViewer in about 6 hours for you.

    Add me on skype: turbeh
    Reply With Quote Edit / Delete Australia Show Events

  20. Post #1460
    quality poster
    Dennab
    August 2009
    12,242 Posts
    Code:
    border-collapse: collapse
    Stick that in your CSS for the cells and see if it goes away. This is assuming it isn't there already seeing as you didn't give us any idea what the CSS is like currently.
    yeah sorry my post was utter shit and really not detailed enough to get any help for

    i'll make another post tomorrow with more details, thanks anyway
    Reply With Quote Edit / Delete Windows 7 United States Show Events

  21. Post #1461
    Gold Member
    twenty's Avatar
    March 2011
    539 Posts
    http://lolcode.com/

    Code:
    HAI
    CAN HAS STDIO?
    VISIBLE "HAI WORLD!"
    KTHXBYE
    God have mercy...
    Reply With Quote Edit / Delete Windows 7 Australia Show Events Late Late x 1Dumb Dumb x 1 (list)

  22. Post #1462
    Gold Member
    marcin1337's Avatar
    May 2006
    875 Posts
    hey guys, on my website login screen, user puts in his password and username, I then check in php ( sha1 + salt ) if it matches with the one with the MySQL server , if it does I do
    session_regenerate_id();
    $_SESSION['valid']=1;
    $_SESSION['userid'] = $username;

    I then check on every other page
    if(isset($_SESSION['valid']) && $_SESSION['valid'])

    is this safe?
    Reply With Quote Edit / Delete Windows 7 United States Show Events

  23. Post #1463
    Gold Member
    jetboy's Avatar
    January 2009
    2,256 Posts
    hey guys, on my website login screen, user puts in his password and username, I then check in php ( sha1 + salt ) if it matches with the one with the MySQL server , if it does I do
    session_regenerate_id();
    $_SESSION['valid']=1;
    $_SESSION['userid'] = $username;

    I then check on every other page
    if(isset($_SESSION['valid']) && $_SESSION['valid'])

    is this safe?
    It's definitely not the best solution, but it's not really unsafe as long as you protect against session jacking.
    Reply With Quote Edit / Delete Windows 7 United States Show Events Dumb Dumb x 1 (list)

  24. Post #1464
    Gold Member
    Spero78's Avatar
    August 2010
    253 Posts
    hey guys, on my website login screen, user puts in his password and username, I then check in php ( sha1 + salt ) if it matches with the one with the MySQL server , if it does I do
    session_regenerate_id();
    $_SESSION['valid']=1;
    $_SESSION['userid'] = $username;

    I then check on every other page
    if(isset($_SESSION['valid']) && $_SESSION['valid'])

    is this safe?
    You can just do
    $_SESSION['valid']=TRUE;
    
    if($_SESSION['valid']){
    //Do Things
    }
    

    Pretty sure thats how most sites do it,

    Personally i store the users ID, a hashed password (hmac), expiry time and a cookie hash in a string in a cookie and use a Regular Expression to separate it into an array and validate the users password every time they visit the site.

    My system is quite hacked together because I was using a cookie generated by forum software so im not going to share it but the cookie works like this,

    	if (isset($_COOKIE['cookie_name']) && preg_match('%^(\d+)\|([0-9a-fA-F]+)\|(\d+)\|([0-9a-fA-F]+)$%', $_COOKIE['cookie_name'], $matches))
    		{
    			$cookie = array(
    				'user_id'		=> intval($matches[1]),
    				'password_hash' 	=> $matches[2],
    				'expiration_time'	=> intval($matches[3]),
    				'cookie_hash'	=> $matches[4],
    			);
    		}
    
    Reply With Quote Edit / Delete Windows 7 United Kingdom Show Events Dumb Dumb x 3Informative Informative x 1 (list)

  25. Post #1465
    RUBY OVERLORD
    swift and shift's Avatar
    November 2011
    2,115 Posts
    no no no no

    just store the user's id and check if it's there or not

    sessions are completely 100% tamper proof
    Reply With Quote Edit / Delete Australia Show Events Friendly Friendly x 1Agree Agree x 1 (list)

  26. Post #1466
    Meow :3
    Ac!dL3ak's Avatar
    July 2005
    6,045 Posts
    no no no no

    just store the user's id and check if it's there or not

    sessions are completely 100% tamper proof
    unless someone has direct access to your server but i mean

    if they do then you should be worried about something else other than sessions
    Reply With Quote Edit / Delete Linux United Kingdom Show Events Friendly Friendly x 1Agree Agree x 1 (list)

  27. Post #1467
    Gold Member
    Shortyish's Avatar
    August 2008
    3,002 Posts
    does anyone have any experience with the parallels plesk control panel? im trying to set up a website for the first time and i have no idea how to put my html in to actually make it show up.
    Reply With Quote Edit / Delete Windows Vista United States Show Events Programming King Programming King x 2 (list)

  28. Post #1468
    Upload Images
    kragmars102's Avatar
    April 2011
    727 Posts
    Just something that might come useful in the future to restrict content just do:

    Code:
    if(!isset($_SESSION['valid']) || !$_SESSION['valid']) { die(); }
    Reply With Quote Edit / Delete Windows 7 Australia Show Events Disagree Disagree x 2 (list)

  29. Post #1469
    Gold Member
    marcin1337's Avatar
    May 2006
    875 Posts
    In PHP

    I have a class lets say ImgEntry within it I have variables for its source, text, title , etc, and some functions I need to put it on a website.

    I have a MySQL database full of these .

    What I'm asking is how do I get all of these in the MySQL db into the class?,

    do I create an instance for each member of the MySQL db? if so how?!

    do I create one instance of the class and modify the class so it accepts arrays
    Reply With Quote Edit / Delete Windows XP United States Show Events

  30. Post #1470
    Gold Member
    StinkyJoe's Avatar
    June 2006
    2,194 Posts
    In PHP

    I have a class lets say ImgEntry within it I have variables for its source, text, title , etc, and some functions I need to put it on a website.

    I have a MySQL database full of these .

    What I'm asking is how do I get all of these in the MySQL db into the class?,

    do I create an instance for each member of the MySQL db? if so how?!

    do I create one instance of the class and modify the class so it accepts arrays
    You create a new instance for each row in your result set:

    Pseudo-something example:

    class MyThing
    {
        private $data = array()
    
        public function __construct(array $data)
        {
            $this->data = $data
        }
    }
    
    
    $results = <mysql query>
    $results->each(function($row)
    {
        $row = new MyThing($row)
    })
    
    Reply With Quote Edit / Delete Linux Portugal Show Events Friendly Friendly x 1 (list)

  31. Post #1471
    Gold Member
    marcin1337's Avatar
    May 2006
    875 Posts
    You create a new instance for each row in your result set:

    Pseudo-something example:

    class MyThing
    {
        private $data = array()
    
        public function __construct(array $data)
        {
            $this->data = $data
        }
    }
    
    
    $results = <mysql query>
    $results->each(function($row)
    {
        $row = new MyThing($row)
    })
    
    ok here is how I did it based on what you wrote

    	
    $results = mysql_query("SELECT * FROM Images");
    	
    	while( $row = mysql_fetch_array($results)){
    		$row['key'] = new ClassTest();
    		$row['key']->imgURL = $row['img_url'];
    		$row['key']->ShowImage();
    		}
    
    

    is this really how it is done in the real world?
    Reply With Quote Edit / Delete Windows 7 United States Show Events

  32. Post #1472
    Upload Images
    kragmars102's Avatar
    April 2011
    727 Posts
    Please excuse the long post. I'm looking to create this as efficiently as possible, it's for a online store. I'm new to classes

    Code:
    	  // database class.
    	  class Database {
    	    var $host;
    	    var $username;
    	    var $password;
    	    var $table;
    		// connect.
    	    public function connect() {
    		  mysql_connect($this->host,$this->username,$this->password) or die ("Could not establish a connection to ".$this->table);
    		  mysql_select_db($this->table) or die ("Error selecting database.");
    	    }
    		// display.
    		public function extract($data) {
    		  if(isset($data['type'])) {
    		    switch ($data['type']) {
    		      // products.
    		      case "product":
    		      if(!$data['id']) { $query = mysql_query("SELECT * FROM products"); } else { $query = mysql_query("SELECT * FROM products WHERE id='{$data['id']}'"); } return $query;
    		    break;
    		      // user.
    		      case "user":
    		    
    		    break;
    		      // cart.
    		      case "cart":
    		    
    		    break;
    		    }
    		  } 
    		}
    	  }
    	  
    	  // database object.
    	  $obj = new Database();
    	  
    	  // establish a connection.
    	  $obj->host = "localhost";
    	  $obj->username = "root";
    	  $obj->password = "";
    	  $obj->table = "stickers";
    	  $obj->connect();
    	  
    	  // list products.
    	  $proquery = array('type'=>'product','id'=>'');
    	  $products = $obj->extract($proquery);
    	  
    	  while($row = mysql_fetch_array($products)) {
    	    // gather product details.
    	    $product['name'] = (strlen($row['name']) > 0) ? ucfirst($row['name']) : "Untitled";
    	    $product['category'] = $row['category'];
    	    $product['price'] = $row['price'];
    	    $product['images'] = (strlen($row['images']) > 0) ? $row['images'] : "default.jpg";
    	    $product['images'] = explode(';',$product['images']);
    	    $product['quantity'] = ($row['quantity'] > 0) ? $row['quantity'] : "No stock avaliable";
    	    $product['voucher'] = $row['voucher'];
    	    $product['time'] = $row['time'];
    	    $product['description'] = (strlen($row['description']) > 0) ? $row['description'] : "No description avaliable";
    		// display product.
    		$display  = '<div id="product">';
    		 $display .= '<span class="grunge"></span>';
    		 $display .= '<img src="img/content/'.$product['images'][0].'" />';
    		 $display .= '<h4>'.$product['name'].'</h4>';
    		$display .= '</div>';
    		echo $display;
    	  }
    Reply With Quote Edit / Delete Windows 7 Australia Show Events

  33. Post #1473
    Gold Member
    StinkyJoe's Avatar
    June 2006
    2,194 Posts
    I'm really tired and have to head to bed, I'll give you some help with this tomorrow, but before I go:

    // database class.
    	  class Database {

    Those sort of comments are nothing but junk, what does "// database class" tell me that "class Database" doesn't?
    Reply With Quote Edit / Delete Linux Portugal Show Events Agree Agree x 2 (list)

  34. Post #1474
    Gold Member
    StinkyJoe's Avatar
    June 2006
    2,194 Posts
    I reworked your example. Have a look at what I've made, investigate what you can through the manual, and go ahead and ask questions about everything you don't understand.

    This is a quick example only, the code will likely be riddled with bugs and isn't the most flexible thing in the world, so don't bother copying it directly into use.

    <?php
    
    class Database {
      private $host; 
      private $username;
      private $database;
      private $pdo;
      private $connected = false;
    
      public function __construct($username, $password, $database, $host = 'localhost')
      {
          $this->host     = $host;
          $this->username = $username;
          $this->password = $password;
          $this->database = $database;
      }
    
      public function connect()
      {
        $this->pdo = new PDO( "mysql:host={$this->host};dbname={$thos->database};charset=utf-8", 
                              $this->username, $this->password );
    
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->connected = true; 
      }
    
      public function getDatabaseName()
      {
        return $this->database;
      }
    
      public function isConnected()
      {
        return $this->connected;
      } 
    
      public function find($model, $limit = null, array $conditions = [])
      {
        $query = "SELECT * FROM `$model`";
    
        if($conditions)
        {
          $values = [];
          $conditionPairs = [];
          foreach($conditions as $cond => $value)
          {
            $conditionPairs[] = "{$cond}?"
            $values[] = $value;
          }
    
          $query .= " WHERE " . join(' AND ', $conditionPairs);
        }
    
        // $limit can be an array or a number, if it's an array, it's turned into 
        // LIMIT x,y
        if($limit)
          $query .= " LIMIT " . is_array($limit) ? join(", ", $limit) : $limit;
    
        $handle = $pdo->prepare($query);
        if(!$handle->execute($values ?: null))
        {
          // something failed, handle it
          // this WILL throw an exception
        }
    
        // If we have a class available with the same name as
        // the model, use it, otherwise, use a stdClass
        if(class_exists($model, true))
        {
          $handle->setFetchMode(PDO::FETCH_CLASS, $model);
          return $handle->fetchAll();
        }
    
        return $handle->fetchAll(PDO::FETCH_OBJ); // stdClass
      }
    }
    
    // Note: ideally the constructor would only take a "database" argument
    // and the "connect" method would take the "username", "host", and "password"
    // arguments. This reinforces the idea that the same database may exist
    // in different environments.
    $db = new Database('username', 'password', 'database', 'host');
    $db->connect();
    
    // This is completely unecessary, just a demonstration:
    if(!$db->isConnected())
      throw new RuntimeException('boo');
    
    // Select 10 products
    $stickers = $db->query('stickers', 10); 
    foreach($stickers as $sticker)
    {
      echo $sticker->name;
      echo $sticker->category;
    }
    
    // Select 1 product with id 5
    $sticker = $db->query('stickers', 1, [ 'id=' => 5]);
    echo $sticker->name;
    echo $sticker->category;
    
    // Select all products between 20 and 50 where "quantity" is above 6 and
    // price is under or equal to 20
    $stickers = $db->query('stickers', [20, 50], ['quantity>' => 6, 'price<=' => 20]);
    // etc..
    Reply With Quote Edit / Delete Linux Portugal Show Events Programming King Programming King x 2 (list)

  35. Post #1475
    Upload Images
    kragmars102's Avatar
    April 2011
    727 Posts
    Thanks StinkyJoe i'll definitely look through the code! Quick question, what does __construct do and what is PDO.
    Reply With Quote Edit / Delete Windows 7 Australia Show Events

  36. Post #1476
    Gold Member
    jaybuz's Avatar
    May 2006
    5,516 Posts
    __construct is run when the an instance of the class is created. PDO is a database wrapper and it's pretty good.
    Reply With Quote Edit / Delete Mac United Kingdom Show Events Agree Agree x 1Friendly Friendly x 1 (list)

  37. Post #1477
    Gold Member
    Crhem van der B's Avatar
    January 2010
    1,690 Posts
    You can also just use "public function <ClassName>", it will work the same as __construct.
    Reply With Quote Edit / Delete Windows 7 United States Show Events

  38. Post #1478
    Meow :3
    Ac!dL3ak's Avatar
    July 2005
    6,045 Posts
    You can also just use "public function <ClassName>", it will work the same as __construct.
    __construct is better, in my opinion (i've never heard of that)
    Reply With Quote Edit / Delete Linux United Kingdom Show Events

  39. Post #1479
    RUBY OVERLORD
    swift and shift's Avatar
    November 2011
    2,115 Posts
    You can also just use "public function <ClassName>", it will work the same as __construct.
    no that's deprecated
    Reply With Quote Edit / Delete Australia Show Events Agree Agree x 1 (list)

  40. Post #1480
    Upload Images
    kragmars102's Avatar
    April 2011
    727 Posts
    I reworked your example. Have a look at what I've made, investigate what you can through the manual, and go ahead and ask questions about everything you don't understand.

    This is a quick example only, the code will likely be riddled with bugs and isn't the most flexible thing in the world, so don't bother copying it directly into use.
    Thanks Stinkyjoe i've created a very nice structure now, based of your snippet. There were a few things in the script that didn't work right but it gave me a clear idea what to do :)
    Reply With Quote Edit / Delete Windows 7 Australia Show Events