How to insert value with new increment in codeigniter? - php

public function myfuntion() {
if($_POST){
$urnno = "NU-62819100";
$data = array(
"name" => $this->input->post('name'),
"email" => $this->input->post('email'),
"phone" => $this->input->post('phone'),
"urnno" => $urnno + 1
);
$sql = $this->db->insert('student',$data);
if($sql){
echo "success";
}else{
echo "fail";
}
}
$this->loca->view('myform');
}
In this code I am simply insert form value but what happen here when I insert value then urnno must be auto increment after new insert like if when I insert value first time then urnno must be NU-62819101 second time it will be 102 then 103 like this. So, How can I do this? Please help me.
Thank You

You can first get the last urnno stored in the table, get its numerical part increment it and then save it in the table.
I've written a possible solution for your problem, comments are mentioned wherever necessary. See if it helps you.
public function myfuntion() {
if($_POST){
// get the last row saved in table
$last = $this->db->select('urnno')->from('student')->order_by('id', 'DESC')->get()->row(); // id or some other auto incremented field
// get urnno from the last row
$last_urnno = $last->urnno;
$last_arr = explode("-", $last_urnno); // make it an array to get the numerical part
$new = $last_arr[1] + 1; // increment the value
$urnno = "NU-{$new}"; // new value
$data = array(
"name" => $this->input->post(''),
"email" => $this->input->post(''),
"phone" => $this->input->post(''),
"urnno" => $urnno // new value
);
$sql = $this->db->insert('student', $data);
if($sql){
echo "success";
}else{
echo "fail";
}
}
$this->loca->view('myform');
}

if you only increment the column with value 1 then you can try with setting up the column auto incremented in database. it makes easier and remove unwanted calculations.

Related

Can you store multiple arrays in one session?

Can you push multiple arrays to one session?
For example
array_push($_SESSION['mySession'], $array);
Problem: When i push another array to my session it removes tha last one in the session.
My case:
Get specific item from database
$meubel = $_GET['meubel'];
$sql = "SELECT * FROM mphp6_meubels WHERE naam LIKE '$meubel' ";
$stm = $pdo->prepare($sql);
$stm->execute();
Make new session if its does not exists:
if(!isset($_SESSION['meubels'])){
$_SESSION['meubels'] = array();
}
Make specific array
while($row = $stm->fetch()){
$meubel = [
'naam' => $row['naam'],
'type' => $row['type'],
'omschrijving' => $row['omschrijving'],
'prijs' => $row['prijs'],
];
}
push it to session
array_push($_SESSION['meubels'], $meubel);
When a button is clicked an ajax reqeust is made:
var url = 'test.php?meubel=' + meubel;
Output the session in a div
document.getElementById("div3").innerHTML = result;
If all ajax code is required please tell me.
Example:
When you buy a seat add it to the session. A seat has property's like: name, description and price. So the session must contain multiple arrays.
You are redefining $meubel each time through the loop so there is only one array. You want to dynamically append each row []:
while($row = $stm->fetch()){
$meubel[] = [
'naam' => $row['naam'],
'type' => $row['type'],
'omschrijving' => $row['omschrijving'],
'prijs' => $row['prijs'],
];
}
Then you probably want to merge instead of push, not sure what end result you want:
$_SESSION['meubels'] = array_merge($_SESSION['meubels'], $meubel);

How to store values in a PHP array as multiple records in MySQL

I have created a PHP function to insert data into a MySQL table. One of the values passed into the function is an array. The array contains unique values only. When I run the script it saves one record to the table with the field corresponding to the array storing all the array values.
This is my function which is in a separate class file:
public function importTest($val1,$valArray,$val3){
try {
$stm = $this->dbSt->prepare('INSERT INTO table (val1,valArray,val3) VALUES (:val1,:valArray,:val3)');
$stm->bindParam(':val1',$val1);
$stm->bindParam(':valArray',$valArray);
$stm->bindParam(':val3',$val3);
if($stm->execute()){
return true;
}
}catch (PDOException $e) {
echo $e->getMessage();
}
return false;
}
Setting $test and echoing to the screen for testing purposes. This displays all unique values in the array which is what I am looking for.:
$test = implode("<br />", (array_keys($array_unique_guests)));
echo 'TEST:<br /> '.$test.' <br />'; // Displays all unique values
echo '<br /><br />';
This is where I am calling the function:
$importTest = $statsDao->importTest($getSites[$x]['site_id'],$test,$updateDate);
I am using a for loop to get values for $getSites which calls another function.
I need all the values being echoed to the screen above as $test to be saved as new records in the table. Instead they are all being added in one record.
I would like to insert as many rows as there are values in the array. This number will change, but for example, if there are 10 values in the array, there should be 10 records added to the table, along with a date and another field. Basically, I am trying to retrieve all the values in the array and create a new record for each one when the script runs.
I hope this is clear. I've been stuck on this for a while and hoping someone can help!
Thanks!
Pass the array to the function, not an imploded string, and then use a loop in the function.
public function importTest($val1,$valArray,$val3){
try {
$stm = $this->dbSt->prepare('INSERT INTO table (val1,valArray,val3) VALUES (:val1,:val2,:val3)');
$stm->bindParam(':val1',$val1);
$stm->bindParam(':val2',$val2);
$stm->bindParam(':val3',$val3);
foreach ($valArray as $val2) {
$stm->execute();
}
}catch (PDOException $e) {
echo $e->getMessage();
return false;
}
return true;
}
You pass the array directly with:
$statsDao->importTest($getSites[$x]['site_id'], array_keys($array_unique_guests), $updateDate);
So far I could guess from the title,
$inser = "INSERT INTO table_name(id,name,pass) VALUES";
$valuearray = array( // the array composed of values that you have prepared
[
"id" => 1,
"name" => "John Due",
"pass" => "123456"
],
[
"id" => 2,
"name" => "Jonathan",
"pass" => "123456"
],
[
"id" => 3,
"name" => "Jonny",
"pass" => "123456"
]
);
foreach($valuearray as $val)
{
$inser .= "('".$val['id']."','".$val['name']."','".$val['pass']."')";
}
echo $inser;

Cannot create an array of just inserted record with mysqli in php

I am trying to insert a record into my table and then to use array push to create an array with that record but it seems that I am missing something here.. I use
$insert_sql = "INSERT INTO PasswordResetRequest(email,encrypted_temp_password,salt,created_at) VALUES('$email','$encrypted_temp_password','$salt',NOW());";
$insert_query = mysqli_query($con,$insert_sql);
$ins_result = array();
while($row = mysqli_fetch_array($insert_query)) {
array_push($ins_result, array(
'email' => $row['email'],
'encrypted_temp_password' => $row['encrypted_temp_password'],
'salt' => $row['salt'],
'created_at' => $row['created_at']
));
}
if ($ins_result) {
$user["email"] = $email;
$user["temp_password"] = $random_string;
return $user;
} else {
return false;
}
but I get an array with null, how should I implement it?
Thank you
Remember one thing, when you are inserting something its function will return true or false. True means record inserted and false means an error.
If you want to list down all inserted records as I assume that you were trying.
You need to make it in two parts.
// insert record
$insert_sql = "INSERT INTO PasswordResetRequest(email,encrypted_temp_password,salt,created_at) VALUES('$email','$encrypted_temp_password','$salt',NOW());";
$insert_query = mysqli_query($con,$insert_sql);
// select and list all records
$select_sql = "Select * from PasswordResetRequest";
$resultSet = mysqli_query($con, $select_sql);
while($row = mysqli_fetch_array($resultSet)){
array_push($ins_result,array('email'=>$row['email'],'encrypted_temp_password'=>$row['encrypted_temp_password'],'salt'=>$row['salt'],'created_at'=>$row['created_at']));
}
I think it will resolve your issue.

PHP search results not inserting on my table

I am creating a search module to show results from database, I am echoing out the data to check if I am receiving it from database.
here is my current output:
As you can see, the results are there but I wasn't able to display it on my table, and I also have that error for invalid argument for foreach(). Can anyone check what is the problem here?
echo form_open(site_url() . '/search/get_account',array('id' => 'formSearch'));
$data = array(
'name' => 'acctNum',
'id' => 'acctNum',
'type' => 'hidden',
'value' => set_value('acctNum',''),
);
$dataCertType = array($data);
$dataCertType[''] = '--';
if(! is_null($certType))
foreach($certType as $rowType)
$dataCertType[$rowType->certTypeId] = $rowType->certTypeName;
$formCertType = form_dropdown('certType', $dataCertType, set_value('certType'),'id="certType" class="dropdown"');
add brackets. echo out the form drop dropdown.
if(! is_null($certType)){
foreach($certType as $rowType){
$dataCertType[$rowType->certTypeId] = $rowType->certTypeName;
$formCertType = form_dropdown('certType', $dataCertType,set_value('certType'),'id="certType" class="dropdown"');
echo $formCertType ;
}
}
bonus points - do your is_null check in your controller, and then show an appropriate view.

Saving multiple HTML textareas in CodeIgniter

I would like to grab the values of several textarea fields and save them to the database. For now I have four of each with different values and I want to batch save these values, the textarea fields are:
<textarea name="compedia[]"></textarea>
<textarea name="specification[]"></textarea>
and the save function:
function saveCOA(){
$labref=$this->uri->segment(3);
$data= $this->input->post('compedia');
$data1= $this->input->post('specification');
$compedia=array(
'labref'=>$labref, //NDQA201303001
'compedia'=>$data,
'specification'=>$data1
);
foreach ($compedia as $value) {
$this->db->insert('coa_body',$value);
}
}
When I print_r($value) it returns :
NDQA201303001
Array ( [0] => Alphy [1] => poxy [2] => alphy [3] => poxy )
Array ( [0] => poxy [1] => alphy [2] => poxy [3] => alphy )
and when I try to save, it returns:
A Database Error Occurred
Error Number: 1054
Unknown column 'NDQA201303001' in 'field list'
INSERT INTO `coa_body` (`NDQA201303001`) VALUES ('')
Filename: C:\xampp\htdocs\NQCL\system\database\DB_driver.php
Line Number: 330
How should the syntax be so as to loop over all the textarea values and save them to the database at once?
I hope that
count($data) == count($data1); //Always True!
If that's the case the following will work:
for ($i=0;$i<count($data);$i++) {
$insert_data = array(
'labref'=>$labref, //NDQA201303001 - Same for all the rows
'compedia'=>$data[$i],
'specification'=>$data1[$i]
);
$this->db->insert('coa_body',$insert_data);
}
Check this Link: CodePad.org
Update:
Suggested by Rcpayan:
//This will reduce number of context switching,
//even though loping is doubled!
for ($i=0;$i<count($data);$i++) {
$insert_data[$i] = array(
'labref'=>$labref, //NDQA201303001
'compedia'=>$data[$i],
'specification'=>$data1[$i]
);
}
$this->db->insert_batch('coa_body',$insert_data);
You could do something like this, it's a bit longer but can also deal with compedia and specification not being equal. This solutions assumes a few things:
You want the value of labref to be the same for each row inserted
If the number of values for compedia and specification aren't equal, you still want to insert the row, but the 'missing' values will be set to NULL.
$labref = $this->uri->segment(3);
$compedia_data = $this->input->post('compedia');
$specification_data = $this->input->post('specification');
//Calculate which array is larger, so we can loop through all values
$max_array_size = max(count($compedia_data), count($specification_data));
//Iterate through the arrays
for ($i = 0; $i < $max_array_size; $i++)
{
$this->db->set('labref', $labref);
//If we still have a value(s) for compedia, then assign the value, otherwise set to NULL
if array_key_exists($i, $compedia_data)
{
$this->db->set('compedia', $compedia_data[$i]);
}
else
{
$this->db->set('compedia', NULL);
}
//If we still have a value(s) for specification, then assign the value, otherwise set to NULL
if array_key_exists($i, $specification_data)
{
$this->db->set('specification', $specification_data[$i]);
}
else
{
$this->db->set('specification', NULL);
}
//Insert into table: 'coa_body'
$this->db->insert('coa_body');
}
Alternatively, you could change the loop to assign the values to an array, then batch insert these values. This might offer better performance.
//Initial other relevant code is included in the example above (excluded here for brevity)
$insert_array = new array();
//Iterate through the arrays
for ($i = 0; $i < $max_array_size; $i++)
{
$row_array = new array();
$row_array['labref'] = $labref;
//If we still have a value(s) for compedia, then assign the value, otherwise set to NULL
if array_key_exists($i, $compedia_data)
{
$row_array['compedia'] = $compedia_data[$i];
}
else
{
$row_array['compedia'] = NULL;
}
//If we still have a value(s) for specification, then assign the value, otherwise set to NULL
if array_key_exists($i, $specification_data)
{
$row_array['specification'] = $specification_data[$i];
}
else
{
$row_array['specification'] = NULL;
}
//Add current row to the insert array, so it can be added to the database
$insert_array[$i] = $row_array;
}
//Insert into table: 'coa_body'
$this->db->insert_batch('coa_body', $insert_array);

Categories