how to group the functions in class - function

i am new to PHP how to group functions inside a class and use it in other pages to reduce typing this is for single page what if i use multiple pages with pageination
this is my coding
<?php
include ('conn.php');
class sel
{
function sell()
{
if(isset($_POST['submit']))
{
$id=$_POST['id'];
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$result = $myDBObject -> select('*', 'admin', 'username = "'.$username.'" and
password ="'.$password.'"');
$x = $rdata['id'];
echo $x;
$_SESSION['username'] =$id;
echo $_SESSION['username'];
if(! $rdata)
{
echo "Enter your username and password correctly";
}
else
{
echo '<script type="text/javascript">
document.location="list.php";
</script>';
}
}
}
}
$myDBObject = new sel();
$myDBObject->sell();
?>
and my connection.php code is
<?php
class DBConnect
{
private $host = 'localhost';
private $user = 'root';
private $pass = '';
private $db = 'enquiry';
public function __construct(){
$conn = mysql_connect($this -> host, $this -> user, $this -> pass);
$sql = mysql_select_db($this -> db, $conn) or die(mysql_error());
}
private function select($select, $table, $where){
$sql = "select ".$select." from ".$table." where ".$where;
$result = mysql_query($sql);
return $rdata = mysql_fetch_array($result);
}
}
$myDBObject = new DBConnect();
$myDBObject->__construct();
$myDBObject->select($select, $table, $where);
?>
if i did like this i get this error what did i do wrong in code
Fatal error: Call to private method DBConnect::select() from context '' in C:\xampp\htdocs
\Raj\cform\conn.php on line 23

You can use database class as mentioned below
class DBConnect
{
private $host = 'localhost';
private $user = 'user';
private $pass = 'pass';
private $db = 'mydb';
public function __construct(){
$conn = mysql_connect($this -> host, $this -> user, $this -> pass);
$sql = mysql_select_db($this -> db, $conn) or die(mysql_error());
}
// select query
private function select($select, $table, $where){
$sql = "select ".$select." from ".$table." where ".$where;
$result = mysql_query($sql);
return $rdata = mysql_fetch_array($result);
}
// update query
private function update($update, $table, $where){
// code here
}
}
When required, create object of the class and call functions as below
require 'dbConnect.php'; // assuming, you have included the database class in this file
$myDBObject = new DBConnect();
$username = mysql_real_escape_string($_POST['username']); // mysql escaping
$password = mysql_real_escape_string($_POST['password']); // mysql escaping
// select required data
$result = $myDBObject -> select('*', 'admin', 'username = "'.$username.'" and password = "'.$password.'"');
The function described in the class above are for demonstration purpose. You can include other functions in the class along with data escaping functionality.
FYI: mysql is deprecrated. Use mysqli or PDO instead. The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

// Hi,
class ClassName {
static function funcName1(){
funcBody1;
}
static function funcName2(){
funcBody2;
}
}
// to use functions juste do :
ClasseName::funcName1();
ClasseName::funcName2();

Related

Getting SQLSTATE[HY093]: Invalid parameter number: no parameters were bound in E:\wamp64\www\social\classes\db.php on line 12 error

I'm making a social network's login page but when I login a get the error above. My db.php is (i use pdo):
<?php
class DB {
private static function connect() {
$pdo = new PDO('mysql:host=127.0.0.1;dbname=social;charset=utf8', 'danny', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
public static function query($query, $params = array()) {
$statement = self::connect()->prepare($query);
$statement->execute($params);
if (explode(' ', $query)[0] == 'SELECT') {
$data = $statement->fetchAll();
return $data;
}
}
}
?>
Called from
$user_id = DB::query('SELECT id
FROM users
WHERE email=:email')[0]['id'];
DB::query('INSERT INTO login_tokens
VALUES(\'\', :token, :user_id)',
array(':token'=>sha1($token), ':user_id'=>$user_id));
Your class has many issues. to fix them:
class DB {
protected static $pdo;
public static function connect() {
static::$pdo = new PDO('mysql:host=127.0.0.1;dbname=social;charset=utf8', 'danny', 'Dani2034');
static::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public static function query($query, $params = array()) {
$statement = self::$pdo->prepare($query);
$statement->execute($params);
return $statement;
}
}
DB::connect(); // called only once
$user_id = DB::query('SELECT id FROM users WHERE email=?', array($email))->fetchColumn();
DB::query('INSERT INTO login_tokens VALUES(null, ?, ?)', array(sha1($token), $user_id));

Mysql functions in zend 2

How to query below in zend 2
select * from states st where TRIM(LOWER(st.state_name))='noida'
Any help is appreciated.
Thanks
/* DB Adapter get and SQL object create */
$adapter = GlobalAdapterFeature::getStaticAdapter();
$sql = new \Zend\Db\Sql\Sql($adapter);
/* Select object create */
$select = new \Zend\Db\Sql\Select();
$select->from('states');
$select->where->addPredicate(
new \Zend\Db\Sql\Predicate\Expression(
'TRIM(LOWER(state_name)) = ?',
'noida'
)
);
/* Select object convert to string and execute */
$queryString = $sql->getSqlStringForSqlObject($select);
$result = $adapter->query($queryString, Adapter::QUERY_MODE_EXECUTE);
Use following:
$resultStates=$this->states->select()->where('TRIM(LOWER(st.state_name))=?','noida')
->query()
->fetchAll();
For details refer Here and Here.
In you model file just use below code here I am using module profile.
Profile/Model/Common.php
namespace Profile\Model;
use Zend\Db\Sql\Sql;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Select;
class Common
{
protected $dbConfig;
protected $adapter;
public function __construct($dbConfig)
{
$this->adapter = new Adapter($dbConfig);
}
public function getStateList()
{
$sql = "select * from states st where TRIM(LOWER(st.state_name))='noida'";
$statement = $this->adapter->query($sql);
$results = $statement->execute();
$resultSet = new ResultSet();
$resultSet->initialize($results);
$list = $resultSet->toArray();
return $list; // This will return a list of array
}
}
Profile/Controller/IndexController
namespace Profile\Controller;
use Profile\Model\Common;
class IndexController extends AbstractActionController
{
protected $dbConfig = array(
'driver' => DRIVER,
'database' => DB,
'username' => DBUSER,
'password' => DBPASS
);
public function init(){
$ssOrder = new Container(__CLASS__);
//SET OPTIONS
}
public function indexAction()
{
$plist = new Common($this->dbConfig);
$resultList = $plist->getStateList(); // This will give you state list
}
}
Good Luck

PDO 'SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

I see many have had this same message for a number of different reasons but cannot see any solutions that seem to relate to my specific situation, which on the face of it a very simple one. Yes my password etc is md5 and should be changed but I do not believe that is the issue here.
I would appreciate someone pointing out why the first single line code works and the second does not. There is only one line that meets the criteria in the table in each case.
<?php
// Include database class
include 'DBClass.php';
// Instantiate database.
$db = new DBClass();
//***********************
// This works
//***********************
$em = 'admin#infin8integr8.com';
$sid = 39;
$db->query("select ufname,ulname from users where uemail = :em and sub_id = :sb");
$db->bind(':em', $em);
$db->bind(':sb', $sid);
$row = $db->single();
echo $row['ufname'].' '.$row['ulname'].'<br>';
//***************************
// This returns the error 'SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens' in C:\wamp\www\pdo\DBClass.php on line 85
//*****************************
//Line 85 in DBClass is "return $this->stmt->execute();" in
//public function execute(){
//return $this->stmt->execute();
//}
$userid = 'f534983b255eb2820bf3ba1438ddcf65';
$password = '0bfd2660362f242169d11e33f7affe0a';
$db->query = ("select ufname,ulname from users where username = :vuid and upwd = :vpwd");
$db->bind(':vuid', $userid);
$db->bind(':vpwd', $password);
$row = $db->single();
echo $row['ufname'].' * '.$row['ulname'].'<br>';
?>
The relevant class code is:-
<?php
class DBClass{
private $host = 'localhost';
private $user = '<user>';
private $pass = '<password>';
private $dbname = 'infinint_infin8';
private $dbh;
private $error;
private $stmt;
public function __construct(){
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");
// Create a new PDO instanace
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
// Catch any errors
catch(PDOException $e){
$this->error = $e->getMessage();
}
}
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function execute(){
return $this->stmt->execute();
}
public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function single(){
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
}
?>

Delete multiple value from database

I am using this file to delete record from server
<?php
$dbhandle = mysql_connect("localhost", "admin", "admin") or die(mysql_error()) ;
$selected = mysql_select_db("dbname" ,$dbhandle) or die(mysql_error()) ;
$id=$_POST['id'];
foreach($id as $value)
{
$query = mysql_query("DELETE FROM `record` WHERE `id`=$value");
}
mysql_close($dbhandle);
?>
but i am unable to delete record from the database. query is executing without any error but it cannot delete records from table
$query = mysql_query('DELETE FROM `record` WHERE `id` IN (' . implode(',', array_map('intval', $id)) . ')');
This will work even if $id array doesn't contain integers.
class db {
private static $instance = NULL;
private function __construct() {} //Make private
private function __clone(){} //Make private
public static function db() //Get instance of DB
{
if (!self::$instance)
{
self::$instance = new PDO("mysql:host=localhost;dbname=myDB;charset=utf8",'myUsername','myPassword',array(PDO::ATTR_EMULATE_PREPARES=>false,PDO::MYSQL_ATTR_USE_BUFFERED_QUERY=>true,PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC));
}
return self::$instance;
}
}
if(count($ids)) { //Make sure you don't have an empty data set.
$qMarks = str_repeat('?,', count($ids)-1) . '?';
$sql ="DELETE FROM `record` WHERE `id` IN ({$qMarks})";
$stmt = $db::db->prepare($sql);
$stmt->execute($id);
}

PDO query failure

I have a problem with my PDO class. I just have started learning OOP and I don't really know where I made a mistake
My class code:
<?php
class admin
{
private $host = 'mysql:host=localhost;dbname=db501865';
private $username = 'root';
private $password = 'root';
private $conn;
public function connect() {
try {
$conn = new PDO($this->host, $this->username, $this->password);
} catch ( PDOException $e ) {
die( 'Connection failed: ' . $e->getMessage() );
}
return $conn;
}
public function disconnect( $conn ) {
$conn = '';
}
public function listReal()
{
$this ->connect();
$real = $conn->query('SELECT * FROM `real`');
echo '<ul>';
foreach ($real as $row)
{
echo'<li><img src="'.$row['image'].'"></li>';
}
$real -> closeCursor();
echo'</ul>';
}
}
?>
and after executing following code I have 500 error in my browser.
$db = new admin;
$db -> listReal();
Where I made a mistake?
You have to use $this->var_name for your member variables.
Also there is no need to connect if you are already connected.
class admin
{
private $host = 'mysql:host=127.0.0.1;dbname=test';
private $username = 'root';
private $password = 'local#pass';
private $conn;
public function connect() {
if($this->conn) return;
$this->conn = new PDO($this->host, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function disconnect( $conn ) {
$conn = '';
}
public function listReal()
{
$this ->connect();
$real = $this->conn->query('SELECT * FROM `real`');
echo '<ul>';
foreach ($real as $row)
{
echo'<li><img src="'.$row['user_id'].'"></li>';
}
$real -> closeCursor();
echo'</ul>';
}
}
try{
$db = new admin;
$db -> listReal();
} catch(Exception $e) {
echo 'error: '.$e->getMessage();
}