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.
Related
I have been working on a form that allows entering a menu item for a cafe establishment, alongside its ingredients (arrays of data). Unfortunately, a problem came up as it only executes 1 query even though 2 or more ingredients were entered in the form (dynamic, jQuery).
Here is the PHP code:
<?php
include("session.php");
if (isset($_POST['submit'])) {
$productname = $_POST['product_name'];
$categoryID = $_POST['categoryID'];
$price = $_POST['srp'];
// ingredients
$ingredients = $_POST['ingredients'];
$qty = $_POST['qty'];
$measure = $_POST['measure'];
if (!empty($productname) && !empty($categoryID) && !empty($price) && !empty($ingredients) && !empty($qty) && !empty($measure)) {
for ($i=0; $i < count($ingredients); $i++) {
if ($ingredients[$i] != "" && $qty[$i] != "" && $measure[$i] != "") {
mysqli_query($db, "insert into individual_ingredients values ('', '$productname', '{$ingredients[$i]}', '{$qty[$i]}', '{$measure[$i]}')");
}
}
mysqli_query($db, "insert into end_products values ('', '$productname', '$price', '', '$categoryID')");
mysqli_query($db, "insert into audit_trail values ('', now(), '{$_SESSION['login_user']}', 'New end product added')");
header("location: end_products.php");
} else {
echo '<font color="red">'."Incomplete data entered".'</font>';
}
}
?>
And here is the HTML form and JQuery:
<html>
<head>
<title><?php echo $login_session; ?> | New End Product Record</title>
<link rel="stylesheet" href="css/main.css" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Bootstrap js library -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//add more fields group
$(".addMore").click(function(){
var fieldHTML = '<div class="form-group fieldGroup">'+$(".fieldGroupCopy").html()+'</div>';
$('body').find('.fieldGroup:last').after(fieldHTML);
});
//remove fields group
$("body").on("click",".remove",function(){
$(this).parents(".fieldGroup").remove();
});
});
</script>
</head>
<body>
HTML form:
<table style="margin: 5% -1% 0 -10%; font-size: 0.9em">
<tr>
<form action="new_end_product_record.php" method="post">
<td>Name</td>
<td><input type="text" name="product_name"></td>
<td>Raw Material/s Used</td>
<td>
<div class="fieldGroup">
<select name="ingredients[]">
<option value="">Ingredient</option>
<?php
$items_sql = "select name from raw_materials where status='Active'";
$get_items = mysqli_query($db, $items_sql);
while ($option = mysqli_fetch_assoc($get_items)) { ?>
<option value="<?php echo $option['name']; ?>"><?php echo $option['name']; ?></option>
<?php } ?>
</select>
<input type="text" name="qty[]" placeholder="Quantity" style="width:60px">
<select name="measure[]">
<option value="">Measure Unit</option>
<?php
$get_units = "select * from raw_material_measures";
$units = mysqli_query($db, $get_units);
while ($unit = mysqli_fetch_assoc($units)) {
?>
<option value="<?php echo $unit['full_name']; ?>"><?php echo $unit['full_name']; ?></option>
<?php } ?>
</select>
ADD
<br /><br />
</div>
<!-- second set -->
<div class="fieldGroupCopy" style="display: none;">
<div class="input-group">
<select name="ingredients[]">
<option value="">Ingredient</option>
<?php
$items_sql = "select name from raw_materials where status='Active'";
$get_items = mysqli_query($db, $items_sql);
while ($option = mysqli_fetch_assoc($get_items)) { ?>
<option value="<?php echo $option['name']; ?>"><?php echo $option['name']; ?></option>
<?php } ?>
</select>
<input type="text" name="qty[]" placeholder="Quantity" style="width:60px">
<select name="measure[]">
<option value="">Measure Unit</option>
<?php
$get_units = "select * from raw_material_measures";
$units = mysqli_query($db, $get_units);
while ($unit = mysqli_fetch_assoc($units)) {
?>
<option value="<?php echo $unit['full_name']; ?>"><?php echo $unit['full_name']; ?></option>
<?php } ?>
</select>
REMOVE
<br /><br />
</div>
</div>
</td>
</tr>
<tr>
<td>SRP</td>
<td><input type="text" name="srp"></td>
</tr>
<tr>
<td>Category</td>
<td>
<select name="categoryID">
<option value="">Select category...</option>
<!--list all categories in the database-->
<?php
$cat_query = "select category_ID, name from end_products_categories";
$get_cats = mysqli_query($db, $cat_query);
while ($option = mysqli_fetch_assoc($get_cats)) { ?>
<option value="<?php echo $option['category_ID']; ?>"><?php echo $option['name']?></option>
<?php } ?>
</select>
</td>
<!-- <td>Expiration</td>
<td><input type="date"></input></td> -->
</tr>
</table><br>
<input type="submit" class="button" name="submit" value="ADD RECORD">
<input type="reset" value="ERASE ALL">
</div></form>
</div>
</body>
</html>
Is there a problem with the loop or with the HTML form that prevents the second to the last set of values from being inserted? Any help would be appreciated.
I have a dropdown list with 5 elements (Volleyball, Handball, Rugby, Basketball, Autres)
I wish for example to select the element "Rugby" in my form, then confirm.
My problem is when I wish to change my old choice in my form (edit); the element "Rugby" is not the element which has been save previously.
By default I always have the element "VolleyBall".
[![<td>Type de Club:</td><td>
<select name="type_club" style="width:144px">
<option>Volley-Ball</option>
<option>Hand-Ball</option>
<option>Rugby</option>
<option>Basket-Ball</option>
<option>Autres</option>
</select>][1]][1]
[1]: https://i.stack.imgur.com/xQ83B.png
Here is my code.
<?php
// including the database connection file
include_once("config_bd.php");
if(isset($_POST['update']))
{
$pk_club = mysqli_real_escape_string($mysqli, $_POST['pk_club']);
$nom_club = mysqli_real_escape_string($mysqli, $_POST['nom_club']);
$type_club = mysqli_real_escape_string($mysqli, $_POST['type_club']);
// checking empty fields
if(empty($nom_club) || empty($type_club)) {
if(empty($nom_club)) {
echo "<font color='red'>Le nom du club est vide.</font><br/>";
}
if(empty($type_club)) {
echo "<font color='red'>Le type du club est vide.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE clubs SET nom_club='$nom_club',type_club='$type_club' WHERE pk_club=$pk_club");
//redirectig to the display page. In our case, it is index.php
header("Location: vue_club.php");
}
}
//getting id from url
$pk_club = $_GET['pk_club'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM clubs WHERE pk_club=$pk_club");
while($res = mysqli_fetch_array($result))
{
$nom_club = $res['nom_club'];
$type_club = $res['type_club'];
}
?>
<html>
<head>
</head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Palais des Sports</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="style/style1.css">
<body>
<div class="bandeau-bleu">
<h2>Palais des Sports</h2>
<i class="material-icons"></i>
<i class="material-icons"></i>
</div>
<div class="form_encodage">
<h3>Cliquez ici pour afficher les enregistrements</h3>
<br />
<h4> Editer un enregistrement</h4><br />
<form name="form1" method="post" action="edit_club.php">
<table border="0">
<tr>
<td>Nom du Club:</td>
<td><input type="text" name="nom_club" value="<?php echo $nom_club;?>"></td>
</tr>
<tr>
<td>Type de Club:</td><td>
<select name="type_club" style="width:144px">
<option>Volley-Ball</option>
<option>Hand-Ball</option>
<option>Rugby</option>
<option>Basket-Ball</option>
<option>Autres</option>
</select>
</td></tr>
<td><input type="submit" name="update" class="bouton_bleu" value="Update"></td>
<td><input type="hidden" name="pk_club" value=<?php echo $_GET['pk_club'];?>></td>
</tr>
</table>
</form>
</div>
</body>
</html>
You can use selected property with options.
Below is updated code for dropdown you have put thin td.
Try this:
<td>Type de Club:</td><td>
<select name="type_club" style="width:144px">
<option <?php if(isset($type_club) and $type_club=='Volley-Ball'){ echo 'selected'; }?>>Volley-Ball</option>
<option <?php if(isset($type_club) and $type_club=='Hand-Ball'){ echo 'selected'; }?>>Hand-Ball</option>
<option <?php if(isset($type_club) and $type_club=='Rugby'){ echo 'selected'; }?>>Rugby</option>
<option <?php if(isset($type_club) and $type_club=='Basket-Ball'){ echo 'selected'; }?>>Basket-Ball</option>
<option <?php if(isset($type_club) and $type_club=='Autres'){ echo 'selected'; }?>>Autres</option>
</select>
</td>
Complete updated code:
<?php
// including the database connection file
include_once("config_bd.php");
if(isset($_POST['update']))
{
$pk_club = mysqli_real_escape_string($mysqli, $_POST['pk_club']);
$nom_club = mysqli_real_escape_string($mysqli, $_POST['nom_club']);
$type_club = mysqli_real_escape_string($mysqli, $_POST['type_club']);
// checking empty fields
if(empty($nom_club) || empty($type_club)) {
if(empty($nom_club)) {
echo "<font color='red'>Le nom du club est vide.</font><br/>";
}
if(empty($type_club)) {
echo "<font color='red'>Le type du club est vide.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE clubs SET nom_club='$nom_club',type_club='$type_club' WHERE pk_club=$pk_club");
//redirectig to the display page. In our case, it is index.php
header("Location: vue_club.php");
}
}
//getting id from url
$pk_club = $_GET['pk_club'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM clubs WHERE pk_club=$pk_club");
while($res = mysqli_fetch_array($result))
{
$nom_club = $res['nom_club'];
$type_club = $res['type_club'];
}
?>
<html>
<head>
</head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Palais des Sports</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="style/style1.css">
<body>
<div class="bandeau-bleu">
<h2>Palais des Sports</h2>
<i class="material-icons"></i>
<i class="material-icons"></i>
</div>
<div class="form_encodage">
<h3>Cliquez ici pour afficher les enregistrements</h3>
<br />
<h4> Editer un enregistrement</h4><br />
<form name="form1" method="post" action="edit_club.php">
<table border="0">
<tr>
<td>Nom du Club:</td>
<td><input type="text" name="nom_club" value="<?php echo $nom_club;?>"></td>
</tr>
<tr>
<td>Type de Club:</td><td>
<select name="type_club" style="width:144px">
<option <?php if(isset($type_club) and $type_club=='Volley-Ball'){ echo 'selected'; } ?>>Volley-Ball</option>
<option <?php if(isset($type_club) and $type_club=='Hand-Ball'){ echo 'selected'; } ?>>Hand-Ball</option>
<option <?php if(isset($type_club) and $type_club=='Rugby'){ echo 'selected'; } ?>>Rugby</option>
<option <?php if(isset($type_club) and $type_club=='Basket-Ball'){ echo 'selected'; } ?>>Basket-Ball</option>
<option <?php if(isset($type_club) and $type_club=='Autres'){ echo 'selected'; }?>>Autres</option>
</select>
</td></tr>
<td><input type="submit" name="update" class="bouton_bleu" value="Update"></td>
<td><input type="hidden" name="pk_club" value=<?php echo $_GET['pk_club'];?>></td>
</tr>
</table>
</form>
</div>
</body>
</html>
You will need to query your database before loading your select form to get the previous save then build your list
$sqla= "SELECT * FROM `save_table` WHERE `id` = $id ";
$result = $conn->query($sqla);
if ($result->num_rows > 0) {
$save = $row['save'];
$select= ('<td>Type de Club:</td><td>
<select name="type_club" style="width:144px">
<option>');
$select.='$save';
$select.='</option> <option>Volley-Ball</option>
<option>Hand-Ball</option>
<option>Rugby</option>
<option>Basket-Ball</option>
<option>Autres</option>
</select>';
echo $select;
You can also use if statements to remove the second $save variable from the list before you build it so there is no repeat option in the list.
I have built a website which has lots of lists/tables (based on php). I am trying to make a Change All and Delete All system for the lists. I have already added checkbox to all individual list items. I also have one checkbox to select all those items with one click. Now I am stuck at how to execute the change and delete option. It's been 3 days...
I have done the Change All code right. But I can't figure out Delete All part.
I don't know to pass the $targetpage variable to make it redirect after that.
Here is the code:
<!DOCTYPE html>
<html>
<title>List 1</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3-theme-purple.css">
<?php include('dbcon.php');?>
<style>a {text-decoration: none;}</style>
<!--Select All-->
<script>
function checkAll(ele) {
var checkboxes = document.getElementsByTagName('input');
if (ele.checked) {
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = true;
}
}
} else {
for (var i = 0; i < checkboxes.length; i++) {
console.log(i)
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = false;
}
}
}
}
</script>
<body>
<!--?php include ('header.php');?-->
<form name="form1" enctype="multipart/form-data" action="ajaxAction.php" method="post">
<div class="w3-container">
<div class="w3-padding-32 w3-center">
<input class="w3-btn w3-green" type="submit" name="chkbox" value="Change All" />
<input class="w3-btn w3-red" type="submit" value="Delete All">
</div>
<center>
<table class="w3-table-all" style="width: auto;">
<tr class="w3-theme">
<th><input class="w3-check" type="checkbox" onchange="checkAll(this)" name="chk[]" /></th>
<th>Data</th>
</tr>
<tr>
<td>
<input class="w3-check" type="checkbox" name="chkbox[]" />
</td>
<td class="w3-small" >
The data is displayed here.
</td>
</tr>
</table>
</center>
</div>
</form>
<br>
<!--?php include ('footer.php');?-->
</body>
</html>
Here is the ajaxAction.php code:
<!--Change-->
<?php
if ($_REQUEST['chkbox']) {
$targetpage = $_REQUEST['targetpage'];
$change = array ();
$change = $_REQUEST['chkbox'];
for($c=0;$c<count($change); $c++){
$sql_all = "update `table` set `value`='123' WHERE `id` = '$change[$c]'";
mysql_query($sql_all) or die(mysql_error());
}
?>
<script>
var targetpage = "<?php echo $targetpage ?>";
location.href=targetpage+"?done";
</script>
<?php } ?>
<!--Delete-->
<?php ?>
<script>
var targetpage = "<?php echo $targetpage ?>";
location.href=targetpage+"?done";
</script>
With my current code, I am only able to use the selected array chkbox[] for one processing i.e. Change All. I don't know how to use the same array for Delete All button.
After using the trial and error method and trying for two weeks, I finally got the solution ON MY OWN and I have a serious gripe because no one from this forum cared to show me the solution.
It was simple. All I had to do was to use $_POST instead of $_REQUEST and use different names both the buttons like this:
<input class="w3-btn w3-green" type="submit" name="submit1" value="Change All">
<input class="w3-btn w3-red" type="submit" name="submit2" value="Delete All">
So, I changed ajaxAction.php to:
<?php
//Change All
if(isset($_POST['submit1'])){
if(!empty($_POST['chkbox'])){
$targetpage = $_REQUEST['targetpage'];
foreach($_POST['chkbox'] as $selected){
$sql_all = "update `table` set value='123' WHERE `id` = '$selected'";
mysql_query($sql_all) or die(mysql_error());
}
}
?>
<script>
location.href="tables.php?done";
</script>
<?php } ?>
<?php
//Delete All
if(isset($_POST['submit2'])){
if(!empty($_POST['chkbox'])){
foreach($_POST['chkbox'] as $selected){
$sql_all = "DELETE FROM `table` WHERE `id` = '$selected'";
mysql_query($sql_all) or die(mysql_error());
}
}
?>
<script>
location.href="tables.php?done";
</script>
<?php } ?>
All you had to do was tell me that I should use $_POST. No one from Stack Overflow helped me.
I have a problem here about how to search an exact value from database. Here i have my codes that are function normally but the problem is, when i search the value for example i search for "T1" and then the result show me for "T1", "T11", "T12", "T13" and some more. I just only the value that match with "T1" only be shown. Here my codes below
<?php
include_once("mysql_connect.php");
$output1 = '';
?>
<?php
if(isset($_POST['select'])) {
$selectq = $_POST['select'];
$query = mysql_query("SELECT * FROM asset_a WHERE Tag_no LIKE '%$selectq%' or
Speciality LIKE '%$selectq%' ") or die("could not search!");
$count = mysql_num_rows($query);
if($count == 0){
$output = 'There was no search results!';
}else{
while($row = mysql_fetch_array($query)) {
$tag = $row['Tag_no'];
$special = $row['Speciality'];
$output1 .= $special;
}
}
}
?>
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Testing</title>
</head>
<body>
<p>
<form name="form1" method="post" action="testq.php" >
<label for="textfield" style="font-family:'Gill Sans', 'Gill Sans MT', 'Myriad Pro',
'DejaVu Sans Condensed', Helvetica, Arial, sans-serif; font-size:20px">
Tag No:</label>
<select name="select" id="select" class="textfields" >
<option value="0">-- Select your tag no --</option>
<?php
$getallAsset_a = mysql_query("SELECT * FROM asset_a ");
while($viewallAsset_a = mysql_fetch_array($getallAsset_a)){
?>
<option id="<?php echo $viewallAsset_a ['Tag_id'];?>"><?php echo
$viewallAsset_a['Tag_no']; ?></option>
<?php } ?>
<input type="image" name="submit" id="submit" src="../Search.png"
formaction="testq.php" >
</p>
</select>
<p>
<label for="textfield">Text Field:</label>
<input type="text" name="special" id="textfield"value="<?php print ("$output1");?>" >
</p>
</form>
</body>
</html>
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