Value of $_GET Superglobal Not Being Passed To Processing Page - php

Ultimately I am trying to delete an admin by id. I know the id of the admins are making it to the list admins page because I am printing the admin id in the table next to each admin username and seeing the id. But when the delete admin link is clicked, the delete admin page is not receiving the id from the GET superglobal.
Why not?
Thanks,
CM
list_admins.php (contains the delete button at the bottom for deleting an admin)
<?php require_once("../../includes/initialize.php"); ?>
<?php //if (!$session->is_logged_in()) {redirect_to("login.php");} ?>
<?php confirm_logged_in(); ?>
<?php
$admin_set = User::find_all();
$message = "";
?>
<?php $layout_context = "admin"; ?>
<?php include("../layouts/admin_header.php"); ?>
<div id="main">
<div id="navigation">
<br />
« Main menu<br />
</div>
<div id="page">
<?php echo output_message($message); ?>
<h2>Manage Admins</h2>
<table style="border: 1px solid #000; color:#000;">
<tr>
<th style="text-align: left; width: 200px;">Username</th>
<th style="text-align: left; width: 200px;">User Id</th>
<th colspan="2" style="text-align: left;">Actions</th>
</tr>
<?php foreach($admin_set as $admin) : ?>
<tr>
<td><?php echo $admin->username; ?></td>
<td><?php echo $admin->id; ?></td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php endforeach ?>
</table>
<br />
Add new admin
</div>
</div>
<?php include("../layouts/footer.php"); ?>
delete_admin.php
<?php require_once("../../includes/initialize.php"); ?>
<?php if (!$session->is_logged_in()) { redirect_to("login.php"); } ?>
<?php
//$admin_set = User::find_all();//This works, var_dump shows me the users are
//being returned
//var_dump($admin_set);
$admin = User::find_by_id($_GET['id']);//This returns database query failed.
var_dump($admin);
?>
user.php
<?php
// If it's going to need the database, then it's
// probably smart to require it before we start.
require_once(LIB_PATH.DS.'database.php');
class User extends DatabaseObject {
protected static $table_name="admins";
protected static $db_fields = array('id', 'username', 'password', 'first_name', 'last_name');
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
public function full_name() {
if(isset($this->first_name) && isset($this->last_name)) {
return $this->first_name . " " . $this->last_name;
} else {
return "";
}
}
public static function authenticate($username="", $password="") {
global $database;
$username = $database->escape_value($username);
$password = $database->escape_value($password);
$sql = "SELECT * FROM users ";
$sql .= "WHERE username = '{$username}' ";
$sql .= "AND password = '{$password}' ";
$sql .= "LIMIT 1";
$result_array = self::find_by_sql($sql);
return !empty($result_array) ? array_shift($result_array) : false;
}
// Common Database Methods
public static function find_all() {
return self::find_by_sql("SELECT * FROM ".self::$table_name);
}
public static function find_by_id($id=0) {
$result_array = self::find_by_sql("SELECT * FROM ".self::$table_name." WHERE id={$id} LIMIT 1");
return !empty($result_array) ? array_shift($result_array) : false;
}
public static function find_by_sql($sql="") {
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = self::instantiate($row);
}
return $object_array;
}
public static function count_all() {
global $database;
$sql = "SELECT COUNT(*) FROM ".self::$table_name;
$result_set = $database->query($sql);
$row = $database->fetch_array($result_set);
return array_shift($row);
}
private static function instantiate($record) {
// Could check that $record exists and is an array
$object = new self;
// Simple, long-form approach:
// $object->id = $record['id'];
// $object->username = $record['username'];
// $object->password = $record['password'];
// $object->first_name = $record['first_name'];
// $object->last_name = $record['last_name'];
// More dynamic, short-form approach:
foreach($record as $attribute=>$value){
if($object->has_attribute($attribute)) {
$object->$attribute = $value;
}
}
return $object;
}
private function has_attribute($attribute) {
// We don't care about the value, we just want to know if the key exists
// Will return true or false
return array_key_exists($attribute, $this->attributes());
}
protected function attributes() {
// return an array of attribute names and their values
$attributes = array();
foreach(self::$db_fields as $field) {
if(property_exists($this, $field)) {
$attributes[$field] = $this->$field;
}
}
return $attributes;
}
protected function sanitized_attributes() {
global $database;
$clean_attributes = array();
// sanitize the values before submitting
// Note: does not alter the actual value of each attribute
foreach($this->attributes() as $key => $value){
$clean_attributes[$key] = $database->escape_value($value);
}
return $clean_attributes;
}
public function save() {
// A new record won't have an id yet.
return isset($this->id) ? $this->update() : $this->create();
}
public function create() {
global $database;
// Don't forget your SQL syntax and good habits:
// - INSERT INTO table (key, key) VALUES ('value', 'value')
// - single-quotes around all values
// - escape all values to prevent SQL injection
$attributes = $this->sanitized_attributes();
$sql = "INSERT INTO ".self::$table_name." (";
$sql .= join(", ", array_keys($attributes));
$sql .= ") VALUES ('";
$sql .= join("', '", array_values($attributes));
$sql .= "')";
if($database->query($sql)) {
$this->id = $database->insert_id();
return true;
} else {
return false;
}
}
public function update() {
global $database;
// Don't forget your SQL syntax and good habits:
// - UPDATE table SET key='value', key='value' WHERE condition
// - single-quotes around all values
// - escape all values to prevent SQL injection
$attributes = $this->sanitized_attributes();
$attribute_pairs = array();
foreach($attributes as $key => $value) {
$attribute_pairs[] = "{$key}='{$value}'";
}
$sql = "UPDATE ".self::$table_name." SET ";
$sql .= join(", ", $attribute_pairs);
$sql .= " WHERE id=". $database->escape_value($this->id);
$database->query($sql);
return ($database->affected_rows() == 1) ? true : false;
}
public function delete() {
global $database;
// Don't forget your SQL syntax and good habits:
// - DELETE FROM table WHERE condition LIMIT 1
// - escape all values to prevent SQL injection
// - use LIMIT 1
$sql = "DELETE FROM ".self::$table_name;
$sql .= " WHERE id=". $database->escape_value($this->id);
$sql .= " LIMIT 1";
$database->query($sql);
return ($database->affected_rows() == 1) ? true : false;
// NB: After deleting, the instance of User still
// exists, even though the database entry does not.
// This can be useful, as in:
// echo $user->first_name . " was deleted";
// but, for example, we can't call $user->update()
// after calling $user->delete().
}
}
?>
database.php
<?php
require_once(LIB_PATH.DS."config.php");
class MySQLDatabase{
private $connection;
function __construct(){
$this->open_connection();
}
public function open_connection(){
$this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS,DB_NAME);
if(mysqli_connect_errno()) {
die("Database connections failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
}
public function close_connection(){
if(isset($this->connection)){
mysqli_close($this->connection);
unset($this->connection);
}
}
public function query($sql){
$result = mysqli_query($this->connection, $sql);
$this->confirm_query($result);
return $result;
}
private function confirm_query($result_set) {
if (!$result_set) {
die("Database query failed yo.");
}
}
public function escape_value($string) {
$escaped_string = mysqli_real_escape_string($this->connection, $string);
return $escaped_string;
}
//database neutral functions
public function fetch_array($result_set){
return mysqli_fetch_array($result_set);
}
public function num_rows($result_set){
return mysqli_num_rows($result_set);
}
public function insert_id(){
return mysqli_insert_id($this->connection);
}
public function affected_rows(){
return mysqli_affected_rows($this->connection);
}
}//End class MySQLDatabase
$database = new MySQLDatabase();
?>

Simple answer on this one ;)
You have:
<a href="edit_admin.php?id=<?php $admin->id; ?>"> ...
<a href="delete_admin.php?id=<?php $admin->id; ?>" ...
When it should be:
<a href="edit_admin.php?id=<?php echo $admin->id; ?>">...
<a href="delete_admin.php?id=<?php echo $admin->id; ?>" ...
^^^^

Related

OOP PHP - proper way to pass $_POST values from form to database_write function

I have trouble understanding OOP...
Lets say I wanted to create a page that adds a new user to a database and wanted to work with classes.
For that scenario i'd create a form with a function.
There are forms for each CRUD functionality - renderHTMLFormAddUser() :
...
<form action="" method="POST" >;
<label>Shopname*</label><br>;
<input type="text" name="shopname" class="input_wide" required><br>;
<label>Username*</label><br>;
<input type="text" name="username" class="input_wide" required><br>;
<input type="submit" value="add" name="submit" >
...
a DataBaseConnector class:
class DataBaseConnector
{
protected $con;
public function __construct()
{
$this->con=mysqli_connect('mariaDB','root','123456','produktmuster');
}
public function getConnection()
{
return $this->con;
}
public function __destruct()
{
$this->con->close();
}
}
and a QueryDatabase class that requires the DataBaseConnector connection as a transfer parameter in its constructor:
class QueryDatabase
{
private $con;
public function __construct(DataBaseConnector $con)
{
$this->con = $con;
}
public function addUser($shopname,$username)
{
$sql = "INSERT INTO `brandportal_manager`( `Shopname`, `Username`) VALUES ($shopname,$username)";
$result = mysqli_query($this->con->connect(), $sql);
return $result;
}
To get the $_POST values in the QueryDatabase add User function, i'd need to declare variables like so:
$shopname= $_POST['shopname'];
$username= $_POST['username'];
But is there a better way to do so?
Like maybe renderHTMLFormAddUser()->'shopname'.
Im just trying to understand what is the cleanest way to code in this scenario.
Because using a function to render the forms the adduser.php would look something like this:
$createuserform=new Forms();
$createuserform->renderHTMLFormAddUser();
$shopname= $_POST['shopname']; // this is what confuses me, you'd have to look into the
$username= $_POST['username']; // renderHTMLFormAddUser() function to see the code
$db = new DataBaseConnector();
$query= new QueryDatabase();
$query->addUser($shopname,$username)
Should I just create an own page that posts the form to a page that then uses the data?
In the beginning i simply used no transfer parameters with the addUser function, and it started with declaring the $_POSTs:
$shopname= $_POST['shopname'];
$username= $_POST['username'];
$sql = "INSERT INTO `brandportal_manager`( `Shopname`, `Username`) VALUES ($shopname,$username)";
...
But I was told it was unsafe to do so - in that regard, I sanitize my data but for the sake of easier example i stripped away all the unnecessary code.
Should I take a completely different approach, just would like to know the cleanest way to add form input data into a database.
Well, there are many approaches to do this. You can also do my OOPs approach:
Make a define.php to set the constant variables & database connection variables:
define.php
define("DB_HOSTNAME", "localhost");
define("DB_USERNAME", "your_username");
define("DB_PASSWORD", "your_password");
define("DB_NAME", "your_databasename");
define("custom_variable", "custom_variable_value");
define("baseurl", "https://localhost/myproject/");
Then, make dbase.php, to create a dynamic SQL function:
You don't need to change this file. You just need to call this class. This file work as the core file of the system.
Dbase.php
<?php session_start();
date_default_timezone_set("Asia/Karachi");
require_once("define.php");
Class Dbase
{
private $Host = DB_HOSTNAME;
private $UserName = DB_USERNAME;
private $Password = DB_PASSWORD;
private $DBname = DB_NAME;
private $connDb = false;
public $LastQuery = null;
public $AffectedRows = 0;
public $InsertKey = array();
public $InsertValues = array();
public $UpdateSets = array();
public $id;
public function __construct()
{
$this->connect();
}
protected function connect()
{
$this->connDb = #mysqli_connect($this->Host, $this->UserName, $this->Password);
if (!($this->connDb)) {
die('Database Connection Failed.<br>' . mysql_error($this->connDb));
} else {
$Select = mysqli_select_db($this->connDb,$this->DBname);
if (!$Select) {
die('Database Selection Failed.<br>' . mysql_error($this->connDb));
}
}
mysqli_set_charset($this->connDb,'utf8');
}
public function close()
{
if (!mysqli_close($this->connDb)) {
die('Closing Connection Failed.<br>');
}
}
public function escape($value)
{
if (function_exists('mysql_real_escape_string')) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$value = mysql_real_escape_string($value);
} else {
if (!get_magic_quotes_gpc()) {
$value = addcslashes($value);
}
}
return $value;
}
public function query($sql)
{
$query = $sql;
$result = mysqli_query($this->connDb,$sql);
// $this->displayQuery($result);
return $result;
}
public function displayQuery($result)
{
if (!$result) {
$output = 'Database Query Failed' . mysql_error($this->connDb) . '<br>';
$output .= 'Last Query was' . $this->LastQuery;
die($output);
} else {
$this->AffectedRows = mysqli_affected_rows($this->connDb);
}
}
public function fetchAll($sql)
{
$result = $this->query($sql);
$output = array();
while ($row = mysqli_fetch_assoc($result)) {
$output[] = $row;
}
// mysql_free_result($result);
return $output;
}
public function fetchOne($sql)
{
$output = $this->fetchAll($sql);
return $output;
// return array_shift($output);
}
public function prepareInsert($array = null)
{
if (!empty($array)) {
foreach ($array as $key => $value) {
$this->InsertKey[] = $key;
$this->InsertValues[] = $this->escape($value);
}
}
}
public function insert($table = null)
{
if (!empty($table) && !empty($this->InsertKey) && !empty($this->InsertValues)) {
$sql = "insert into '{$table}' ('";
$sql .= implode("','", $this->InsertKey);
$sql .= "') values ('";
$sql .= implode("','", $this->InsertValues);
$sql .= "')";
if ($this->query($sql)) {
$this->id = $this->lastId();
return true;
}
return false;
} else {
return false;
}
}
public function prepareUpdate($array = null)
{
if (!empty($array)) {
foreach ($array as $key => $value) {
$this->UpdateSets[] = "`{$key}` = '" . $this->escape($value) . "'";
}
}
}
public function update($table = null, $id = null, $whereId)
{
if (!empty($table) && !empty($id) && !empty($this->UpdateSets)) {
$sql = "update `{$table}` set";
$sql .= implode(",", $this->UpdateSets);
// $sql.="where id='".$this->escape($id)."'";
$sql .= "where '" . $whereId . "'='" . $this->escape($id) . "'";
return $this->query($sql);
} else {
return false;
}
}
public function lastId()
{
return mysqli_insert_id($this->connDb);
}
public function TotalNumberOfRecords($sql)
{
$result = $this->query($sql);
$output = mysqli_num_rows($result);
return $output;
}
public function GetServerInfo()
{
return mysqli_get_server_info();
}
}
Create a Query.php file. This file work as your model file as in MVC.
Query.php
<?php include "Dbase.php";
Class Query extends Dbase
{
public function __construct()
{
$this->connect();
date_default_timezone_set("Asia/Karachi");
}
public function getData($idlevelOne)
{
$sql = "SELECT * FROM `table` where level_one_id=$idlevelOne ORDER BY `sorting` ASC";
$result = $this->fetchAll($sql);
return $result;
}
/*For Insert & Edit, use this fucntion*/
public function editMember($email, $phone, $address, $city, $country, $zipcode, $id)
{
$sql = "UPDATE `members` SET `email` = '" . $email . "', `phone` = '" . $phone . "', `address` = '" . $address . "'
, `city` = '" . $city . "', `country` = '" . $country . "', `zip_code` = '" . $zipcode . "'
WHERE `id` = '$id'";
$result = $this->query($sql);
return $result;
}
}
Now, you just need to call the Query class in your PHP files to get the data.
<?php
include "Query.php";
$ObjQuery = new Query();
$ObjQuery->getData(1);

I looked over it 4 times and fixed all the errors I can find. Are there a problems with my code?

I can't find what is wrong with the code. It is suppose to allow inserting of products to my SQL table, but the html won't show up in my browser. I ran a similar code and it ran, but my didn't. So I'm just a little confused.
Which problems are still remaining in my code?
<html>
<head>
<title>Create New Product</title>
</head>
<body>
<?php
if (isset($_POST["CreateSubmit"]))
{
validate_form();
} else
{
$messages = array();
show_form($messages);
}
?>
<?php
function show_form($messages)
{
//Assign post values if exist
$newproduct = "";
$productprice = "";
$productID = "";
if (isset($_POST["newproduct"]))
$newproduct = $_POST["newproduct"];
if (isset($_POST["productprice"]))
$productprice = $_POST["productprice"];
if (isset($_POST["productID"])) ;
$productID = $_POST["productID"];
echo "<p></p>";
echo "<h2> Enter New Product</h2>";
echo "<p></p>";
?>
<h5>Fill out New Product Information and click Submit to create.</h5>
<form name="createproduct" method="POST" action="InsertEcom.php">
<table border="1" width="100%" cellpadding="0">
<tr>
<td width="157">Product Name:</td>
<td><input type="text" name="newproduct" value='<?php echo $newproduct ?
>' size="30"></td>
</tr>
<tr>
<td width="157">Price:</td>
<td><input type="text" name="productprice" value=' <?php echo $productprice ?
>' size="30"></td>
</tr>
<tr>
<td width="157">Product ID:</td>
<td><input type="text" name="productID" value=' <?php echo $productID ?>'
size="30"></td>
</tr>
<tr>
<td width="157"><input type="submit" value="Submit" name="CreateSubmit">
</td>
<td> </td>
</tr>
</table>
</form>
<?php
} //End Show Form
?>
<?php
function validate_form()
{
$messages = array();
$redisplay = false;
//Assign values
$newproduct = $_POST["newproduct"];
$productprice = $_POST["productprice"];
$productID = $_POST["productID"];
$product = new ProductClass($newproduct, $productprice, $productID);
$count = countProduct($product);
//Check for products that already exist and Do insert
if ($count == 0)
{
$res = insertProduct($product);
echo "<h3>New Product Inserted!</h3> ";
} else
{
echo "<h3>A product with that ID already exist.</h3>";
}
}//End Validate Form
function countProduct($product)
{
//Connect to the database
$mysqli = connectdb();
$newproduct = $product->getNewproduct();
$productprice = $product->getProductprice();
$productID = $product->getProductID();
//Connect to the database
$mysqli = connectdb();
//Define the Query
//For Windows MYSQL String is case insentisitive
$Myquery = "SELECT count(*) AS count FROM Products WHERE productID='$productID'";
if ($result = $mysqli->query($Myquery))
{
/*Fetch the results of the query*/
while ($row = $results->fetch_assoc())
{
$count = $row["count"];
}
/*Destroy the result set and free the memory used for it */
$result->close();
}
$mysqli->close();
return $count;
}//End count Product
function insertProduct($product)
{
//Connect to the database
$mysqli = connectdb();
$newproduct = $product->getNewproduct();
$productprice = $product->getProductprice();
$productID = $product->getProductID();
//Now we can insert
$Query = "
INSERT INTO Products
(newProduct, productPrice, productID)
VALUES
('$newproduct', '$productprice', '$productID')
";
$Success = false;
if ($result = $mysqli->query($Query))
{
$Success = true;
}
$mysqli->close();
return $Success;
}//End Insert Product
function getDbparms();
{
$trimmed = file('parms/dbparms.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPPTY_LINES);
$key = array();
$vals = array();
foreach ($trimmed as $line)
{
$pairs = explode("=", $line);
$key[] = $pairs[0];
$vals[] = $pairs[1];
}//foreach
//Combine Key and Values into an array
$mypairs = array_combine($key, $vals);
//Assign values to ParametersClass
$myDbparms = new DbparmsClass($mypairs['username'], $mypairs['password'],
$mypairs['host'], $mypairs['db']);
//Display the Parameters values
return $myDbparms;
}//End getDbparms
function connectdb()
{
//Get the DBParameters
$mydbparms = getDbparms();
//Try to connectdb
$mysqli = new mysqli($mydbparms->getHost(), $mydbparms->getUsername(),
$mydbparms->getPassword(), $mydbparms->getDb());
if ($mysqli->connect_error)
{
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
return $mysqli;
}
class DbparmsClass
{
//property declaration
private $username = "";
private $password = "";
private $host = "";
private $db = "";
//constructor
public function __construct($myusername, $mypassword, $myhost, $mydb)
{
$this->username = $myusername;
$this->password = $mypassword;
$this->host = $myhost;
$this->db = $mydb;
}
//Get methods
public function getUsername()
{
return $this->username;
}
public function getPassword()
{
return $this->password;
}
public function getHost()
{
return $this->host;
}
public function getDb()
{
return $this->db;
}
//Set methods
public function setUsername($myusername)
{
$this->username = $myusername;
}
public function setPassword($mypassword)
{
$this->password = $mypassword;
}
public function setHost($myhost)
{
$this->host = $myhost;
}
public function setDb($mydb)
{
$this->db = $mydb;
}
} //End DBparms class
//Class to construct Products with getters/settes
class ProductClass
{
//property declaration
private $newproduct = "";
private $productprice = "";
private $productID = "";
//Constructor
public function __construct($newproduct, $productprice, $productID)
{
$this->newproduct = $newproduct;
$this->productprice = $productprice;
$this->productID = $productID;
}
//Get Methods
public function getNewproduct()
{
return $this->newproduct;
}
public function getProductprice()
{
return $this->productprice;
}
public function getProductID()
{
return $this->productID;
}
//Set Methods
public function setNewproduct($value)
{
$this->newproduct = $value;
}
public function setProductprice($value)
{
$this->productprice = $value;
}
public function setProductID($value)
{
$this->productID = $value;
}
}//End ProductClass
?>
</body>
</html>
The php tags need to start and end on the same line.
?>
You should make use of error reporting to debug potential issues while developing as it revealed this error immediately.
<?php error_reporting(E_ALL); ?>
<tr>
<td width="157">Product Name:</td>
<td><input type="text" name="newproduct" value='<?php echo $newproduct ?
>' size="30"></td>
</tr>
<tr>
<td width="157">Price:</td>
<td><input type="text" name="productprice" value='<?php echo $productprice ?
>' size="30"></td>
</tr>
On lines 42 and 47, you have the ?> php ending tag splitted to two lines. This is not correct, the ?> must be on the same line, without any chars in between.
On line 106, you probably have typo, because you have
if ($result = $mysqli->query($Myquery))
{
/*Fetch the results of the query*/
while ($row = $results->fetch_assoc() )
there. You store result of query to $result variable, but then you use
$results variable, so probably you want to to this: $row = $result->fetch_assoc()
And on line 136, you have: function getDbparms();. The functions in php should not have semicolon after the name, so it should be function getDbparms() instead.
When you write in PHP, I highly recommend you to use some IDE, which watches for basic errors like this.
I discovered all of the above mentioned errors by simply copypasting this code to PhpStorm IDE and then just reading errors.
<!DOCTYPE html>
<html>
<head>
<title>Create New Product</title>
</head>
<body>
<?php
if (isset($_POST["CreateSubmit"])) {
validate_form();
} else {
$messages = array();
show_form($messages);
}
function show_form($messages)
{
//Assign post values if exist
$newproduct="";
$productprice="";
$productID="";
if (isset($_POST["newproduct"])) {
$newproduct=$_POST["newproduct"];
}
if (isset($_POST["productprice"])) {
$productprice=$_POST["productprice"];
}
if (isset($_POST["productID"])) {
$productID=$_POST["productID"];
}
echo "<p></p>";
echo "<h2> Enter New Product</h2>";
echo "<p></p>";
?>
<h5>Fill out New Product Information and click Submit to create.</h5>
<form name="createproduct" method="POST" action="InsertEcom.php">
<table border="1" width="100%" cellpadding="0">
<tr>
<td width="157">Product Name:</td>
<td><input type="text" name="newproduct" value='<?php echo $newproduct ?>' size="30"></td>
</tr>
<tr>
<td width="157">Price:</td>
<td><input type="text" name="productprice" value='<?php echo $productprice ?>' size="30"></td>
</tr>
<tr>
<td width="157">Product ID:</td>
<td><input type="text" name="productID" value='<?php echo $productID ?>' size="30"></td>
</tr>
<tr>
<td width="157"><input type="submit" value="Submit" name="CreateSubmit">
</td>
<td> </td>
</tr>
</table>
</form>
<?php
} //End Show Form
function validate_form()
{
$messages = array();
$redisplay = false;
//Assign values
$newproduct = $_POST["newproduct"];
$productprice = $_POST["productprice"];
$productID = $_POST["productID"];
$product = new ProductClass($newproduct, $productprice, $productID);
$count = countProduct($product);
//Check for products that already exist and Do insert
if ($count==0) {
$res = insertProduct($product);
echo "<h3>New Product Inserted!</h3> ";
} else {
echo "<h3>A product with that ID already exist.</h3>";
}
}//End Validate Form
function countProduct($product)
{
//Connect to the database
$mysqli = connectdb();
$newproduct = $product->getNewproduct();
$productprice = $product->getProductprice();
$productID = $product->getProductID();
//Connect to the database
$mysqli = connectdb();
//Define the Query
//For Windows MYSQL String is case insentisitive
$Myquery = "SELECT count(*) as count from Products
where productID='$productID'";
if ($result = $mysqli->query($Myquery)) {
/*Fetch the results of the query*/
while ($row = $results->fetch_assoc()) {
$count=$row["count"];
}
/*Destroy the result set and free the memory used for it */
$result->close();
}
$mysqli->close();
return $count;
}//End count Product
function insertProduct($product)
{
//Connect to the database
$mysqli = connectdb();
$newproduct = $product->getNewproduct();
$productprice = $product->getProductprice();
$productID = $product->getProductID();
//Now we can insert
$Query = "INSERT INTO Products
(newProduct, productPrice, productID)
VALUES ('$newproduct', '$productprice', '$productID')";
$Success=false;
if ($result = $mysqli->query($Query)) {
$Success=true;
}
$mysqli->close();
return $Success;
}//End Insert Product
function getDbparms()
{
$trimmed = file('parms/dbparms.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPPTY_LINES);
$key = array();
$vals = array();
foreach ($trimmed as $line) {
$pairs = explode("=", $line);
$key[] = $pairs[0];
$vals[] = $pairs[1];
}//foreach
//Combine Key and Values into an array
$mypairs = array_combine($key, $vals);
//Assign values to ParametersClass
$myDbparms = new DbparmsClass($mypairs['username'], $mypairs['password'],
$mypairs['host'], $mypairs['db']);
//Display the Parameters values
return $myDbparms;
}//End getDbparms
function connectdb()
{
//Get the DBParameters
$mydbparms = getDbparms();
//Try to connectdb
$mysqli = new mysqli($mydbparms->getHost(), $mydbparms->getUsername(),
$mydbparms->getPassword(), $mydbparms->getDb());
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
return $mysqli;
}
class DbparmsClass
{
//property declaration
private $username="";
private $password="";
private $host="";
private $db="";
//constructor
public function __construct($myusername, $mypassword, $myhost, $mydb)
{
$this->username = $myusername;
$this->password = $mypassword;
$this->host = $myhost;
$this->db = $mydb;
}
//Get methods
public function getUsername()
{
return $this->username;
}
public function getPassword()
{
return $this->password;
}
public function getHost()
{
return $this->host;
}
public function getDb()
{
return $this->db;
}
//Set methods
public function setUsername($myusername)
{
$this->username = $myusername;
}
public function setPassword($mypassword)
{
$this->password = $mypassword;
}
public function setHost($myhost)
{
$this->host = $myhost;
}
public function setDb($mydb)
{
$this->db = $mydb;
}
} //End DBparms class
//Class to construct Products with getters/settes
class ProductClass
{
//property declaration
private $newproduct="";
private $productprice="";
private $productID="";
//Constructor
public function __construct($newproduct, $productprice, $productID)
{
$this->newproduct = $newproduct;
$this->productprice = $productprice;
$this->productID = $productID;
}
//Get Methods
public function getNewproduct()
{
return $this->newproduct;
}
public function getProductprice()
{
return $this->productprice;
}
public function getProductID()
{
return $this->productID;
}
//Set Methods
public function setNewproduct($value)
{
$this->newproduct = $value;
}
public function setProductprice($value)
{
$this->productprice = $value;
}
public function setProductID($value)
{
$this->productID = $value;
}
}//End ProductClass
?>
</body>
</html>

making abstract pdo class

i'm just switching from mysql_* to PDO since i read that mysql_* will be removed in the future and now i have no idea to abstract my current class for insert,update,and delete operation to PDO, maybe some one can point me out how to translate it to PDO based?
this is my connection class for handling all connection and other related function (i already making this one PDO so there is no problem with this)
<?php
require_once(folder.ds."constants.php");
class MySQLDatabase {
private $dbh;
private $host = DB_SERVER;
private $dbname = DB_NAME;
private $stmt;
public $query_terakhir;
public $error_text;
function __construct(){
$this->open_connection();
}
public function open_connection(){
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try{
$this->dbh = new PDO($dsn,DB_USER,DB_PASS,$options);
}
catch(PDOException $e) {
date_default_timezone_set('Asia/Jakarta');
$dt = time();
$waktu = strftime("%Y-%m-%d %H:%M:%S", $dt);
$log = array_shift(debug_backtrace());
file_put_contents('PDOErrors.txt',$waktu. ": " .$e->getMessage(). ": " .$log['file']. ": line " .$log['line']. "\n", FILE_APPEND);
}
}
public function query($sql){
$this->stmt = $this->dbh->prepare($sql);
}
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 fetchall(){
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function fetch(){
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
public function rowCount(){
return $this->stmt->rowCount();
}
public function lastInsertId(){
return $this->dbh->lastInsertId();
}
public function beginTransaction(){
return $this->dbh->beginTransaction();
}
public function endTransaction(){
return $this->dbh->commit();
}
public function cancelTransaction(){
return $this->dbh->rollBack();
}
public function debugDumpParams(){
return $this->stmt->debugDumpParams();
}
}
$database = new MySQLDatabase();
?>
and here is one of my class that help me to do saving(create or update), delete and others, with this class i only need to change $nama_tabel for table name, $db_fields for my table fields and public $xxxxx that match with my table fields and create, update and delete function can work perfectly...
but with pdo i just can't figure out how to make it work for create, update and delete with the same method as above....
<?php
require_once('database.php');
class staff{
public static $nama_tabel="staff";
protected static $db_fields = array('id','name','job');
public $id;
public $name;
public $job;
private function has_attribute($attribute){
$object_var = $this->attributes();
return array_key_exists($attribute,$object_var);
}
protected function attributes(){
$attributes = array();
foreach(self::$db_fields as $field){
if(property_exists($this, $field)){
$attributes[$field] = $this->$field;
}
}
return $attributes;
}
protected function sanitized_attributes(){
global $database;
$clean_attributes = array();
foreach($this->attributes() as $key => $value){
$clean_attributes[$key] = $database->escape_value($value);
}
return $clean_attributes;
}
public function create(){
global $database;
$attributes = $this->sanitized_attributes();
$sql = "INSERT INTO " .self::$nama_tabel." (" ;
$sql .= join(", ", array_keys($attributes));
$sql .=")VALUES('";
$sql .= join("', '", array_values($attributes));
$sql .= "')";
if($database->query($sql)){
$this->id_kategori = $database->insert_id();
return true;
}else{
return false;
}
}
public function update(){
global $database;
$attributes = $this->sanitized_attributes();
$attribute_pairs = array();
foreach($attributes as $key => $value){
$attribute_pairs[] = "{$key}='{$value}'";
}
$sql ="UPDATE " .self::$nama_tabel." SET ";
$sql .= join(", ", $attribute_pairs);
$sql .=" WHERE id=" . $database->escape_value($this->id);
$database->query($sql);
return($database->affected_rows() == 1) ? true : false;
}
public function delete(){
global $database;
$sql = "DELETE FROM " .self::$nama_tabel;
$sql .= " WHERE id=". $database->escape_value($this->id);
$sql .= " LIMIT 1";
$database->query($sql);
if(!empty($this->gambar)){
$target = website .ds. $this->upload_dir .ds. $this->gambar;
unlink($target);
}
return($database->affected_rows() == 1) ? true : false;
}
}
?>
updated: this is my approach for create function after tweaking from update function from GolezTrol, but not inserting the value instead it inserting name=:name and content=:content and so on
Updated:its already fixed! here is the right one
public function create(){
global $database;
$attributes = $this->attributes();
$attribute_pairs = array();
foreach($attributes as $key => $value){
$attribute_pairs[] = ":{$key}";
}
$sql = "INSERT INTO " .self::$nama_tabel." (" ;
$sql .= join(", ", array_keys($attributes));
$sql .=")VALUES(";
$sql .= join(", ", $attribute_pairs);
$sql .= ")";
$database->query($sql);
foreach($attributes as $key => $value){
$database->bind(":$key", $value);
}
if($database->execute()){
$this->id = $database->lastInsertId();
return true;
}else{
return false;
}
}
2nd update : i experiencing some weird thing in while loop operation where i doing while and inside the while i check if this field id is equal with my other table id then i will show that id name field... and it show, but stoping my while loop, so i only get 1 row while loop (it supposed to show 40 row)
$database->query($sql_tampil);
$database->execute();
while($row = $database->fetch()){
$output = "<tr>";
if(!empty($row['id']))
$output .="<td><a data-toggle=\"tooltip\" data-placement=\"top\"
title=\"Tekan untuk mengubah informasi kegiatan ini\"
href=\"ubah_cuprimer.php?cu={$row['id']}\"
>{$row['id']}</a></td>";
else
$output .="<td>-</td>";
if(!empty($row['name'])){
$y = "";
$x = $row['name'];
if(strlen($x)<=40)
$y = $x;
else
$y=substr($x,0,40) . '...';
$output .="<td><a data-toggle=\"tooltip\" data-placement=\"top\"
title=\"{$row['name']}\"
href=\"ubah_cuprimer.php?cu={$row['id']}\"
> {$y} </td>";
}else
$output .="<td>-</td>";
$wilayah_cuprimer->id = $row['wilayah'];
$sel_kategori = $wilayah_cuprimer->get_subject_by_id();
if(!empty($sel_kategori))
$output .="<td><a href=\"#\" class=\"modal1\"
data-toggle=\"tooltip\" data-placement=\"top\"
title=\"Tekan untuk mengubah kategori artikel ini\"
name={$row['id']}>{$sel_kategori['name']}</a></td>";
else
$output .="<td><a href=\"#\" class=\"modal1\"
data-toggle=\"tooltip\" data-placement=\"top\"
title=\"Tekan untuk mengubah kategori artikel ini\"
name={$row['id']}>Tidak masuk wilayah</a></td>";
if(!empty($row['content'])){
$content = html_entity_decode($row['content']);
$content = strip_tags($content);
$z = "";
$v = $content;
if(strlen($v)<=40)
$z = $v;
else
$z=substr($v,0,40) . '...';
$output .="<td><a data-toggle=\"tooltip\" data-placement=\"top\"
title=\"{$content}\"
href=\"ubah_cuprimer.php?cu={$row['id']}\"
>{$z}</a> </td>";
}else
$output .="<td>-</td>";
if(!empty($row['tanggal']))
$output .="<td>{$row['tanggal']}</td>";
else
$output .="<td>-</td>";
if(!empty($row['id']))
$output .="<td><button class=\"btn btn-default modal2\"
name=\"{$row['id']}\"
data-toggle=\"tooltip\" data-placement=\"top\"
title=\"Tekan untuk menghapus layanan ini\" ><span
class=\"glyphicon glyphicon-trash\"></span></button></td>";
else
$output .="<td>-</td>";
$output .="</tr>";
echo $output;
}
And here is my $wilayah_cuprimer->get_subject_by_id(); function
public function get_subject_by_id(){
global $database;
$sql = "SELECT * ";
$sql .= "FROM ".self::$nama_tabel;
$sql .= " WHERE id = :id" ;
$sql .= " LIMIT 1";
$database->query($sql);
$database->bind(":id",$this->id);
$database->execute();
$array = $database->fetch();
return $array;
}
Good that you make the transition to PDO. It's better to do it now, then to find out some day that you can't upgrade PHP, because it would break your application.
As far as I can tell, $database->query($sql); only prepares a statement. That is the first step, but after that you need to execute it as well. You already have the $database->execute() method for that, but you don't call it in your insert, update and delete functions.
Apart from that issue, it would even be better if you used bind parameters for the updates too, and leave escaping strings up to the database.
It's hard to test your class in its entirety, but I hope this gives you some ideas. I added comments to describe the steps.
public function update(){
global $database;
// Don't need 'clean' attributes if you bind them as parameters.
// Any conversion you want to support is better added in $database->bind,
// but you don't need, for instance, to escape strings.
$attributes = $this->attributes();
// Place holders for the parameters. `:ParamName` marks the spot.
$attribute_pairs = array();
foreach($attributes as $key => $value){
$attribute_pairs[] = "{$key}=:{$key}";
}
$sql ="UPDATE " .self::$nama_tabel." SET " .
join(", ", $attribute_pairs) .
" WHERE id = :UPDATE_ID";
$database->query($sql);
// Bind the ID to update.
$database->bind(':UPDATE_ID', $this->id);
// Bind other attributes.
foreach($attributes as $key => $value){
$database->bind(":$key", $value);
}
// Execute the statement.
$database->execute();
// Return affected rows. Note that ->execute also returns false on failure.
return($database->affected_rows() == 1) ? true : false;
}

CRUD - Error When Updating MySQL Database

I'm learning how to code php and I'm working on the CRUD. So far, I've got the Create and Delete methods working, but for the life of me, I cannot get Update to work. Am I missing something completely obvious here? Thank you in advance.
In my User class I have the following (Only related methods included here):
protected static $table_name="users";
protected static $db_fields = array('id', 'f_name');
public $id;
public $f_name;
public static function find_by_id($id=0) {
global $db;
$result_array = self::find_by_sql("SELECT * FROM ".static::$table_name." WHERE id={$id} LIMIT 1");
return !empty($result_array) ? array_shift($result_array) : false;
}
protected function attributes() {
$attributes = array();
foreach(self::$db_fields as $field) {
if(property_exists($this, $field)) {
$attributes[$field] = $this->$field;
}
}
return $attributes;
}
protected function sanitized_attributes() {
global $db;
$clean_attributes = array();
foreach($this->attributes() as $key => $value){
$clean_attributes[$key] = $db->escape_value($value);
}
return $clean_attibutes;
}
public function update() {
global $db;
$attributes = $this->attributes();
$attribute_pairs = array();
foreach($attributes as $key => $value) {
$attibute_pairs[] = "{$key}='{$value}'";
}
$sql = "UPDATE ".self::$table_name." SET ";
$sql .= join(", ", $attribute_pairs);
$sql .= " WHERE id=". $db->escape_value($this->id);
$db->query($sql);
if ($db->affected_rows() == 1) {
echo "Yes!";
} else {
echo "No!";
}
}
In my html file, I simply have:
<?php
$user = User::find_by_id(1);
$user->f_name = "UpdatedUser";
$user->update();
?>
Well for one, your query is probably failing on account of this
$sql = "UPDATE ".static::$table_name." SET ";
being invalid. Try:
$sql = "UPDATE ".self::$table_name." SET ";

Connect to MySQL database using PHP OOP concept

I'm writing a class and handful of functions to connect to the database and retrieve the information from the tables. I went through previous posts having similar titles, but most of them have written using mysql functions and I am using mysqli functions.
I want somebody who can go through this simple script and let me know where I am making my mistake.
This is my class.connect.php:
<?php
class mySQL{
var $host;
var $username;
var $password;
var $database;
public $dbc;
public function connect($set_host, $set_username, $set_password, $set_database)
{
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
$this->database = $set_database;
$this->dbc = mysqli_connect($this->host, $this->username, $this->password, $this->database) or die('Error connecting to DB');
}
public function query($sql)
{
return mysqli_query($this->dbc, $sql) or die('Error querying the Database');
}
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql));
return $array;
}
public function close()
{
return mysqli_close($this->dbc);
}
}
?>
This is my index.php:
<?php
require_once ("class.connect.php");
$connection = new mySQL();
$connection->connect('localhost', 'myDB', 'joker', 'names_list');
$myquery = "SELECT * FROM list";
$query = $connection->query($myquery);
while($array = $connection->fetch($query))
{
echo $array['first_name'] . '<br />';
echo $array['last_name'] . '<br />';
}
$connection->close();
?>
I am getting the error saying that Error querying the Database.
Few problems :-
you don't die without provide a proper mysql error (and is good practice to exit gracefully)
fetch method is only FETCH the first row
mysqli have OO method, why you still using procedural function?
The problem is either this:
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql));
return $array;
}
or this:
while($array = $connection->fetch($query))
Because you are using the result from the query to query again. Basically, you are doing:
$r = mysqli_query($this->dbc, $sql);
$array = mysqli_fetch_array(mysqli_query($this->dbc, $r));
And you are getting an error, because $r is not a query string. When it's converted to a string, it's a "1" (from your other comment).
Try changing the function to (changed name of variable so you can see the difference):
public function fetch($result)
{
return mysqli_fetch_array($result);
}
or just call the function directly.
If you don't do your own db abstraction for learning php and mysql, you can use Medoo (http://medoo.in/).
It's a free and tiny db framework, that could save a huge work and time.
Obviously an error occurs on SELECT * FROM list you can use mysqli_error to find the error:
return mysqli_query($this->dbc, $sql) or die('Error:'.mysqli_error($this->dbc));
This will display the exact error message and will help you solve your problem.
Try to check this
https://pramodjn2.wordpress.com/
$database = new db();
$query = $database->select(‘user’);
$st = $database->result($query);
print_r($st);
class db {
public $server = ‘localhost';
public $user = ‘root';
public $passwd = ‘*****';
public $db_name = ‘DATABASE NAME';
public $dbCon;
public function __construct(){
$this->dbCon = mysqli_connect($this->server, $this->user, $this->passwd, $this->db_name);
}
public function __destruct(){
mysqli_close($this->dbCon);
}
/* insert function table name, array value
$values = array(‘first_name’ => ‘pramod’,’last_name’=> ‘jain’);
*/
public function insert($table,$values)
{
$sql = “INSERT INTO $table SET “;
$c=0;
if(!empty($values)){
foreach($values as $key=>$val){
if($c==0){
$sql .= “$key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= “, $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$c++;
}
}else{
return false;
}
$this->dbCon->query($sql) or die(mysqli_error());
return mysqli_insert_id($this->dbCon);
}
/* update function table name, array value
$values = array(‘first_name’ => ‘pramod’,’last_name’=> ‘jain’);
$condition = array(‘id’ =>5,’first_name’ => ‘pramod!’);
*/
public function update($table,$values,$condition)
{
$sql=”update $table SET “;
$c=0;
if(!empty($values)){
foreach($values as $key=>$val){
if($c==0){
$sql .= “$key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= “, $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$c++;
}
}
$k=0;
if(!empty($condition)){
foreach($condition as $key=>$val){
if($k==0){
$sql .= ” WHERE $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= ” AND $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$k++;
}
}else{
return false;
}
$result = $this->dbCon->query($sql) or die(mysqli_error());
return $result;
}
/* delete function table name, array value
$where = array(‘id’ =>5,’first_name’ => ‘pramod’);
*/
public function delete($table,$where)
{
$sql = “DELETE FROM $table “;
$k=0;
if(!empty($where)){
foreach($where as $key=>$val){
if($k==0){
$sql .= ” where $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= ” AND $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$k++;
}
}else{
return false;
}
$del = $result = $this->dbCon->query($sql) or die(mysqli_error());
if($del){
return true;
}else{
return false;
}
}
/* select function
$rows = array(‘id’,’first_name’,’last_name’);
$where = array(‘id’ =>5,’first_name’ => ‘pramod!’);
$order = array(‘id’ => ‘DESC’);
$limit = array(20,10);
*/
public function select($table, $rows = ‘*’, $where = null, $order = null, $limit = null)
{
if($rows != ‘*’){
$rows = implode(“,”,$rows);
}
$sql = ‘SELECT ‘.$rows.’ FROM ‘.$table;
if($where != null){
$k=0;
foreach($where as $key=>$val){
if($k==0){
$sql .= ” where $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= ” AND $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$k++;
}
}
if($order != null){
foreach($order as $key=>$val){
$sql .= ” ORDER BY $key “.htmlentities($val, ENT_QUOTES).””;
}
}
if($limit != null){
$limit = implode(“,”,$limit);
$sql .= ” LIMIT $limit”;
}
$result = $this->dbCon->query($sql);
return $result;
}
public function query($sql){
$result = $this->dbCon->query($sql);
return $result;
}
public function result($result){
$row = $result->fetch_array();
$result->close();
return $row;
}
public function row($result){
$row = $result->fetch_row();
$result->close();
return $row;
}
public function numrow($result){
$row = $result->num_rows;
$result->close();
return $row;
}
}
The mysqli_fetch_array function in your fetch method requires two parameters which are the SQL result and the kind of array you intend to return. In my case i use MYSQLI_ASSOC.
That is it should appear like this:
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql), MYSQLI_ASSOC);
return $array;
}
**classmysql.inc.php**
<?php
class dbclass {
var $CONN;
function dbclass() { //constructor
$conn = mysql_connect(SERVER_NAME,USER_NAME,PASSWORD);
//$conn = mysql_connect(localhost,root,"","");
if(!$conn)
{ $this->error("Connection attempt failed"); }
if(!mysql_select_db(DB_NAME,$conn))
{ $this->error("Database Selection failed"); }
$this->CONN = $conn;
return true;
}
//_____________close connection____________//
function close(){
$conn = $this->CONN ;
$close = mysql_close($conn);
if(!$close){
$this->error("Close Connection Failed"); }
return true;
}
function error($text) {
$no = mysql_errno();
$msg = mysql_error();
echo "<hr><font face=verdana size=2>";
echo "<b>Custom Message :</b> $text<br><br>";
echo "<b>Error Number :</b> $no<br><br>";
echo "<b>Error Message :</b> $msg<br><br>";
echo "<hr></font>";
exit;
}
//_____________select records___________________//
function select ($sql=""){
if(empty($sql)) { return false; }
if(!eregi("^select",$sql)){
echo "Wrong Query<hr>$sql<p>";
return false; }
if(empty($this->CONN)) { return false; }
$conn = $this->CONN;
$results = #mysql_query($sql,$conn);
if((!$results) or empty($results)) { return false; }
$count = 0;
$data = array();
while ( $row = mysql_fetch_array($results)) {
$data[$count] = $row;
$count++; }
mysql_free_result($results);
return $data;
}
//________insert record__________________//
function insert ($sql=""){
if(empty($sql)) { return false; }
if(!eregi("^insert",$sql)){ return false; }
if(empty($this->CONN)){ return false; }
$conn = $this->CONN;
$results = #mysql_query($sql,$conn);
if(!$results){
$this->error("Insert Operation Failed..<hr>$sql<hr>");
return false; }
$id = mysql_insert_id();
return $id;
}
//___________edit and modify record___________________//
function edit($sql="") {
if(empty($sql)) { return false; }
if(!eregi("^update",$sql)){ return false; }
if(empty($this->CONN)){ return false; }
$conn = $this->CONN;
$results = #mysql_query($sql,$conn);
$rows = 0;
$rows = #mysql_affected_rows();
return $rows;
}
//____________generalize for all queries___________//
function sql_query($sql="") {
if(empty($sql)) { return false; }
if(empty($this->CONN)) { return false; }
$conn = $this->CONN;
$results = mysql_query($sql,$conn) or $this->error("Something wrong in query<hr>$sql<hr>");
if(!$results){
$this->error("Query went bad ! <hr>$sql<hr>");
return false; }
if(!eregi("^select",$sql)){return true; }
else {
$count = 0;
$data = array();
while ( $row = mysql_fetch_array($results))
{ $data[$count] = $row;
$count++; }
mysql_free_result($results);
return $data;
}
}
function extraqueries($sql="") {
if(empty($sql)) { return false; }
if(empty($this->CONN)) { return false; }
$conn = $this->CONN;
$results = mysql_query($sql,$conn) or $this->error("Something wrong in query<hr>$sql<hr>");
if(!$results){
$this->error("Query went bad ! <hr>$sql<hr>");
return false; }
else {
$count = 0;
$data = array();
while ( $row = mysql_fetch_array($results))
{ $data[$count] = $row;
$count++; }
mysql_free_result($results);
return $data;
}
}
}
?>
**config.inc.php**
<?php
ini_set("memory_limit","70000M");
ini_set('max_execution_time', 900);
ob_start();
session_start();
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
############################################
# Database Server
############################################
if($_SERVER['HTTP_HOST']=="localhost")
{
define("DB_NAME","DB_NAME");
define("SERVER_NAME","SERVER_NAME");
define("USER_NAME","USER_NAME");
define("PASSWORD","PASSWORD");
}
else
{
define("DB_NAME","DB_NAME");
define("SERVER_NAME","SERVER_NAME");
define("USER_NAME","USER_NAME");
define("PASSWORD","PASSWORD");
}
#############################################
# File paths
#############################################
// For the Database file path
include("system/classmysql.inc.php");
//For the inc folders
define("INC","inc/");
//For the Function File of the pages folders
define("FUNC","func/");
//For the path of the system folder
define("SYSTEM","system/");
$table_prefix = 'dep_';
################################################################
# Database Class
################################################################
$obj_db = new dbclass();
?>
**Function Page**
<?php
// IF admin is not logged in
if(!isset($_SESSION['session_id']))
{
header("location:index.php");
}
$backpage = 'page.php?type=staff&';
if(isset($_REQUEST['endbtn']) && trim($_REQUEST['endbtn']) == "Back")
{
header("location:".$backpage);
die();
}
// INSERT into database.
if(isset($_REQUEST['submit']) && trim($_REQUEST['submit']) == "Submit")
{
$pass = addslashes(trim($_REQUEST['password']));
$password = encrypt($pass, "deppro");
$username = addslashes(trim($_REQUEST['username']));
$sql = "select * from ".$table_prefix."users where `UserName` ='".$username."'";
$result = $obj_db->select($sql);
if(count($result) == 0)
{
$insert="INSERT INTO ".$table_prefix."users (`UserName`)VALUES ('".$username."')";
$sql=$obj_db->insert($insert);
$newuserid = mysql_insert_id($obj_db->CONN);
}
header("location:".$backpage."msg=send&alert=2");
die();
}
// DELETE record from database
if(isset($_REQUEST['action']) && trim($_REQUEST['action'])==3)
{
if(isset($_REQUEST['id']) && trim($_REQUEST['id']!=""))
{
$id = site_Decryption($_REQUEST['id']);
$sql_del = "Delete from ".$table_prefix."users where StaffID ='$id'";
$del = $obj_db->sql_query($sql_del);
header("location:".$backpage."msg=delete&alert=2");
die();
}
}
// UPDATE the record
$action=1;
if((isset($_REQUEST['action']) && trim($_REQUEST['action'])==2) && (!(isset($_REQUEST['submit']) && trim($_REQUEST['submit']) == "Submit")))
{
if(isset($_REQUEST['id']) && trim($_REQUEST['id']!=""))
{
$id = site_Decryption($_REQUEST['id']);
//$id = $_SESSION['depadmin_id'];
$sql = "select * from ".$table_prefix."users where StaffID ='$id'";
$result = $obj_db->select($sql);
if($result)
{
foreach($result as $row)
{
$title = stripslashes($row['StaffTitle']);
$action=2;
}
}
if(isset($_REQUEST['submit']) && trim($_REQUEST['submit']) == "Update")
{
$title = addslashes(trim($_REQUEST['title']));
$sql_upd ="UPDATE ".$table_prefix."users SET `StaffTitle` = '$title' WHERE StaffID ='$id'";
$result = $obj_db->sql_query($sql_upd);
$action=1;
header("location:".$backpage."msg=edited&alert=2");
die();
}
}
}
if(isset($_REQUEST['vid']) && trim($_REQUEST['vid']!=""))
{
$id = site_Decryption($_REQUEST['vid']);
$sql = "select * from ".$table_prefix."users where StaffID ='$id'";
$result = $obj_db->select($sql);
if($result)
{
foreach($result as $row)
{
$username = stripslashes($row['UserName']);
}
}
}
?>
<td class="center"><span class="editbutton"> </span> <span class="deletebutton"> </span> <a class="lightbox" title="View" href="cpropertyview.php?script=view&vid=<?php echo site_Encryption($sql[$j]['PropertyID']); ?>&lightbox[width]=55p&lightbox[height]=60p"><span class="viewbutton"> </span></a></td>

Categories