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?
Related
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>
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>
Hi I have a page that displays all of the contents of my table. Alongisde each row of the table I also have a column containing a checkbox. When the user selects one or more rows by ticking the checkbox and pressing the submit button, I want just those rows to appear in a table on the next page (buy.php). I know it is basically a select statement per row that is selected. But I dont know how to approach this. Can anybody help? Thanks
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Shopping</title>
</head>
<body>
<form action='buy.php' method='post'>
<input type='submit' value='Submit' />
</form>
<h1>Buy</h1>
<?php // Script 12.7 - sopping.php
$db = mysql_connect('localhost', '#####', '#####');
mysql_select_db('shopping', $db);
$query = 'SELECT * FROM Items';
if ($r = mysql_query($query, $db)) {
print "<form>
<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['ID']}</td>
<td>{$row['Name']}</td>
<td>{$row['Cost']}</td>
<td><input type='checkbox' name='buy[{$row['ID']}] value='buy' /></td>
</tr>";
}
print "</table>
</form>";
} else {
print '<p style="color: blue">Error!</p>';
}
mysql_close($db); // Close the connection.
?>
</body>
</html>
EDIT: I tried the suggestion below and I did not get a table. Just the title of the page appeard:
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Confirmation</title>
</head>
<body>
<h1>Order Details</h1>
<?php // Script 12.7 - buy.php
$db = mysql_connect('localhost', '#####', '#####');
mysql_select_db('shopping', $db);
foreach($_POST['buy'] as $item) {
$query = 'SELECT * FROM Items WHERE ID = $item';
if ($r = mysql_query($query, $db)) {
print "<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['ID']}</td>
<td>{$row['Name']}</td>
<td>{$row['Cost']}</td>
</tr>";
}
print "</table>";
} else {
print '<p style="color: blue">Error!</p>';
}
}
mysql_close($db);
?>
</body>
</html>
You need to create a dynamic SQL query.
1) I suggest you change your checkbox to the following
<input type='checkbox' name='buy[]' value='{$row['ID']}' />
2) Loop through all of the buy options
<?php
foreach($_POST['buy'] as $item) {
// Append the ID (in the $item variable) to the SQL query, using WHERE `ID` = $item OR `ID` = $item and so on
}
?>
UPDATE:
<?php // Script 12.7 - buy.php
$db = mysql_connect('localhost', '#####', '#####');
mysql_select_db('shopping', $db);
$query = 'SELECT * FROM Items WHERE ';
$item_count = count($_POST['buy']);
for($i = 0; $i < $item_count; $i++) {
$itemid = (int)mysql_real_escape_string($_POST['buy'][i]); // Secures It
$query .= '`ID` = '.$itemid;
if($i +1 < $item_count) {
$query .= ' OR ';
}
}
if ($r = mysql_query($query, $db)) {
print "<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['ID']}</td>
<td>{$row['Name']}</td>
<td>{$row['Cost']}</td>
</tr>";
}
print "</table>";
mysql_close($db);
?>
// this checkbox use
//buy.php foreach($_POST['buy'] as $item) {
$query = "SELECT * FROM Items WHERE ID = $item"; //use " "
// try it if any problem please carefully look you database table // download file and try it 2file with table sql data
// https://copy.com/8ZsBAFj7LvypLJkK
// this checkbox use
<input type='checkbox' name='buy[]' value='{$row['ID']}' />
//buy.php
foreach($_POST['buy'] as $item) {
$query = "SELECT * FROM Items WHERE ID = $item";
//use " "
// try it if any problem please carefully look you database table
// download file and try it 2file with table sql data
// https://copy.com/8ZsBAFj7LvypLJkK
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
I have 3 files
1) show_createtable.html
2) do_showfielddef.php
3) do_showtble.php
1) First file is for creating a new table for a data base, it is a fom with 2 inputs, Table Name and Number of Fields. THIS WORKS FINE!
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<h1>Step 1: Name and Number</h1>
<form method="post" action="do_showfielddef.php" />
<p><strong>Table Name:</strong><br />
<input type="text" name="table_name" size="30" /></p>
<p><strong>Number of fields:</strong><br />
<input type="text" name="num_fields" size="30" /></p>
<p><input type="submit" name="submit" value="go to step2" /></p>
</form>
</body>
</html>
2) this script validates fields and createa another form to enter all the table rows.
This for also WORKS FINE!
<?php
//validate important input
if ((!$_POST[table_name]) || (!$_POST[num_fields])) {
header( "location: show_createtable.html");
exit;
}
//begin creating form for display
$form_block = "
<form action=\"do_createtable.php\" method=\"post\">
<input name=\"table_name\" type=\"hidden\" value=\"$_POST[table_name]\">
<table cellspacing=\"5\" cellpadding=\"5\">
<tr>
<th>Field Name</th><th>Field Type</th><th>Table Length</th>
</tr>";
//count from 0 until you reach the number fo fields
for ($i = 0; $i <$_POST[num_fields]; $i++) {
$form_block .="
<tr>
<td align=center><input type=\"texr\" name=\"field name[]\"
size=\"30\"></td>
<td align=center>
<select name=\"field_type[]\">
<option value=\"char\">char</option>
<option value=\"date\">date</option>
<option value=\"float\">float</option>
<option value=\"int\">int</option>
<option value=\"text\">text</option>
<option value=\"varchar\">varchar</option>
</select>
</td>
<td align=center><input type=\"text\" name=\"field_length[]\" size=\"5\">
</td>
</tr>";
}
//finish up the form
$form_block .= "
<tr>
<td align=center colspan=3><input type =\"submit\" value=\"create table\">
</td>
</tr>
</table>
</form>";
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Create a database table: Step 2</title>
</head>
<body>
<h1>defnie fields for <? echo "$_POST[table_name]"; ?>
</h1>
<? echo "$form_block"; ?>
</body>
</html>
Problem is here
3) this form creates the tables and enteres them into the database.
I am getting an error on line 37 "Parse error: syntax error, unexpected $end in /home/admin/domains/domaina.com.au/public_html/do_createtable.php on line 37"
<?
$db_name = "testDB";
$connection = #mysql_connect("localhost", "admin_user", "pass")
or die(mysql_error());
$db = #mysql_select_db($db_name, $connection)
or die(mysql_error());
$sql = "CREATE TABLE $_POST[table_name](";
for ($i = 0; $i < count($_POST[field_name]); $i++) {
$sql .= $_POST[field_name][$i]." ".$_POST[field_type][$i];
if ($_POST[field_length][$i] !="") {
$sql .=" (".$_POST[field_length][$i]."),";
} else {
$sql .=",";
}
$sql = substr($sql, 0, -1);
$sql .= ")";
$result = mysql_query($sql, $connection) or die(mysql_error());
if ($result) {
$msg = "<p>" .$_POST[table_name]." has been created!</p>";
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Create A Database Table: Step 3</title>
</head>
<body>
<h1>Adding table to <? echo "$db_name"; ?>...</h1>
<? echo "$msg"; ?>
</body>
</html>
$result = mysql_query($sql, $connection) or die(mysql_error());
if ($result) {
$msg = "<p>" .$_POST[table_name]." has been created!</p>";
}
you missing a } in your last if statement, and your for loop is missing a } too
for ($i = 0; $i < count($_POST[field_name]); $i++) {
$sql .= $_POST[field_name][$i]." ".$_POST[field_type][$i];
if ($_POST[field_length][$i] !="") {
$sql .=" (".$_POST[field_length][$i]."),";
} else {
$sql .=",";
}
}
This error message means that a control structure block isn’t closed properly. In your case the closing } of some of your control structures like the for loop or the last if are missing.
You should use proper indentation and an editor that highlights bracket pairs to have a visual aid to avoid such errors.
You must close the for expression block:
for ($i = 0; $i < count($_POST[field_name]); $i++) {
$sql .= $_POST[field_name][$i]." ".$_POST[field_type][$i];
// ...
}
Your for loop is not terminated. You are missing a }
for ($i = 0; $i < count($_POST[field_name]); $i++) {
$sql .= $_POST[field_name][$i]." ".$_POST[field_type][$i];
}
And as pointed by others there is also a missing } for the last if statement:
if ($result) {
$msg = "< p>" .$_POST[table_name]." has been created!< /p>";
}
in your php.ini (php configuration) change :
short_open_tag = Off
you opened php tag shortly at line 1
just find and replace all <? with <?php
Stylistic tip: Use HEREDOCs to assign blocks of text to a variable, instead of the hideous multi-line-with-tons-of-escaping-backslashes constructs you're using. They're far easier to read and less error prone if/when you happen to forget a \ somewhere and break the script with a parse error.
I just solved this error, after checking my code, I had no open tags/braces.
For me, I got this error when moving to a amazon server.
It turns out I needed to enable short_open_tag = On in my php.ini.
This solved this error for me.