Yii Framework Forum: How to insert record with MySQL without using interactive tool? - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • This topic is locked

How to insert record with MySQL without using interactive tool? Rate Topic: -----

#1 User is offline   evetsleh 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 2
  • Joined: 28-October 09

Posted 28 October 2009 - 07:13 AM

How do you insert a record into DB table without using CRUD from the interactive tool?
I cannot insert a new record into DB even when i try to copy from the blog example....
Please help me.... I'm a newbie to yii...
0

#2 User is offline   Asgaroth 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 371
  • Joined: 17-July 09
  • Location:Bogota, Colombia

Posted 28 October 2009 - 04:01 PM

View Postevetsleh, on 28 October 2009 - 07:13 AM, said:

How do you insert a record into DB table without using CRUD from the interactive tool?
I cannot insert a new record into DB even when i try to copy from the blog example....
Please help me.... I'm a newbie to yii...



Well in a controller or even in the console you can do so easily:

for a model like:

Class A extends ActiveRecord{
    public $name
    public $lastname
}


just do something like:

$instance = new A(Array('name'=>'evet', 'lastname'=>'sleh'));
$instance->save();


or from a form:

$instance = new A($_POST['A']);
$instance->save();


that will save the record to the database.

If you dont want to use crud to generate the forms then take a look at the CHtml class documentation, its kind of a helper to generate HTML code

specifically youll need: CHtml::activeLabelEx(), CHtml::activeTextField() and stuff that begins with active...

Alex,
- Extension: Dynamic DataProvider Behavior
- Extension: XUpload - jQuery File Upload Extension
- Extension: PhpQuickProfiler - A Web Log Router that will help you profile your application
- Extension: XDateView - A Date grouped Grid View
- Extension: Foundation - An easy to use, powerful, and flexible framework for building prototypes and production code on any kind of device.



- Wiki: How to generate Yii like Documentation
- Wiki: How to re enable logging during unit testing
0

#3 User is offline   evetsleh 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 2
  • Joined: 28-October 09

Posted 28 October 2009 - 10:31 PM

View PostAsgaroth, on 28 October 2009 - 04:01 PM, said:

Well in a controller or even in the console you can do so easily:

for a model like:

Class A extends ActiveRecord{
    public $name
    public $lastname
}


just do something like:

$instance = new A(Array('name'=>'evet', 'lastname'=>'sleh'));
$instance->save();


or from a form:

$instance = new A($_POST['A']);
$instance->save();


that will save the record to the database.

If you dont want to use crud to generate the forms then take a look at the CHtml class documentation, its kind of a helper to generate HTML code

specifically youll need: CHtml::activeLabelEx(), CHtml::activeTextField() and stuff that begins with active...

Alex,


Hi Alex,
Thnks for the reply, but I still can't insert a new record in MySQL database.
I am able to view the results but no insertion of record have take place.
The following are my codes, please take a look whether if I understand you correctly.

I am creating a message form with the following fields:
  • author
  • message
  • phone number
  • cars


MessageForm.php (Message Form Model):
<?php
/*
* MessageForm Class
* Basic Model that holds our "Hello World" String
* and the rules and attributes to change that String.
*/
class MessageForm extends CFormModel
{
/**
* define public variables to manipulate model
*/
public $message;
public $author;
public $phoneNumber;
public $cars;

/**
* @return array validation rules for model attributes.
*/
public function rules()
{
return array(
	 
// author and message are required
array('author, message, phoneNumber, cars', 'required'),
);
}
}
?>



MessageController.php:
class MessageController extends CController
{

    private $_model;


	public function actionShow()
	{
// create a new instance of MessageForm model
$message=new MessageForm;
/*
* check to see if the MessageForm fields were filled in
*
* If they were, then print out the message and author
* with the show render - based on what the user inputted
*
* If not, then print out the default hellow world and
* default author with the show render.
*/

if(isset($message->message))
$this->render('show',array('message'=>$message));
else
{
$message->message = "Hello World";
$message->author = "Default Author";
$message->phoneNumber = "123456";
$message->cars= "Dropdown List";

$this->render('show',array('message'=>$message));
}
	}

        public function actionEdit()
	{
// create a new instance of MessageForm model
$message=new MessageForm;

/*Your method here*/
$messagesave = new message($_POST['MessageForm']);
$messagesave->save();


/*
* check to see if All the fileds are filled in on the form
* if so proceed to assign the values to the variables in
* the message model (author and message)
*
* If they validate (no errors) then render the show page
* with the new data values
*
* If there's errors, return to the edit form showing the
* errors
*
* Finally if the form wasn't set then we render the edit
* page so that the user can input field values.
*/


if(isset($_POST['MessageForm']))
{
$message->attributes=$_POST['MessageForm'];

//$message->save();
	if($message->validate())

        $this->render('show',array('message'=>$message)
        );
	else
	$this->render('edit', array('message'=>$message));
	}
else
$this->render('edit', array('message'=>$message));
	}



	public function actionIndex()
	{
                $this->render('index', array(
                'Users' => Users::model()->findAll(),               
                //'Products' => Product::model()->findAll(),
                //'Sms' => Sms::model()->findAll(),
                //Product Table's relationship with Brand Table is being preloaded.
                'Products' => Product::model()->with(array('brand'))->findAll(),
        ));

	}

}



message.php (This model generated from yiic shell in command prompt):
<?php

class message extends CActiveRecord
{
    public $id;
    public $author;
    public $message;
    public $phonenum;
    public $cars;


	/**
	 * The followings are the available columns in table 'message':
	 * @var integer $id
	 * @var string $author
	 * @var string $message
	 * @var integer $phonenum
	 * @var string $cars
	 */

	/**
	 * Returns the static model of the specified AR class.
	 * @return CActiveRecord the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'message';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		return array(
			array('author','length','max'=>100),
			array('message','length','max'=>100),
			array('cars','length','max'=>50),
			array('author, message, phonenum, cars', 'required'),
			array('phonenum', 'numerical', 'integerOnly'=>true),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'Id',
			'author' => 'Author',
			'message' => 'Message',
			'phonenum' => 'Phonenum',
			'cars' => 'Cars',
		);
	}
}


edit.php:
<?php $this->pageTitle=Yii::app()->name . ' - Edit Message'; ?>
<p><?php echo CHtml::link('Back', array('/message'))?> </p>
<h1>Edit Our Message</h1>
<p>
<div class="yiiForm">
<?php echo CHtml::beginForm(); ?>
<?php echo CHtml::errorSummary($message); ?>
<div class="simple">
<?php echo CHtml::activeLabel($message,'author'); ?>
<?php echo CHtml::activeTextField($message,'author'); ?>
</div>
<div class="simple">
<?php echo CHtml::activeLabel($message,'message'); ?>
<?php echo CHtml::activeTextField($message,'message'); ?>
</div>
<div class="simple">
<?php echo CHtml::activeLabel($message,'phoneNumber'); ?>
<?php echo CHtml::activeTextField($message,'phoneNumber'); ?>
</div>
<div class="simple">
<?php echo CHtml::activeLabel($message,'cars'); ?>
<?php echo CHtml::activeDropDownList($message,'cars', $htmlOptions=array("Lambo"=>Lambo, "Hyundai"=>Hyundai, "Honda"=>Honda)); ?>
</div>

<div class="action">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php echo CHtml::endForm(); ?>
</div><!-- yiiForm -->
</p>



show.php:
<?php $this->pageTitle=Yii::app()->name . ' - Show Message'; ?>
<p><?php echo CHtml::link('Back', array('/message'))?> </p>
<h1>Our Message</h1>

<p>
Author is <strong><?php echo $message->author; ?></strong>
<br />
Message is <strong><?php echo $message->message; ?></strong>
<br />
Phone Number is <strong><?php echo $message->phoneNumber; ?></strong>
<br />
Cars is <strong><?php echo $message->cars; ?></strong>

</p>


This my results page. No Errors but No insertion of record.
Posted Image

Please Advise.
0

#4 User is offline   nawi2010 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 4
  • Joined: 15-November 10

Posted 05 December 2010 - 11:02 PM

I do have the same problem, still newbie...
0

#5 User is offline   Maurizio Domba Cerin 

  • Yii - Yesss It Is !!!
  • Yii
  • Group: Yii Dev Team
  • Posts: 4,336
  • Joined: 12-October 09
  • Location:Croatia

Posted 06 December 2010 - 03:05 AM

You have too many inconsistency in your code...

As you are a Yii beginner... I would advise you to read the "Definitive Guide to Yii"... and use the Gii tool to create the basic code...

then if needed change that code step by step... checking the functionality on every change... so that you get an understanding of how all this works...
Find more about me.... btw. Do you know your WAN IP?
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • This topic is locked

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users