avoid duplicate data in php mysql in update? - php

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>

Related

why this code dosen't update the data

I can't update the data on this code . it just return to the main page without any update . and i am sure about the connection data on connection file .
and all the column in the data bas is correct
so what is the problem please
<?
include "../include/config.php";
echo "<a href='del_update.php'>Delete</a>"
?>
<div class="articleall">
<?
$id = $_REQUEST['do'];
if($_REQUEST['do'] == 'remove'){
$gid= $_GET['id'] ;
$de = mysql_query("delete from article where id='$gid'");
if($de){
echo "Delete doen";
echo '<meta http-equiv="refresh" content="2; url=del_update.php"/>';
exit ;
}
}
#############################################
if($_REQUEST['do'] == 'update'){
$gid2 = $_GET['id'];
$sel = mysql_query("select * from article where id='$gid2'");
$row2 = mysql_fetch_assoc($sel);
$id2 =$row2['id'];
$name2= $row2['name'];
$auther2= $row2['auther'];
$text2 = $row2['text'];
####################################### post
$postid = $_POST['id'];
$postname = $_POST['name'];
$postauther = $_POST['auther'];
$posttext = $_POST['text'];
if($_POST['del_update']){
if($postname ==''){
echo "it is empty";
echo '<meta http-equiv="refresh" content="2; url=del_update.php"/>';
exit ;
}
else {
$update = mysql_query("update article set
name ='$postname',
auther='$postauther'
where id ='$postid'
");
if(isset($update)){
echo "update done ";
echo '<meta http-equiv="refresh" content="2; url=del_update.php"/>';
exit ;
}
}
}
?>
<form action="del_update.php?do=update" method="post" >
title : <input type="text" class="name" name="name" value="<?=$name2; ?>"></br>
auther : <input type="text" class="name" name="auther" value="<?=$auther2;?>"></br>
date : <input type="text" class="name" name="date" value=""></br>
<input type="hidden" class="name" name="id" value=""></br>
text : <textarea value="" id="elm1" name="elm1" rows="15" cols="80" style="width: 80%">
<? echo $text2; ?>
</textarea>
<input type="submit" class="botton" value="update" name="go"><br>
</form>
<?
}
?>
<?
$query = mysql_query("select * from article order by id desc ");
while ($row = mysql_fetch_assoc($query)
){
$id = $row['id'];
$name = $row['name'];
echo "
<div class='shortarticle'>
<h3>$name ||
<a href='?do=remove&id=$id'>Delete</a>||
<a href='?do=update&id=$id'>Update</a>
</h3>
</div>
</div> ";
}
?>

Select specific duplicate database values and display the count

I've tried a million different ways, and this is probably something super simple, but I can't get it figured out.
I have a database that displays several different columns (name, age, gender, breed, player, etc.)
What I would like is to include a line that states "We have ___ number of female characters."
Here is my entire page where I want it displayed:
<!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>
<title>AUSUS --- mythical equine RPG</title>
<link rel="stylesheet" type="text/css" href="/css/evolution2.css" />
<link href='http://fonts.googleapis.com/css?family=Vollkorn:400,400italic,700,700italic|Kreon:400,700,300|La+Belle+Aurore|Stalemate|IM+Fell+English:400,400italic|Mrs+Saint+Delafield' rel='stylesheet' type='text/css'>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>Character Database</h1>
<p>
We currently have <b>
<?php
$link = mysql_connect("***", "***", "***");
mysql_select_db("tarb89_characters", $link);
$result = mysql_query("SELECT * FROM characters", $link);
$num_rows = mysql_num_rows($result);
echo "$num_rows";
?>
</b>
characters listed in the database. You may search the character database by character name or player name. Dams and sires marked with an asterisk (*) are from <b>outside</b> Ausus.<br><br>
<br><br>
<form action="searchchars.php" method="GET"/>
<input type="text" name="searchchars" />
<input type="submit" name="submit" value="Character Name Search" /><br>
</form>
<br>
<form action="searchplays.php" method="GET"/>
<input type="text" name="searchplays" />
<input type="submit" name="submit" value="Player Name Search" />
</form>
</p>
<p>
<br><br>
<?php
/// In order to use this script freely
/// you must leave the following copyright
/// information in this file:
/// Copyright 2012 www.turningturnip.co.uk
/// All rights reserved.
include("connect.php");
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * 20;
$result = mysql_query("SELECT * FROM characters ORDER BY name ASC LIMIT $start_from, 20");
$num = mysql_num_rows ($result);
if ($num > 0 ) {
$i=0;
while ($i < $num) {
$id = stripslashes(mysql_result($result,$i,"id"));
$name = stripslashes(mysql_result($result,$i,"name"));
$breed = stripslashes(mysql_result($result,$i,"breed"));
$gender = stripslashes(mysql_result($result,$i,"gender"));
$color = stripslashes(mysql_result($result,$i,"color"));
$markings = stripslashes(mysql_result($result,$i,"markings"));
$genetics = stripslashes(mysql_result($result,$i,"genetics"));
$player = stripslashes(mysql_result($result,$i,"player"));
$traits = stripslashes(mysql_result($result,$i,"traits"));
$defects = stripslashes(mysql_result($result,$i,"defects"));
$extras = stripslashes(mysql_result($result,$i,"extras"));
$profile = stripslashes(mysql_result($result,$i,"profile"));
$dam = stripslashes(mysql_result($result,$i,"dam"));
$sire = stripslashes(mysql_result($result,$i,"sire"));
$status = stripslashes(mysql_result($result,$i,"status"));
$row .= '
<h5>'.$name.'</h5>
<table width="550px" cellpadding="5" cellspacing="20" style="background: #eeeeee; border-radius: 15px; border: 1px solid #5067be;">
<tr>
<td width="50%"><p>
<b>ID Number:</b> '.$id.'<br>
<b>Breed:</b> '.$breed.'<br>
<b>Gender:</b> '.$gender.'<br>
<b>Dam: </b>'.$dam.'<br>
<b>Sire: </b>'.$sire.'<br>
<b>Status: </b>'.$status.'<br>
<b>Profile:</b> Click Here<br>
<b>Player:</b> '.$player.'</p></td>
<td width="50%"><p>
<b>Color:</b> '.$color.'<br>
<b>Genetics: </b>'.$genetics.'<br>
<b>Markings:</b> '.$markings.'<br>
<b>Traits:</b> '.$traits.'<br>
<b>Defects:</b> '.$defects.'<br>
<b>Extras:</b> '.$extras.'</p></td>
</table><br>
';
++$i; }} else { $row = '<tr><td colspan="2" align="center">Database empty.</td></tr>'; }
mysql_close();
?>
<? echo $row ?>
</p><center>
<font face="tahoma" style="font-size: 12px;">Pages:
<?php
include("connect.php");
$result = mysql_query("SELECT COUNT(name) FROM characters");
$row = mysql_fetch_row($result);
$total_records = $row[0];
$total_pages = ceil($total_records / 20);
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='index.php?page=".$i."'>".$i."</a> | ";
};
?>
</center></font>
</body>
</html>
Here is example for the same you can edit this
<?php
$cnt = 0;
$query = "select * from table";
$resulr = mysql_query($query);
while($var = mysql_fetch_array($result)){
if($var['gender']=='female'){
$cnt++;
}
}
echo "We have ".$cnt." female characters";
?>
SELECT COUNT(id) FROM characters where gender = 'female'
That will get you the count of characters which have 'female' as the value for gender. Is that what you want?

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

php OOP, full sample [closed]

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

Categories