cakephp: creating new records from other controller - cakephp

I'm going to create 50 temp/dummy rows inside my model database. My problems is how can I create and save new records in my DB? Assume my model Random containts columns (id,randomValue,...).

public function addNew() {
$this->autoRender = false; // We don't render a view in this example
$moduleSize = 50;
$count = $moduleSize;
while ($count > 0) {
$random_number = rand(1000000000, 9999999999);
//check if duplicate
if ($this->checkIfDuplicateSerial($random_number)) {
//nothing to be done
} else {
$this->Random->create(array('randomValue' => $random_number));
$this->Random->save();
$this->Random->clear(); //to init new one
$count--;
}
}
$this->response->body('Inserted' . $moduleSize . 'Random Numbers');
}

Related

Create a Schema from an existing one?

I have two databases:
database A with missing indexes,constraints,foreign keys etc ...
database B with all the missing features
I have loaded the schemas of the two databases in my C# code and after comparing them I added the missing features to the first schema.
Now I want to update that schema back to SQL Server. How to do that? Could I create a schema from an existing schema?
This is what I have tried:
public static void Compare(ref DbMetaData dbSchema , ref DbMetaData dbSchema2)
{
foreach (var schemaGroup in dbSchema.SchemasDic.Values )
{
DbUserSchemaInfo schemaGroup2=dbSchema2.SchemasDic.Values.First(sc => sc.SchemaName == schemaGroup.SchemaName);
foreach (var x in schemaGroup.TablesDic)
{
var y = schemaGroup2.TablesDic.First(sc => sc.Value.TableName == x.Value.TableName);
// GET the difference in columns
var colDiff = x.Value.Columns.Except(y.Value.Columns);
// GET the difference in indexes
var indexDiff = x.Value.Indexes.Except(y.Value.Indexes);
// GET the difference in constraints
var constraintDiff = x.Value.DfConstraints.Except(y.Value.DfConstraints);
// GET the difference in Fk
var foreignKeysDiff = x.Value.ForeignKeys.Except(y.Value.ForeignKeys);
//check if a primary key exists
var primaryKeysDiff = y.Value.PrimaryKey == null ? x.Value.PrimaryKey : null;
// GET the difference in triggers
var triggersDiff = x.Value.Triggers.Except(y.Value.Triggers);
//merge the difference
if (indexDiff.Count() != 0)
{
foreach (var index in indexDiff)
{
y.Value.AddTableIndex(index.Value);
}
}
if (constraintDiff.Count() != 0)
{
foreach (var constraint in constraintDiff)
{
y.Value.AddDefaultConstraint(constraint.Value);
}
}
if (foreignKeysDiff.Count() != 0)
{
foreach (var foreignKey in foreignKeysDiff)
{
y.Value.AddFk(foreignKey.Value);
}
}
if (triggersDiff.Count() != 0)
{
foreach (var trigger in triggersDiff)
{
y.Value.AddTableTrigger(trigger.Value);
}
}
}
}
//Update DbSchema in sqlserver
}

Symfony - saving array to database

I wrote a function where I get array of marks that i need to post to my database..
My function stores it in a filed row like:
And I need to pull just one per column individually like:
Here is my api call..
public function generate(Map $seatMap)
{
$layout = $seatMap->getSeatLayout();
$seats = [];
$layoutArray = json_decode($layout, true);
$columns = range('A', 'Z');
foreach($layoutArray as $index => $result)
{
$columnLetter = $columns[$index];
$letters = str_split($result);
$letterIndex = 1;
foreach($letters as $letterIndex => $letter) {
switch($letter) {
case 'e':
$seats[] = $columnLetter . $letterIndex;
$letterIndex++;
}
}
}
foreach($seats as $seat => $result) {
$result = new Seat();
$result->setName(json_encode($seats));
$this->em->persist($result);
$this->em->flush();
}
}
Any suggestions?
I think that problem is in the part where I need to store it to database..
If I understand you correctly, your issue is here:
foreach($seats as $seat => $result) {
$result = new Seat();
$result->setName(json_encode($seats));
$this->em->persist($result);
$this->em->flush();
}
}
You're indeed creating new Seat instance for every seat, but in this line:
$result->setName(json_encode($seats));
you still assign all (encoded) seats to every instance of Seat. What you want is to assign only the seat from current loop iteration, which is represented by $result variable.
So try with:
$result->setName($result);
You do not need json_encode here too.
If your array is like you say it it then try this
foreach($seats as $seat) {
$result = new Seat();
$result->setName($seat);
$this->em->persist($result);
$this->em->flush();
}

Get array data and insert into database

I'm trying to get the data in the array that came from another function(that function is extracting the data in the csv file) and when i tried calling the two fields from that array it shows an error that it is unidentified variables.
The $this->csv_process(); as shown on the function action() is the function that extracts the data from the csv file and stores it in an array which is successful since I tried checking it on var_dump();
I also named the two fields as $name and $email as shown below:
Function CSV_process()
public function csv_process()
{
/* variables for openning the csv file */
if (!in_array($extension, $allowed_ext)) {
$this->session->set_flashdata("message", "Sorry, CSV file only.");
} else {
if ($filesize > 0) {
$file = fopen($filename, "r");
$toWrite = array();
$error = false;
$col_size = 2;
$skip = 0;
while ($data = fgetcsv($file, 10000, ","))
{
$skip++;
if ($skip == 1) {
continue;
}
$numofcol = count($data);
if ($numofcol != $col_size ) {
$this->session->set_flashdata("message", "Column count exceeded or missing.");
} else {
$name1 = $data[0];
$name = str_replace("'", "''", $name1);
$email1 = $data[1];
$email = str_replace("'", "''", $email1);
$toWrite[] = [
'name' => $name,
'email' => $email
];
}
}
}
}
return $toWrite;
}
Function Action()
function action(){
$toWrite[] = $this->csv_process();
foreach ($toWrite as $arr) {
list($name, $email) = $arr;
//die(var_dump($arr));
$query = $this->db->query("SELECT * FROM import WHERE name ='$name' AND email = '$email'");
if ($query->num_rows() >= 1) {
} else {
if ($name == "" OR $email == "") {
} else {
if ((filter_var($email, FILTER_VALIDATE_EMAIL)) == FALSE ) {
} else {
$this->db->query("INSERT INTO import(name, email, created_date) VALUES('".$name."', '".$email."', '".date("Y-m-d h-i-s")."')");
$this->session->set_flashdata('message', 'SUCCESS YEAY');
redirect('Clean_csv/index');
}
}
}
$query->free_result();
}
}
Listing arrays doesn't seem to work for here, anyone knows how to extract the data array from $arr?
You don't need to extract the values. You can use each $arr in a bound query. It simplifies the syntax for the select query.
For inserting use CodeIgniter's insert() method. Again, the $arr can be used directly by adding the date to it before the insert is attempted.
I think this will work.
function action()
{
$toWrite[] = $this->csv_process();
foreach($toWrite as $arr)
{
$query = $this->db->query("SELECT * FROM import WHERE name=? AND email=?", $arr);
if($query->num_rows() >= 1)
{}
else
{
if($arr['name'] == "" OR $arr['email'] == "")
{}
else
{
if((filter_var($email, FILTER_VALIDATE_EMAIL)) == FALSE)
{}
else
{
$arr['created_date'] = date("Y-m-d h-i-s");
$this->db->insert("import", $arr);
$this->session->set_flashdata('message', 'SUCCESS YEAY');
//??? redirect('Clean_csv/index');
//Are you sure, you may still have more $arr in $toWrite to process - right?
}
}
}
$query->free_result();
}
}
You need to know what a terrible idea it is to repeatedly run database queries inside a loop. Even though you use free_result() it could be a massive drain on server resources. If your csv file has several thousand items you are severely stressing the database and the server.

Drupal node_save is not saving fields

I have just stumbled upon very strange behaviour. In my code I am saving new node with some fields. I must say this used to work perfectly well. However now it just stopped working. I use the devel module to print out the content of objects and variables and this is my code:
dsm($node);
node_save($node);
dsm($node);
The first dsm() function displays node object as I created it and as it is supposed to be. The second dsm() function displays entirely correct node object with nid populated, fields content, etc... However, none of the fields is saved in database although there is new record in {node} table. Also, node_save does not generate any kind of error.
Any idea what is happening here?
This is the function storing the node:
function manhattan_incident_save($data) {
if ($data['nid']) {
$node = node_load($data['nid']);
manhattan_compare_changes($node, $data);
}
else {
$node = new stdClass();
$node->type = 'incident';
node_object_prepare($node);
$node->title = manhattan_create_incident_id();
$node->language = LANGUAGE_NONE;
}
$node->field_incident_popis[$node->language][0]['value'] = $data['field_incident_popis'];
$node->field_incident_popis[$node->language][0]['safe_value'] = check_plain($data['field_incident_popis']);
$node->field_incident_agent[$node->language][0]['uid'] = isset($data['field_incident_agent'])?intval($data['field_incident_agent']):NULL;
$node->field_incident_zdroj[$node->language][0]['tid'] = intval($data['field_incident_zdroj']);
$node->og_group_ref[$node->language][0]['target_id'] = $data['field_incident_oblast']?intval($data['field_incident_oblast']):variable_get('manhattan_public_form_default_area_nid', NULL);
$node->field_incident_riesitel[$node->language][0]['uid'] = isset($data['field_incident_riesitel'])?intval($data['field_incident_riesitel']):NULL;
$node->field_incident_typ[$node->language][0]['tid'] = intval($data['field_incident_typ']);
$node->field_incident_doplnenie[$node->language][0]['nid'] = intval($data['field_incident_doplnenie']);
$node->field_incident_sposob_kontaktu[$node->language][0]['value'] = $data['field_incident_sposob_kontaktu'];
$node->field_incident_dovod_vzniku[$node->language][0]['tid'] = intval($data['field_incident_dovod_vzniku']);
if ($data['field_incident_suvisiaci_zaznam']) {
foreach ($data['field_incident_suvisiaci_zaznam'] as $file) {
$result = manhattan_save_files($file);
if ($result) {
$node->field_incident_suvisiaci_zaznam[$node->language][] = array('nid' => $result);
}
}
}
// now create/save the customer
if (function_exists('customer_customer_save')) {
$customer = $data;
$customer['nid'] = $data['field_incident_customer'];
$result = customer_customer_save($customer);
if ($result) {
watchdog('upvs', $result['message'], array(), WATCHDOG_NOTICE);
}
else {
watchdog('upvs', t('There was a problem with saving customer %nid'), array('%nid' => $data['nid']), WATCHDOG_ERROR);
}
}
// now we store nid of saved customer to the node object
$node->field_incident_customer[$node->language][0]['nid'] = $result['nid'];
dsm($node);
node_save($node);
dsm($node);
if ($data['nid']) {
watchdog('upvs', t('Incident number %title has been succesfully saved.'), array('%title' => $node->title), WATCHDOG_NOTICE);
}
else {
watchdog('upvs', t('Incident number %title has been succesfully created.'), array('%title' => $node->title), WATCHDOG_NOTICE);
}
return $node;
}

Cake Php: Editing record also adds new records

i am trying to soft delete a record, but when ever i update the record i also get 6 new empty records. here is my edit code
public function del($id = null){
$dt = $this->Store->findById($id);
$dt["Store"]["status"] = 0;
if($this->Store->save($dt)){
$this->Session->setFlash("Your Store has been Deleted");
$this->redirect("/stores/");
}
}
As you describe in your question updated function will sure help you
public function del($id = null){
$dt = $this->Store->findById($id);
$dt["Store"]["id"] = $dt['Store']['id'];
// or
$dt["Store"]["id"] = $id // not empty every time.
$dt["Store"]["status"] = 0;
if($this->Store->save($dt)){
$this->Session->setFlash("Your Store has been Deleted");
$this->redirect("/stores/");
}
}
Set id for Store model, then use saveField.
public function del($store_id)
{
$this->Store->id = $store_id;
$this->Store->saveField('status', 0);
$this->redirect('/stores/');
}

Resources