Codeigniter Insert Array to Database - arrays

I have created a form in Codeigniter with a phone number field that dynamically is duplicated using javascript. So basically I can have one or more fields like this.
<input name="phone[]" value=""type="text">
<input name="phone[]" value=""type="text">
Then in my controller I have
$form_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'phone' => $this->input->post('phone[]')
);
Then I am saving this to my dabase like so
function SaveForm($form_data)
{
$this->db->insert('customers', $form_data);
if ($this->db->affected_rows() == '1')
{
return TRUE;
}
return FALSE;
}
but obviously the code for 'phone' is wrong, I just cant figure out how to properly do this.

you can't save array in to database. You can convert it in to string using implode() and whenever you needed then convert it back in array using explode(). Like below
$phone=implode(',',$this->input->post('phone'));
$form_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'phone' => $phone
);
OR
You can convert it to json string and when you needed convert back to Array Like below:
$phone = json_encode($this->input->post('phone'));
Convert back to array
$phone = json_decode($phone, TRUE);

Modify your function as below and it will works like charm,
function SaveForm($form_data)
{
foreach ($form_data as $contact)
{
$data[] = array(
'first_name' => $contact['first_name'],
'last_name' => $contact['last_name'],
'phone' => $contact['phone']
);
}
$this->db->insert_batch('customers', $data);
if ($this->db->affected_rows() > 0)
{
return TRUE;
}
return FALSE;
}
Modified:
Oh, yes you have to edit para array that you passed to SaveForm function.
Please use following code, ignore above code:
foreach($_POST['first_name'] as $key=>$fname)
{
$form_data[] = array(
'first_name' => $_POST['first_name'][$key],
'last_name' => $_POST['last_name'][$key],
'phone' => $_POST['phone'][$key],
);
}
function SaveForm($form_data)
{
$this->db->insert_batch('customers', $data);
if ($this->db->affected_rows() > 0)
{
return TRUE;
}
return FALSE;
}

In controller
$phone = $_POST['phone'];//this will store data as array. Check image 02
$form_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'phone' => $phone,//some times it works with '$phone'
);
In Model
function SaveForm($form_data)
{
$this->db->insert('customers', $form_data);
if ($this->db->affected_rows() == '1')
{
return TRUE;
}
else
{
return FALSE;
}
}
Tested
Image 01 (My form)
Image 02 (After Submitted)

mysql doesn’t has any array data type. So we can not store array directly into mysql database.
To do this we have to first convert array into string using php serialize() function then save it into mysql database.
for eg:php code to store array in database
$array = array("foo", "bar", "hello", "world");
$conn=mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db("mysql_db",$conn);
$array_string=mysql_escape_string(serialize($array));
To retrieve array from database
$conn=mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db("mysql_db",$conn);
$q=mysql_query("select column from table",$conn);
while($rs=mysql_fetch_assoc($q))
{
$array= unserialize($rs['column']);
print_r($array);
}

for array insertion to database use this programme in codeigniter controller=>
$inputdata=$this->input->post();
$phone=array($inputdata['phone']);
foreach($phone as $arr)
{
$phoneNo=$arr;
$f=count($phoneNo);
for($i=0;$i<$f;$i++)
{
$arre=[
'phone'=>$phoneNo[$i],
];
$insertB= $this->user_model->userdata($arre);
}
}

public function add_theme_pages(){
$page_name = $this->input->post('page');
$page_img = $this->input->post('page_img');
for($i=0; $i < count($page_name); $i++){
$pages_data = array(
'theme_id' => $this->input->post('theme_id'),
'theme_page_name' => $page_name[$i],
'theme_page_img' => $page_img[$i]
);
if($this->backendM->add_theme_pages($pages_data)){
$this->session->set_flashdata('message', 'Theme Added Successfully !');
$this->session->set_flashdata('message_class', 'green');
$this->create_template();
}else{
$this->create_template();
}
}
}

Related

How to match an input value in Laravel match before saving to sqlite database

I am trying to make the value of $input data to first match with one the pluck array values in a user table in the database before the input is saved and a response of 'its a match be given'. I trying to put these checks on an API I'm making. I'm new to laravel API and I will appreciate the help. Thank you
public function create(Request $request)
{
//
$this->validate($request, [
'inputed_number' => 'required|unique:users',
'user_id' => 'required'
]);
try {
Auth::user();
$phonenumber = new PhoneNumber();
$phonenumber->inputed_number = $request->inputed_number;
$phonenumber->user_id = $request->user_id;
if($this->user->phonenumber()->save($phoneuumber)){
$user = User::all();
$input = $request->only('inputed_number');
$user_number = $user->pluck('phone');
foreach ($input as $phone) {
if ($phone !== $user_number) {
return response()->json([
'success' => false,
'message' => 'Invalid number',
'data' => $phone,
], Response::HTTP_UNAUTHORIZED);
}
return response()->json([
'success' => true,
'message' => 'Its a match!!',
'data' => $phone,
]);
}
}
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => 'You have already inputted this number.',
], Response::HTTP_UNAUTHORIZED);
}
}
just get the whole user object with Auth:user no need for the pluck statement, you can access values directly via user object,
$user = Auth:user();
$input = $request->only('inputed_number');
if($user->phone !== $input ) {
//perform this code
}
If you want to match phone numbers from all users,
//get all users where phone number matches
$users = User::where('phone', $input)->get();
// iterate through $users rows
foreach ($users as $user) {
///do some thing
}

Retrive data using cakephp

I am new to cakephp and i want to find data that has been created
This is my sql function works
Select Trv_No from Ticket_LO
This is my model in cakephp
$ticket = $this->Ticket->find('first', array('conditions' => array('AND' => array('Ticket.TRV_No' => $trv_no)));
if(empty($ticket))
{
$table_name = 'Ticket_L0';
$this->Ticket->setSource($table_name);
//$ticket = $this->Ticket->find('first', array('conditions' => array('Ticket.TRV_No' => $trv_no)));
$ticket = $this->Ticket->find('first', array('conditions' => array('AND' => array('Ticket.TRV_No' => $trv_no, 'Ticket.HIDDEN_STAT LIKE' =>'0'))));
if(empty($ticket)) { return false; } else { return true; }
}
else
{ return true; }
}
First things first,
You don't need to set $this->Ticket->setSource($table_name); in your model.
You can use $this->find
I'm not sure what do you really want. But, I guess you want something like that.
$ticket = $this->find('first', array(
'conditions' => array(
'Ticket.TRV_No' => $trv_no,
'Ticket.HIDDEN_STAT'=> 0 //if you want to find 0 only, you don't need LIKE. But, if you want some string, you can use something like 'Ticket.HIDDEN_STAT LIKE'=>'yourString%'
)
)
);
And, you can add your condition after that.
if(!empty($ticket)) return true;
else return false;

cakephp 3.0 passing data to the form.php

I am using a modelless form to send a contact email. I am using the example in the cookbook.
With the change to data in objects form arrays I am unsure what form the data is in being passed to the ContactForm.php
I have tried $data['name'] and $data[0]['name']
View for input name without the data[]
<input type="text" class="form-control" name="name" placeholder="Your Name" required="" aria-required="true" aria-invalid="false">
PagesController.php
public function contact(){
$this->request->allowMethod('ajax');
$contact = new ContactForm();
if ($this->request->is('post')) {
if ($contact->execute($this->request->data)) {
$data = array(
'status' => 'successful'
);
} else {
$data = array(
'status' => 'error'
);
}
$this->set(compact('data')); // Pass $data to the view
$this->set('_serialize', 'data');
}
}
ContactForm.php
protected function _execute(array $data)
{
// Send an email.
$email = new Email('default');
$email->emailFormat('html');
$email->template('demoTemplate')->viewVars( array('userName' => $data[0]['name'],
'userCompany' => '$data',
'userEmail' => '$data',
'userPhone' => '$data'));
$email->from('info#domain.com');
$email->to('$data');
$email->bcc('$data');
$email->subject('Contact Form Submission');
if ($email->send()) {
return true;
}
else {
return false;
}
}
Well for do this I use first this tool advanced-rest-client, and inside the code of cakephp you can use try and catch, you can user debug() too, example debug($data); in combination with advanced-rest-client you can see the result.
and if debug dont work serialice the data
$this->set('data', $data);
$this->set('_serialize', ['data']);
but even when serialized data use advanced-rest-client, just select the post option and type the url of where you want to get the post.
so:
public function contact(){
$this->request->allowMethod('ajax');
$contact = new ContactForm();
if ($this->request->is('post')) {
if ($contact->execute($this->request->data)) {
debug($this->request->data());//first
$datos = $this->request->data();//second
$data = [
'content' => $datos,
'status' => 'successful',
];
} else {
$datos = $this->request->data();
$data = [
'content' => $datos,
'status' => 'error,
];
}
$this->set(compact('data')); // Pass $data to the view
$this->set('_serialize', 'data');
}
}

custom datasource find('list') issue

I am creating a custom datasource and I am having problems when i request find('list'). find('all') returns perfectly what I want within my controller but find('list') just returns an empty array.
The funny thing is if I do a die(Debug($results)) in the datasource within the read function then I get my find('list') array correctly but if I return it i then get an empty array in my controller. Any ideas?
Code below:
public function read(Model $model, $queryData = array(), $recursive = null) {
if ($queryData['fields'] == 'COUNT') {
return array(array(array('count' => 1)));
}
$this->modelAlias = $model->alias;
$this->suffix = str_replace('Flexipay', '', $model->alias);
if(empty($model->id)){
$this->url = sprintf('%s%s%s', $this->sourceUrl, 'getAll', Inflector::pluralize($this->suffix));
}
$r = $this->Http->get($this->url, $this->config);
if($r->isOk()){
$results_src = json_decode($r->body, true);
if(is_array($results_src)){
//$this->find('list');
if($model->findQueryType == 'list'){
return $this->findList($queryData, $recursive, $results_src);
}
//$this->find('all');
foreach($results_src['PortalMandantenResponses']['portalMandantenResponses'] as $r){
$results[] = $r;
}
if(!empty($results)){
$e = array($model->alias => $results);
return $e;
}
}
}else{
//
}
return false;
}
My response from die(debug(array($model->alias => $results);
(int) 0 => array(
'Mandant' => array(
'ns2.id' => (int) 79129,
'ns2.name' => 'company a'
)
),
(int) 1 => array(
'Mandant' => array(
'ns2.id' => (int) 70000,
'ns2.name' => 'company b'
)
),
Controller Code is here:
public function test2(){
//$a = $this->User->find('list');
//die(debug($a));
$this->loadModel('Pay.Mandant');
$a = $this->Mandant->find('list', array('fields' => array('ns2.systembenutzernr', 'ns2.systembenutzernrBezeichnung')));
die(debug($a));
}
use,
$a = $this->Mandant->find('list', array('fields' => array('ns2.systembenutzernr', 'ns2.systembenutzernrBezeichnung')));
$this->set(compact('a'));
You can use $a for the dropdown creation in view file.
I just had the same problem writing my custom model though I don't know if the cause in your case is the same, though you should probably look in the same place.
in Model.php there is a function _findList($state, $query, $results), my issue was the fields you specify in the find() call must match the $results structure exactly, otherwise at the end of the _findList() function the call to:
Hash::combine($results, $query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath'])
returns the empty array. The keyPath of {n}.MODELNAME.id, etc must match the name of the model specified in $results, for example
[0] => ['MODELNAME'] = array()
[1] => ['MODELNAME'] = array()
In my case my keyPath and valuePath had a different value for MODELNAME than in the results array
Hope that helps

How to send data to custom block content

I'm trying to create a module that will display some last entries from database. I'd like to send last entry object to template file (guestbook-last-entries.tpl.php), that looks like that
<p><?php render($title); ?></p>
<?php echo $message; ?>
I have a function that implements hook_theme
function guestbook_theme() {
return array(
'guestbook_last_entries' => array(
'variables' => array(
'entries' => NULL,
),
'template' => 'guestbook-last-entries'
),
);
}
one that do preprocess
function template_preprocess_guestbook_last_entries(&$variables) {
$variables = array_merge((array) $variables['entries'], $variables);
}
and functions that implements hook_block_view
function guestbook_block_view($delta = '') {
switch ($delta) {
case 'guestbook_last_entries':
$block['subject'] = t('Last entries');
$block['content'] = array();
$entries = guestbook_get_last_entries(variable_get('guestbook_m', 3));
foreach ($entries as $entry) {
$block['content'] += array(
'#theme' => 'guestbook_last_entries',
'#entries' => $entry,
);
}
break;
}
return $block;
}
function that gets data from database
function guestbook_get_last_entries($limit = 3) {
$result = db_select('guestbook', 'g')
->fields('g')
->orderBy('posted', 'DESC')
->range(0, $limit)
->execute();
return $result->fetchAllAssoc('gid');
}
But in this case I get only one entry displayed. Can anyone tell me how to resolve this, how should I build that $block['content']?
Thank you
This here wont work:
$block['content'] += array(
'#theme' => 'guestbook_last_entries',
'#entries' => $entry,
);
Maybe you want this if you need an array as the result:
// note that I replaced += with a simple = and added two brackets that will create a new element in that array $block['content']
$block['content'][] = array(
'#theme' => 'guestbook_last_entries',
'#entries' => $entry,
);

Resources