Jump to content

Recommended Posts

hello

 

i have a form which needs a parent id submitted but a cant get it to submit the id. all the other feilds go in fine.

 

please could someone take a look.

 

thanks ricky

 

 

 

 

<?php
require_once('../../includes/initialize.php');
if (!$session->is_logged_in()) { redirect_to("login.php"); }
?>
<?php
if(isset($_POST['submit'])) {
$cats = new cats();

$cats->name = trim($_POST['name']);

$cats->type_id = trim($_POST['type_id']);



// INPUT DATE & TIME
 $date = date('Y-m-d');
 $DT = date("Y/m/d H:i:s");
$cats->created = $DT;
$cats->modified = $DT;


if($cats->save()) {
// Success
	 $session->message("Property Category uploaded successfully.");
redirect_to('list_properties.php');
} else {
// Failure
$session->message("There was an error adding your category.");
	 redirect_to('list_properties.php');
}
}

?>
<?php include_layout_template('admin_header.php'); ?>
<div id="adminWrapper">
 <div class="adminLeft"><?php include_layout_template('admin_leftCol.php'); ?></div>
 <div class="back"><a href="index.php">« Back</a></div>

 <h2>Add Category</h2>

<?php echo output_message($message); ?>
<div id="User-form">
 <form method="POST" name="form" id="form" action="">

	 <table>

		 <tr>
		 <td>Name:</td>
		 <td><input type="text" name="name" placeholder="Enter a Category Name" class='select1css required' autofocus required/></td>
		 </tr>

		 <tr>
		 <td>Parent Property:</td>
		 <td width="315">

	    <?php
		 $propType = Prop_Types::find_all();
		 $getPropType = (isset($_GET['propType']) ? $_GET['propType'] : '');
		 echo "<select name='propType' class='select1css required'>";
	    echo "<option name='' value='' >Select a Property Type...</option>";
	    foreach($propType as $pType) {

	    echo"<option name='type_id' value='" . $pType->id . "'>" . $pType->name . "</option>";

		 }
	    echo "</select>";
		 ?>

		 </td>
		 </tr>

			 <tr>
		 <td> </td>
		 <td><input type="submit" name="submit" class="submitBTN" value="Add a Category" autofocus required/></td>
			 </tr>

	 </table>
	 </form>
 </div><!-- end id="User-form" -->
</div>
<?php include_layout_template('admin_footer.php'); ?>

Link to comment
https://forums.phpfreaks.com/topic/272106-cant-inset-parent-it-in-to-db/
Share on other sites

<option>'s within a <select> do not recognize the name attribute; only a value attribute.

 

Change:

 

echo"<option name='type_id' value='" . $pType->id . "'>" . $pType->name . "</option>";

 

To:

 

echo"<option value='" . $pType->id . "'>" . $pType->name . "</option>";

 

As well as:

 

$cats->type_id = trim($_POST['type_id']);

 

To:

 

$cats->type_id = trim($_POST['propType']);

And, just to add a side comment, I see the following in the code

// INPUT DATE & TIME
$date = date('Y-m-d');
$DT = date("Y/m/d H:i:s");
$cats->created = $DT;
$cats->modified = $DT;

 

I'm assuming you are creating those values for insertion with the record. If so, you are going about it the wrong way. You should instead create those fields in the database to automatically set those values when you insert/update records.

hi all.

 

Thanks for your replies. Its working now. THANKYOU.

 

 

REF - Psycho

 

I'm assuming you are creating those values for insertion with the record. If so, you are going about it the wrong way. You should instead create those fields in the database to automatically set those values when you insert/update records.

 

How would i do that?

is it a setting in phpmyadmin or something else ?

 

thanks

ricky

I believe Psyho is referring to the MySQL functions CURDATE() and NOW().

 

probably more using the field type timestamp set to on_update = current_timestamp()

 

Actually I meant both. I could have sworn you can use a timestamp with an autoupdate value AND a datetime with a default - but apparently not.So, what you should do, is create the date_updated field as a timestamp with the trigger to update with the current timestamp. Then you should NEVER need to touch that field it will be set automatically when the record is created and whenever the record is modified. Then create the date_created field as a date_time and in the function to create the record use the value of NOW() within the query for that field. You shouldn't need to pass the current date/time to the function to create the record

 

Here is an example of how the table structure might look like

CREATE TABLE `category` (
 `cat_id` int(11) NOT NULL auto_increment,
 `type_id` int(11) NOT NULL,
 `cat_name` varchar(25) NOT NULL,
 `date_created` datetime NOT NULL,
 `date_modified` timestamp NOT NULL default '0000-00-00 00:00:00' on update CURRENT_TIMESTAMP,
 PRIMARY KEY  (`type_id`)
)

 

Then the method/function to create the record might look like this

class cats
{
   public var $name;
   public var $type_id;

   public function save()
   {
    $query = "INPUT INTO category
				  (`type_id`, `cat_name`, `date_created`)
			  VALUES
				  ('{$this->type_id}', '{$this->name}', NOW())";
    $result = mysql_query($query);
    return ($result!=false);
   }
}

you can create a timestamp field that has a default value of current_timestamp() and not set the on update aspect of it, maybe that's what you were thinking?

 

Right, but you can only have ONE timestamp field in a table. So, you would use the timestamp field for the date_modified field. For the date_created field you would have to use a datetime type which does not allow you to set a default of CURRENT_TIMESTAMP. I don't know why this is not supported as it would seem to be a common usage.

 

So, the best solution, IMHO, is to use the timestamp with an auto-update of CURRENT_TIMESTAMP and then manually set the date_created value in the method to add records.

Edited by Psycho

Right, but you can only have ONE timestamp field in a table.

Srsly? Why??

 

Hmm, maybe I didn't state that quite right. You can have multiple timestamp fields in a table, but only ONE can use a default value or auto-update to populate the current timestamp value. Why? I have no idea. Like I said, makes perfect sense to me to support a creation date and a last modified date. But, if you try you will get an error such as this

#1293 - Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause 

Edited by Psycho

Hello. Thanks for all your help ..

 

however im having trouble getting it to work

 

my db row looks like this:

 

name: modified

type: timestamp

NULL: yes

default: CURRENT_TIMESTAMP

 

 

my class is like this: (see the full code at the end)

 

class Cats extends DatabaseObject {

protected static $table_name="prop_cats";
protected static $db_fields = array('id', 'type_id', 'name', 'created', 'NOW()');

public $id;
public $type_id;
public $name;
public $created;
public $modified;

 

 

 

 

 

 

 

 

 

<?php
// If it's going to need the database, then it's
// probably smart to require it before we start.
require_once(LIB_PATH.DS.'database.php');
class Cats extends DatabaseObject {

protected static $table_name="prop_cats";
protected static $db_fields = array('id', 'type_id', 'name', 'created', 'NOW()');

public $id;
public $type_id;
public $name;
public $created;
public $modified;
// Common Database Methods
public static function find_all() {
 return self::find_by_sql("SELECT * FROM ".self::$table_name." ORDER BY name");
 }

 public static function find_by_id($id=0) {
   $result_array = self::find_by_sql("SELECT * FROM ".self::$table_name." WHERE id={$id} ORDER BY name LIMIT 1");
 return !empty($result_array) ? array_shift($result_array) : false;

 }


 public static function find_by_parent($getPropType) {
 return self::find_by_sql("SELECT * FROM ".self::$table_name." WHERE type_id={$getPropType} ORDER BY name");
 }

 public static function find_by_sql($sql="") {
   global $database;
   $result_set = $database->query($sql);
   $object_array = array();
   while ($row = $database->fetch_array($result_set)) {
  $object_array[] = self::instantiate($row);
   }
   return $object_array;
 }
public static function count_all() {
  global $database;
  $sql = "SELECT COUNT(*) FROM ".self::$table_name;
   $result_set = $database->query($sql);
  $row = $database->fetch_array($result_set);
   return array_shift($row);
}
private static function instantiate($record) {
 // Could check that $record exists and is an array
   $object = new self;

 // More dynamic, short-form approach:
 foreach($record as $attribute=>$value){
   if($object->has_attribute($attribute)) {
  $object->$attribute = $value;
   }
 }
 return $object;
}

private function has_attribute($attribute) {
  // We don't care about the value, we just want to know if the key exists
  // Will return true or false
  return array_key_exists($attribute, $this->attributes());
}
protected function attributes() {
 // return an array of attribute names and their values
  $attributes = array();
  foreach(self::$db_fields as $field) {
 if(property_exists($this, $field)) {
   $attributes[$field] = $this->$field;
 }
  }
  return $attributes;
}

protected function sanitized_attributes() {
  global $database;
  $clean_attributes = array();
  // sanitize the values before submitting
  // Note: does not alter the actual value of each attribute
  foreach($this->attributes() as $key => $value){
 $clean_attributes[$key] = $database->escape_value($value);
  }
  return $clean_attributes;
}

public function save() {
  // A new record won't have an id yet.
  return isset($this->id) ? $this->update() : $this->create();
}

public function create() {
 global $database;
 // Don't forget your SQL syntax and good habits:
 // - INSERT INTO table (key, key) VALUES ('value', 'value')
 // - single-quotes around all values
 // - escape all values to prevent SQL injection
 $attributes = $this->sanitized_attributes();
  $sql = "INSERT INTO ".self::$table_name." (";
 $sql .= join(", ", array_keys($attributes));
  $sql .= ") VALUES ('";
 $sql .= join("', '", array_values($attributes));
 $sql .= "')";
  if($database->query($sql)) {
 $this->id = $database->insert_id();
 return true;
  } else {
 return false;
  }
}
public function update() {
  global $database;
 // Don't forget your SQL syntax and good habits:
 // - UPDATE table SET key='value', key='value' WHERE condition
 // - single-quotes around all values
 // - escape all values to prevent SQL injection
 $attributes = $this->sanitized_attributes();
 $attribute_pairs = array();
 foreach($attributes as $key => $value) {
   $attribute_pairs[] = "{$key}='{$value}'";
 }
 $sql = "UPDATE ".self::$table_name." SET ";
 $sql .= join(", ", $attribute_pairs);
 $sql .= " WHERE id=". $database->escape_value($this->id);
  $database->query($sql);
  return ($database->affected_rows() == 1) ? true : false;
}
public function delete() {
 global $database;
 // Don't forget your SQL syntax and good habits:
 // - DELETE FROM table WHERE condition LIMIT 1
 // - escape all values to prevent SQL injection
 // - use LIMIT 1
  $sql = "DELETE FROM ".self::$table_name;
  $sql .= " WHERE id=". $database->escape_value($this->id);
  $sql .= " LIMIT 1";
  $database->query($sql);
  return ($database->affected_rows() == 1) ? true : false;

}
}
?>

 

 

on the edit page i commented out some come:

 

if(isset($_POST['submit'])) {

 $findPropCats->name = trim($_POST['name']);


 /* INPUT DATE & TIME
 $date = date('Y-m-d');

 $DT = date("NOW");

 $modified = $findPropCats->modified = $DT;
*/ 

$findPropCats->update();
 if($findPropCats->update()) {
  // Success
   $session->message = "updated successfully.";
  redirect_to('list_properties.php');
 } else {
  // Failure
  $session->message = "there was an error updating";
  redirect_to('list_properties.php');
 }
}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.