php OOP, full sample [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
On this site I found a lot of cool examples of PHP OOP.
Maybe you know where to find complete examples?
Guest books, registration forms, blog...
When I look at the full model is much easier to understand OOP PHP.
As different classes interacting with each other, exchange data
How to use the generic class for sending data to the database
Thanks

Following is the sample code:
class.php
class Database{
/*
* Create variables for credentials to MySQL database
* The variables have been declared as private. This
* means that they will only be available with the
* Database class
*/
private $db_host = "localhost"; // Change as required
private $db_user = "root"; // Change as required
private $db_pass = ""; // Change as required
private $db_name = ""; // Change as required
/*
* Extra variables that are required by other function such as boolean con variable
*/
private $con = false; // Check to see if the connection is active
private $result = array(); // Any results from a query will be stored here
// Function to make connection to database
public function connect(){
if(!$this->con){
$myconn = #mysql_connect($this->db_host,$this->db_user,$this->db_pass); // mysql_connect() with variables defined at the start of Database class
if($myconn){
$seldb = #mysql_select_db($this->db_name,$myconn); // Credentials have been pass through mysql_connect() now select the database
if($seldb){
$this->con = true;
return true; // Connection has been made return TRUE
}else{
array_push($this->result,mysql_error());
return false; // Problem selecting database return FALSE
}
}else{
array_push($this->result,mysql_error());
return false; // Problem connecting return FALSE
}
}else{
return true; // Connection has already been made return TRUE
}
}
// Function to disconnect from the database
public function disconnect(){
// If there is a connection to the database
if($this->con){
// We have found a connection, try to close it
if(#mysql_close()){
// We have successfully closed the connection, set the connection variable to false
$this->con = false;
// Return true tjat we have closed the connection
return true;
}else{
// We could not close the connection, return false
return false;
}
}
}
public function select($sql){
$query = #mysql_query($sql);
// $this->myQuery = $sql; // Pass back the SQL
if($query){
// If the query returns >= 1 assign the number of rows to numResults
$this->numResults = mysql_num_rows($query);
// Loop through the query results by the number of rows returned
for($i = 0; $i < $this->numResults; $i++){
$r = mysql_fetch_array($query);
$key = array_keys($r);
for($x = 0; $x < count($key); $x++){
// Sanitizes keys so only alphavalues are allowed
if(!is_int($key[$x])){
if(mysql_num_rows($query) >= 1){
$this->result[$i][$key[$x]] = $r[$key[$x]];
}else{
$this->result = null;
}
}
}
}
return true; // Query was successful
}else{
array_push($this->result,mysql_error());
return false; // No rows where returned
}
}
// Function to insert into the database
public function insert($sql)
{
// Make the query to insert to the database
if($ins = #mysql_query($sql))
{
array_push($this->result,mysql_insert_id());
return true; // The data has been inserted
}
else
{
array_push($this->result,mysql_error());
return false; // The data has not been inserted
}
}
// Function to update and delete into the database
public function query($sql)
{
if($query = #mysql_query($sql)){
array_push($this->result,mysql_affected_rows());
return true;
}else{
array_push($this->result,mysql_error());
return false;
}
}
// Public function to return the data to the user
public function getResult(){
$val = $this->result;
$this->result = array();
return $val;
}
}
?>
index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example Test</title>
</head>
<body>
<?php
if(isset($_REQUEST['failure']))
{
echo "Email/Password Wrong";
}
?>
<form action="operation.php" method="post">
<label>Email:</label>
<input type="text" name="email" />
<br />
<label>Password:</label>
<input type="password" name="password" />
<br />
<input type="submit" name="cmdlogin" value="Login" />
</form>
</body>
</html>
operation.php
<?php
require_once("class.php");
$db = new Database();
$db->connect();
if(isset($_REQUEST['cmdlogin']))
{
$rs = $db->select("SELECT * FROM tbl_login where email = '".$_REQUEST['email']."' and password= '".md5($_REQUEST['password'])."'");
$res = $db->getResult();
if($res)
{
header('location: http://localhost/project/menu.php ');
}
else
{
header('location: http://localhost/project/index.php?failure');
}
}
if(isset($_REQUEST['cmdproduct_save']))
{
$rs = $db->insert("INSERT INTO `tbl_product`(`product`, `description`, `catid`) VALUES ('".$_REQUEST['product']."','".$_REQUEST['description']."',
'".$_REQUEST['drpcat']."')");
$res = $db->getResult();
header('location: http://localhost/project/product.php?saved');
}
if(isset($_REQUEST['cmdcategory_save']))
{
$filename = '';
if(isset($_FILES['catimage']['name']) && $_FILES['catimage']['name'] != '')
{
$filename = time();
$ext=substr($_FILES['catimage']['name'],strrpos($_FILES['catimage']['name'],'.'),strlen($_FILES['catimage']['name'])-1);
$filepath = $_SERVER['DOCUMENT_ROOT'].'project/image/'.$filename.$ext;
move_uploaded_file($_FILES['catimage']['tmp_name'],$filepath);
}
$rs = $db->insert("INSERT INTO `tbl_category`(`category`, `description`,`catimage`) VALUES ('".$_REQUEST['category']."','".$_REQUEST['description']."','".$filename."')");
$res = $db->getResult();
header('location: http://localhost/project/category.php?saved');
}
if(isset($_REQUEST['cmdproduct_update']))
{
$rs = $db->query("UPDATE `tbl_product` SET `product` = '".$_REQUEST['product']."', `description`= '".$_REQUEST['description']."',`catid` = '".$_REQUEST['drpcat']."' where id = ".$_REQUEST['proeditid']);
$res = $db->getResult();
header('location: http://localhost/project/product.php?updated');
}
if(isset($_REQUEST['cmdcategory_update']))
{
//print_r($_REQUEST);exit;
$rs = $db->query("UPDATE `tbl_category` SET `category`= '".$_REQUEST['category']."', `description` = '".$_REQUEST['description']."' where id =".$_REQUEST['cateditid']);
$res = $db->getResult();
//print_r($res);exit;
header('location: http://localhost/project/category.php?updated');
}
if(isset($_REQUEST['catdelete']))
{
$rs = $db->query("DELETE FROM `tbl_category` WHERE id = ".$_REQUEST['catdelete']);
$res = $db->getResult();
header('location: http://localhost/project/category.php?deleted');
}
?>
product.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example Test</title>
</head>
<body>
<?php
include("menu.php");
require_once("class.php");
$db = new Database();
$db->connect();
$db->select("select * from tbl_category");
$rs = $db->getResult();
if(isset($_REQUEST['proeditid']))
{
$db->select("select * from tbl_product where id = ".$_REQUEST['proeditid']);
$result = $db->getResult();
//print_r($result);
}
?>
<form action="operation.php" method="post">
<label>Product:</label>
<input type="text" name="product" value="<?php if(isset($result)){ echo $result[0]['product']; }?>" />
<br />
<label>Description:</label>
<input type="text" name="description" value="<?php if(isset($result)){ echo $result[0]['description']; }?>" />
<br />
<label>Category:</label>
<select name="drpcat">
<option value="0">Select Category</option>
<?php foreach($rs as $val){?>
<option value="<?php echo $val['id']; ?>"<?php if(isset($result) && $result[0]['catid'] == $val['id']){ echo 'selected="selected"';}?>><?php echo $val['category'];?></option>
<?php }?>
</select>
<br />
<?php if(isset($result)) {?>
<input type="hidden" name="proeditid" value="<?php echo $result[0]['id'];?>" />
<input type="submit" name="cmdproduct_update" value="Update" />
<?php }else {?>
<input type="submit" name="cmdproduct_save" value="Save" />
<?php }?>
</form>
<br />
<br />
<br />
<br />
<?php
$db->select("select p.*,c.category from tbl_product as p, tbl_category as c where c.id = p. catid");
$res = $db->getResult();
?>
<table border="1">
<thead>
<tr>
<th>Product</th>
<th>Description</th>
<th>Category</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
foreach($res as $output){
?>
<tr>
<td><?php echo $output['product']; ?></td>
<td><?php echo $output['description']; ?></td>
<td><?php echo $output['category']; ?></td>
<td>
<form action="operation.php" method="post" name="catedit<?php echo $output['id']; ?>">
<input type="hidden" name="proedit" value="<?php echo $output['id']; ?>" />
</form>
Edit
</td>
<td>
<form action="operation.php" method="post" name="prodelete<?php echo $output['id']; ?>">
<input type="hidden" name="prodelete" value="<?php echo $output['id']; ?>" />
</form>
Delete
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</body>
</html>
<div style="margin-bottom:30px;">
Category
Product
</div>
menu.php
<div style="margin-bottom:30px;">
Category
Product
</div>
category.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example Test</title>
</head>
<body>
<?php
require_once("class.php");
include("menu.php");
$db = new Database();
$db->connect();
if(isset($_REQUEST['cateditid']))
{
$db->select("select * from tbl_category where id = ".$_REQUEST['cateditid']);
$rs = $db->getResult();
//print_r($rs);
}
?>
<form action="operation.php" method="post" enctype="multipart/form-data">
<label>Category:</label>
<input type="text" name="category" value="<?php if(isset($rs)){ echo $rs[0]['category']; }?>" />
<br />
<label>Description:</label>
<input type="text" name="description" value="<?php if(isset($rs)){ echo $rs[0]['description']; }?>" />
<br />
<label>Category Image:</label>
<input type="file" name="catimage" />
<br />
<?php if(isset($rs)) {?>
<input type="hidden" name="cateditid" value="<?php echo $rs[0]['id'];?>" />
<input type="submit" name="cmdcategory_update" value="Update" />
<?php }else {?>
<input type="submit" name="cmdcategory_save" value="Save" />
<?php }?>
</form>
<br />
<br />
<br />
<br />
<?php
$db->select("select * from tbl_category");
$res = $db->getResult();
?>
<table border="1">
<thead>
<tr>
<th>Category</th>
<th>Description</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
foreach($res as $output){
?>
<tr>
<td><?php echo $output['category']; ?></td>
<td><?php echo $output['description']; ?></td>
<td>
<form action="operation.php" method="post" name="catedit<?php echo $output['id']; ?>">
<input type="hidden" name="catedit" value="<?php echo $output['id']; ?>" />
</form>
Edit
</td>
<td>
<form action="operation.php" method="post" name="catdelete<?php echo $output['id']; ?>">
<input type="hidden" name="catdelete" value="<?php echo $output['id']; ?>" />
</form>
Delete
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</body>
</html>

This article helped me very much to understand the basics of OOP
Object Oriented Programming in PHP
I hope it can help you

PHP object oriented solutions
http://www.amazon.com/dp/1430210117
i really enjoyed this book when i was getting rolling with php

Related

avoid duplicate data in php mysql in update?

i have this database which contains tables one for questions and the other for answers and i need to use php to update the question and answers but when i do query to select the question and answers i get four questions and four answers or one question and one answer here's my tables structure
------------------------------------------------------- ---------------------
| question | | answers |
------------------------------------------------------- ---------------------
PHP server scripts are surrounded by delimiters, which?| | <&>...</&>
| | <?php>...</?>
| | <script>..</script>
| | <?php...?>
here's my complete code
<?php include ("connection.php"); ?>
<?php
$msg = "";
if (isset($_POST['update'])) {
if (is_numeric($_POST['question_id'])) {
$question_id = mysqli_real_escape_string($link, htmlspecialchars($_POST['question_id']));
$question_text = mysqli_real_escape_string($link, htmlspecialchars($_POST['question_text']));
$test_id = mysqli_real_escape_string($link, htmlspecialchars($_POST['test_id']));
if ($question_text == "" || $test_id == "" ) {
$msg = "يرجى تعبيئة كافة الحقول";
} else {
$sql = mysqli_query($link, " UPDATE `question` SET `question_text`='".$question_text."',`test_id`= '".$test_id."'
WHERE `question_id` = '".$question_id."' ")or die(mysqli_error($link));
/* UPDATE `question` SET `question_text`='".."',`test_id`= '".."' WHERE `question_id` = */
}
} else {
echo "Error !";
}
}else {
if (isset($_GET['question_id']) && is_numeric($_GET['question_id']) && $_GET['question_id'] > 0) {
$question_id = $_GET['question_id'];
$query = mysqli_query($link, "SELECT * FROM `question` WHERE `question_id` = '".$question_id."' ")
or die(mysqli_error($link));
while ($row = mysqli_fetch_assoc($query)) {
$question_id = $row ['question_id'];
$question_text = $row ['question_text'];
$test_id = $row['test_id'];
$query2 = mysqli_query($link,"SELECT * FROM `answers` WHERE answers.question_id = '".$question_id."' ") or die(mysqli_error($link));
while($row2 = mysqli_fetch_assoc($query2)){
$answer_text = $row2 ['answer_text'];
$correct = $row2 ['correct'];
}
/*
SELECT question.question_id,question.question_text,question.test_id,test.test_name
FROM question,test
WHERE question.test_id = test.test_id
AND question.question_id= '".$question_id."'
*/
/* SELECT `answer_text`, `correct` FROM `answers` WHERE answers.question_id = 6 AND answers.correct = 1 */
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="RTL" lang="Ar">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link href="css/style.css" media="screen" rel="stylesheet" type="text/css" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="refresh" content="30">
</head>
<body>
<form method= "POST" action = "" >
<p>
<label><p>الحقل المخصص للسؤال</p></label>
<textarea name = "question_text"><?php echo $question_text ; ?> </textarea>
</p>
<p>
<label>رقم الاختبار</label>
<td><input type="text" name="test_id" value="<?php echo $test_id ; ?>" /></td>
</p>
<p>
<label>الخيار الاول</label>
<input type="text" name="" value="<?php echo $answer_text ; ?>" />
</p>
<p>
<label>الخيار الثانى</label>
<td><input type="text" name="" value="<?php echo $answer_text ; ?>" /></td>
</p>
<p>
<label>الخيار الثالث</label>
<td><input type="text" name="" value="<?php echo $answer_text ; ?>" /></td>
</p>
<p>
<label>الخيار الرابع</label>
<td><input type="text" name="" value="<?php echo $answer_text ; ?>" /></td>
</p>
<p>
<input type="submit" name="update" value="تحديث البيانات" class="button save" />
</p>
<p>
<input type="hidden" name = "question_id" value="<?php echo $_GET['question_id']; ?>" />
</p>
</form>
</body>
</html>
<?php
}
}
}
?>
Well the problem is in your while cycles. The code is not very clean, but you are printing for every question 4 times the same answer (last found in your mysql database) and not all the answers. Can you try this, I am not sure if there is not a typo because I can not run the code.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="RTL" lang="Ar">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link href="css/style.css" media="screen" rel="stylesheet" type="text/css" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="refresh" content="30">
</head>
<body>
<form method= "POST" action = "" >
<?php include ("connection.php"); ?>
<?php
$msg = "";
if (isset($_POST['update'])) {
if (is_numeric($_POST['question_id'])) {
$question_id = mysqli_real_escape_string($link, htmlspecialchars($_POST['question_id']));
$question_text = mysqli_real_escape_string($link, htmlspecialchars($_POST['question_text']));
$test_id = mysqli_real_escape_string($link, htmlspecialchars($_POST['test_id']));
if ($question_text == "" || $test_id == "" ) {
$msg = "يرجى تعبيئة كافة الحقول";
} else {
$sql = mysqli_query($link, " UPDATE `question` SET `question_text`='".$question_text."',`test_id`= '".$test_id."'
WHERE `question_id` = '".$question_id."' ")or die(mysqli_error($link));
/* UPDATE `question` SET `question_text`='".."',`test_id`= '".."' WHERE `question_id` = */
}
} else {
echo "Error !";
}
}else {
if (isset($_GET['question_id']) && is_numeric($_GET['question_id']) && $_GET['question_id'] > 0) {
$question_id = $_GET['question_id'];
$query = mysqli_query($link, "SELECT * FROM `question` WHERE `question_id` = '".$question_id."' ")
or die(mysqli_error($link));
$isFirst = TRUE;
while ($row = mysqli_fetch_assoc($query)) {
$question_id = $row ['question_id'];
$question_text = $row ['question_text'];
$test_id = $row['test_id'];
if ($isFirst) {
?>
<p>
<label>رقم الاختبار</label>
<td><input type="text" name="test_id" value="<?php echo $test_id ; ?>" /></td>
</p>
<?php
$isFirst = FALSE;
}
?>
<p>
<label><p>الحقل المخصص للسؤال</p></label>
<textarea name = "question_text"><?php echo $question_text ; ?> </textarea>
</p>
<?php
$query2 = mysqli_query($link,"SELECT * FROM `answers` WHERE answers.question_id = '".$question_id."' ") or die(mysqli_error($link));
while($row2 = mysqli_fetch_assoc($query2)){
$answer_text = $row2 ['answer_text'];
$correct = $row2 ['correct'];
/*
SELECT question.question_id,question.question_text,question.test_id,test.test_name
FROM question,test
WHERE question.test_id = test.test_id
AND question.question_id= '".$question_id."'
*/
/* SELECT `answer_text`, `correct` FROM `answers` WHERE answers.question_id = 6 AND answers.correct = 1 */
?>
<p>
<label>الخيار الاول</label>
<input type="text" name="" value="<?php echo $answer_text ; ?>" />
</p>
<?php
}
?>
<p>
<input type="submit" name="update" value="تحديث البيانات" class="button save" />
</p>
<p>
<input type="hidden" name = "question_id" value="<?php echo $_GET['question_id']; ?>" />
</p>
<?php
}
}
}
?>
</form>
</body>
</html>

Administrator tools / updating other users details

I have implemented a functioning login and registration into a website template, but i am stuck on how to update other users details within the database using a form style basis?
For example is changing what group their in for the permissions, then a mod being able to give a 24 hour time out for chat/comments to standard users and so on.
Below is a very basic what i am talking about which iv done using the existing code just a different form, and its getting the username thats entered there that needs to be the 'id' for which row is edited?
I realise my code doesnt have what's needed but if anyone could point me in the right direction id much appreciate it.
<?php
require 'core/init.php';
include 'includes/overall/header.php';
if(!$user->hasPermission('admin')) {
Redirect::to ('index.php');
}
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'username' => array(
'required' => true)
));
if($validation->passed()) {
try {
$user->update(array(
'grouptest' => Input::get('group')
));
} catch(Exception $e) {
die($e->getMessage());
}
Session::flash('home', 'Your Name has been updated succssfully!.');
Redirect::to('useraccount.php');
} else {
foreach($validate->errors() as $error) {
echo $error, '<br>';
}
}
}
}
?>
<form method="post" action="">
<label for="username">Change user:</label>
<input type="text" name="username" id="username" value=""/>
<label for="group"> to group:</label>
<select name="group" id="group">
<option value="1">Standard user</option>
<option value="2">Moderator</option>
<option value="3">Administrator</option>
</select>
<input type="submit" value="Update">
</form>
i sorted it thanks. here is the whole rewrite of the code just for this.
It is basic but made it on its own.
<?php
error_reporting(E_ALL);
require 'connect.php';
require 'security.php';
$records =array();
if(!empty($_POST)){
if(isset($_POST['username'], $_POST['perms'])){
$username = trim($_POST['username']);
$perms = trim($_POST['perms']);
if(!empty($username) && !empty($perms)){
$update = $db->query("UPDATE users2 SET perms = '$perms' WHERE username = '$username'");
if($update){
echo 'success';
header('location: updatedb.php');
die();
} else {
echo 'failed';
}
}
}
}
if($results = $db->query("SELECT * FROM users2")){
if($results->num_rows){
while($row = $results->fetch_object()){
$records[] = $row;
}
$results->free();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>updatedb</title>
</head>
<div id="nav">
<ul>
<li>Add to DB Form</li>
<li>Give Admin to Admin</li>
<li>Update DB Form</li>
<li>Delete from DB form</li>
</ul>
</div>
<body>
<h3>update database</h3>
<?php
if(!count($records)){
echo 'no records';
}else{
?>
<table>
<thead>
<tr>
<th>Username</th>
<th>Permission level</th>
</tr>
</thead>
<tbody>
<?php
foreach ($records as $r){
?>
<tr>
<td><?php echo escape($r->username); ?></td>
<td><?php echo escape($r->perms); ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
?>
<hr>
<form method="post" action="">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value=""/>
<label for="perms">Role:</label>
<select name="perms" id="perms">
<option value="1">Standard user</option>
<option value="2">Moderator</option>
<option value="3">Administrator</option>
</select>
<input type="submit" value="Update">
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
</form>
</body>
</html>

Delete Query won't work on the first row using MySQL & PHP

When I was trying to delete first row of this table, it won't delete, rather it shows me error that kindly put details in text box which I have used while Adding New Category.
IMAGE : https://dl.dropboxusercontent.com/u/88831139/1.jpg
Except Row 1, query works on each row. If I click delete for ID 2, 3 or 4, all works fine, except for Row 1. It does not work with ID=1.
Kindly do suggest me what to do.
NOTE: I have used session to keep the values in variables.
I am not deleting row i just update the status of that to keep it in record here is Code :
to ADD CATEGORY :
if(isset($_POST['category']))
{ $cat = $_POST['category'];
$validate_category = "SELECT * FROM Category WHERE CategoryName ='$cat'";
$result = mysql_query($validate_category);
$count = mysql_num_rows($result);
if(empty($cat))
{
session_start();
$msg = 'kindly Put Details completely';
$_SESSION['status'] = $msg;
$_SESSION['color'] = 'red';
header("location:../category.php");
}
else if($count==1)
{
session_start();
$msg = 'Category Already Exist !!! Kindly Choose any Other Category';
$_SESSION['status'] = $msg;
$_SESSION['color'] = 'red';
header("location:../category.php");
}
else{
$query = "INSERT INTO Category(CategoryName) values ('$cat')";
mysql_query($query);
session_start();
$msg = 'New Category has been Created';
$_SESSION['status'] = $msg;
$_SESSION['color'] = 'green';
header("location:../category.php");
}}
CODE TO DELETE ROW :
$delete_id = mysql_real_escape_string($_POST["delete_id"]);
$del_cat = mysql_result(mysql_query("SELECT CategoryName FROM Category WHERE ID = ".$delete_id), 0); // 1 = row
mysql_query("UPDATE Category SET hidden = '1' WHERE ID =".$delete_id);
session_start();
$msg = "'$del_cat' Category has been Deleted";
$_SESSION['status'] = $msg;
$_SESSION['color'] = 'green';
header("location:../category.php");
HOME PAGE :
<?php
session_start();
if(!isset($_SESSION['UserEmail']))
{
header("location:../login.php");
}
else if($_SESSION['UserRole'] != 'Admin')
{
header("location:../login.php");
}
include "../_inc/config.php";
?>
<html>
<head>
<title>Add Category</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<?php include "_lib/menu.php"; ?>
<h2>Add Category</h2>
<form action="_lib/AddCategory.php" method="POST">
Category : <input type='text' name="category"/>
<input type="Submit" value="Submit" />
<?php
if (isset($_SESSION['status'])){
$msg = $_SESSION['status'];
echo $msg;
unset($_SESSION['status']);
}
?>
<table border='1'>
<tr>
<th>ID</th>
<th>Category</th>
</tr>
<?php
$query1 = "SELECT * from Category where hidden = '0'";
$result = mysql_query($query1);
$i = 1;
while($row = mysql_fetch_array($result)) : ?>
<tr>
<td> <?php echo $i; $i=$i+1; ?> </td>
<td> <?php echo $row['CategoryName']; ?> </td>
<td>
<form action="_lib/DeleteCategory.php" method="POST" >
<input type="hidden" name="delete_id" value="<?php echo $row['ID']; ?>" />
<input type="submit" value="Delete" />
</form>
</td>
</tr>
<?php endwhile; ?>
</table>
</form>
</body>
</html>

insert option in a listbox loaded from mysql

Hi guys i have made a listbox with data from a mysql database and now i want to give the user the possibility to insert an option that don't exists. Can anyone tell me how to do that? I want to create a form or another thing that allows the user to introduce a value for a new option and then it appears in listbox and forward get the value to save in mysql database.
Best regards.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="keywords" content="jquery,ui,easy,easyui,web">
<meta name="description" content="easyui help you build your web page easily!">
<link rel="stylesheet" type="text/css" href="jeasyui_src/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="jeasyui_src/themes/icon.css">
<link rel="stylesheet" type="text/css" href="jeasyui_src/demo/demo.css">
<script type="text/javascript" src="jeasyui_src/jquery.min.js"></script>
<script type="text/javascript" src="jeasyui_src/jquery.easyui.min.js"></script>
</head>
<body>
<script language='Javascript' type='text/javascript'>
function edit_file()
{
$("#button_file").css("visibility" , "hidden");
$("#file_new").css("visibility" , "visible");
}
</script>
<h3>Coloque aqui a sua revisao tecnica:</h3></br>
<?php
include_once 'acess_db.php';
$query = "select * from faqs_treeview where level=1 order by category_title";
$result = mysql_query($query);
?>
<table border='0'>
<tr>
<td>
<form method="POST" name="form1" id="t1" style="visibility: visible;">
<select name="cat_1" style="visibility: visible;">
<option>Selecione a categoria</option>
<?php
while($row = mysql_fetch_array($result))
{
$id = $row["id_category"];
$name = $row["category_title"];
echo "<option value='$id'>".$name."</option>";
}
?>
</select>
<input type="submit" name="submit1" onclick="open2();">
</form>
<?php
if(isset($_POST["cat_1"]))
{
// echo $_POST["cat_1"];
$id2 = $_POST["cat_1"];
$query1 = "select * from faqs_treeview where high_level=$id2";
$result1 = mysql_query($query1);
$form_visible = "visible";
}
else
{
$form_visible = "hidden";
}
?>
</td>
<td>
<form method="POST" name="myform2" id="t2" style="visibility: <?= $form_visible ?>">
<select name="cat_2" >
<option>Selecione a sub-categoria</option>
<?php
while($row1 = mysql_fetch_array($result1))
{
$id = $row1["id_category"];
$name = $row1["category_title"];
echo "<option value='$id'>".$name."</option>";
}
?>
</select>
<input type="submit" name="submit2" onclick="open3();">
<input type="hidden" name="cat_1" value="<?= $_POST["cat_1"]?>">
</form>
</td>
<?php
//echo $_POST["cat_2"];
if(isset($_POST["cat_2"]) )
{
$id3 = $_POST["cat_2"];
$query2 = "select * from faqs_treeview where high_level=$id3";
$result2 = mysql_query($query2);
$form_visible = "visible";
}
else
{
$form_visible = "hidden";
}
?>
<td>
<form method="POST" name="myform3" id="t3" style="visibility: <?= $form_visible ?>">
<select name="cat_3" >
<option>Selecione a sub-sub-categoria</option>
<?php
while($row2 = mysql_fetch_array($result2))
{
$id = $row2["id_category"];
$name = $row2["category_title"];
echo "<option value='$id'>".$name."</option>";
}
?>
</select>
<input type="submit" name="submit3" onclick="closeall();">
<input type="hidden" name="cat_1" value="<?= $_POST["cat_1"]?>">
<input type="hidden" name="cat_2" value="<?= $_POST["cat_2"]?>">
</form>
</td>
</tr>
</table>
You could use AJAX for it. I see you use jQuery, so a simple get or post-request should do the trick.
Here: jQuery .get you will find some examples on how to do this. After the item has been added to the database you can use jQuery to add it to your select-box.

How to change the value of session

The app.php is getting the post value from another page. And that value used for query purposes. That post value is used to edit multiple values in app.php. I post again the multiple values to edit.php to update the records that shows in app.php. What I want is when I back into app.php using <meta http-equiv="refresh" content="0;app.php" /> or <script type="text/javascript">window.history.go(-1);</script> the value in app.php should get the new or the updated value from edit.php. I'm not good using sessions. Help please?
app.php
$mysqli = new mysqli("localhost", "root", "", "app");
ob_start();
session_start()
<form name="myform" method="post" action="edit.php"/>
if (isset($_POST['submit'])) {
//unset the session value
$_SESSION['content'] = '';
$drop = $_POST['drop_1'];
$tier_two = $_POST['tier_two'];
$where = "WHERE a.app_cn='$drop' AND a.app_plan_no='$tier_two'";
$result1 = $mysqli->query(" query ");
<table>
while ($row = $result1->fetch_assoc()) {
<td><input name="checkbox[]" type="checkbox" id="checkbox[]" value="' . $row['id'] . '"'.($row['pr'] == ""?"disabled ":"").' style="cursor:pointer;" class="checkbox"></td>
}
</table>
$sPageContent = ob_get_clean();
$_SESSION['content'] = $sPageContent;
echo $_SESSION['content'];
} else {
if (isset($_SESSION['content'])) {
echo $_SESSION['content'];
}
}
</form>
Edit.php
<?php
$mysqli = new mysqli("localhost", "root", "", "app");
if (isset($_POST['submit'])) {
$counter=$_POST['counter'];
$pr=$_POST['pr'];
$pr_qty=$_POST['pr_qty'];
$N = count($counter);
for($i=0; $i < $N; $i++)
{
$result = $mysqli->query("UPDATE purchase_request SET pr='$pr[$i]', total_quantity='$pr_qty[$i]' where counter='$counter[$i]'");
}
echo'<meta http-equiv="refresh" content="0;app.php" />';
}
?>
<form class="form-horizontal" action="" method="post">
<?php
$id=$_POST['checkbox'];
$N = count($id);
for($i=0; $i < $N; $i++)
{
$result1 = $mysqli->query("
SELECT a.item_name, a.item_description, a.counter, b.counter, b.pr, b.total_quantity
FROM app a
LEFT OUTER JOIN purchase_request b
ON a.counter=b.counter
WHERE a.counter='$id[$i]'
");
while ($row = $result1->fetch_assoc())
{ ?>
<input name="item_name[]" class="textbox" type="text" value="<?php echo $row['item_name'] ?>"/>
<input name="item_description[]" class="textbox" type="text" value="<?php echo $row['item_description'] ?>"/>
<input name="pr_qty[]" id="pr_qty[]" class="textbox tb1" type="text" value="<?php echo $row['total_quantity']; ?>" />
<input name="pr[]" class="textbox" type="text" value="<?php echo $row['pr'] ?>" />
?>
<input name="submit" type="submit" id="sbtBtn" value="Update">
</form>
using header('Location: app.php') instead of <meta http-equiv="refresh" content="0;app.php" />
if you are using javascript to return the page it may keep the previous data. It was because our browser have the cache.
You may use
<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
and
<META HTTP-EQUIV="EXPIRES" CONTENT="Mon, 22 Jul 2002 11:12:01 GMT">
to disable the cache

Categories