Return to Snippet

Revision: 25895
at April 13, 2010 08:53 by djstaz0ne


Initial Code
<?php
class dbCon{
	public function __construct(){
		$server = "host";
		$user = "user";
		$pass = "pass";
		$db = "db";
		mysql_connect($server, $user, $pass) or die("Error connecting to sql server: ".mysql_error());
		mysql_select_db($db);
	}
	
	function getFields($table){
		$fields = $this->selectFields("*",$table);
		return $fields;
	}
	
	function selectFields($fields,$table){
		$rs = mysql_query("SHOW columns FROM " . $table) or die ("cannot select table fields");
		$daFields = explode(",",$fields);
		$chosenFields = array();
		while($row = mysql_fetch_assoc($rs)){
			if($fields != "*"){
				$intersect = array_intersect($daFields,array($row['Field']));
				if(count($intersect) > 0)array_push($chosenFields, $row);
			}
			else array_push($chosenFields,$row);
		}
		array_unshift($chosenFields,$table);
		return $chosenFields;
	}
	
	function createUser($names,$values){
		$na = explode(",",$names);
		$va = explode(",",$values);
		$pass = "";
		for($i=0; $i<count($na); $i++){
			if($na[$i] == "password"){
				$pass = str_replace("'","",$va[$i]);
				$values = str_replace($pass,crypt($pass),$values);
			}
		}
		$sql = "INSERT INTO users (".$names.") VALUES (".$values.")";
		mysql_query($sql) or die("Error Creating User");
		return "Account Successfully Created";
	}
	
	function login($username,$password){
		$sql = "SELECT password FROM users WHERE username='".$username."'";
		$rs = mysql_query($sql);
		while($row = mysql_fetch_assoc($rs)) $cryptPass = $row['password'];
		$rs = mysql_query("SELECT users.id, users.first_name, users.last_name, users.email FROM users WHERE users.username='".$username."' AND users.password='".crypt($password, $cryptPass)."'");
		$userInfo = array();
		while($row = mysql_fetch_array($rs)){
			foreach($row as $name => $value){
				$userInfo[$name] = $value;
			}
		}
		return $userInfo;
	}
	
	function userAvailable($user){
		$rs = mysql_query("SELECT username FROM users WHERE username='$user'");
		return mysql_num_rows($rs);
	}
}
?>

Initial URL


Initial Description
A simple PHP object which connects to a mysql database, selects fields, creates users and more..

Initial Title
PHP Mysql Connection Object

Initial Tags
mysql, database, php

Initial Language
PHP