Get array data and insert into database - arrays

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.

Related

row() return null for specific field

Im trying to save specific field from a record into a session, for my user-role. The problem here is i cannot take any other field except nama.
controller/verify_login
public function index(){
$this->load->model('verify_login_model');
$username = $this->input->post('username');
$password = $this->input->post('password');
$result = $this->verify_login_model->verify($username, $password);
if($result == $username) {
$name = $this->verify_login_model->getinfo($username);
$this->session->set_userdata('logged_in', TRUE);
$this->session->set_userdata('username', $username);
$this->session->set_userdata('name', $name);
$this->load->view('home_view');
} else {
redirect('login');
}
model/verify_login_model
function verify($username, $password){
$this->db->select('username', 'password');
$this->db->from('tb_user');
$this->db->where('username', $username);
$this->db->where('password', MD5($password));
$this->db->limit(1);
$query = $this->db->get();
if($query->num_rows()==1) {
return $username;
} else {
return false;
}
}
function getinfo($username) {
$this->db->select('nama', 'username');
$this->db->from('tb_userInfo');
$this->db->where('username', $username);
$this->db->limit(1);
$query = $this->db->get();
if($query->num_rows()==1) {
$result = $query->row();
return $result->nama;
} else {
return false;
}
}
view
<?php echo $this->session->userdata['name']?>
the var_dump($result) : object(stdClass)#22 (1) { ["nama"]=> string(4) "test" }
if i change the return $result->nama; to $result->username; i get error : Undefined property: stdClass::$username even tho im sure 200% there's username field in the table, and tried the query directly.
There's an error in your select statement, it must be
$this->db->select('nama,username');
You are separating each column, and that's not correct, all of the columns go in one string, that's why it tells you its undefined since the only column you are sending is nama and you're sending username as the second parameter for the select.
Here's a link on active record for CodeIgniter 2.2.0

Backup an entire website and database using PHP

I've been at this for a bit now and this is the closest I've gotten to backing up an entire site and database with PHP. The issue is I can't figure out why I continue to receive errors on lines 145 and 154.
Error:Notice: Undefined variable: arr_zip in C:\xampp\htdocs\wordpress\backup.php on line 145
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\wordpress\backup.php on line 145
Notice: Undefined variable: delete_zip in C:\xampp\htdocs\wordpress\backup.php on line 154
<?php
ini_set ("max_execution_time", 0);
$dir = "site-backup-stark";
if(!(file_exists($dir)))
{
mkdir($dir, 0777);
}
$host = "localhost"; //host name
$username = "wordpress_user"; //username
$password = "pasword99"; // your password
$dbname = "wordpress_db"; // database name
$zip = new ZipArchive();
backup_tables($host, $username, $password, $dbname);
/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '*')
{
$con = mysql_connect($host,$user,$pass);
mysql_select_db($name,$con);
//get all of the tables
if($tables == '*')
{
$tables = array();
$result = mysql_query('SHOW TABLES');
while($row = mysql_fetch_row($result))
{
$tables[] = $row[0];
}
}
else
{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
$return = "";
//cycle through
foreach($tables as $table)
{
$result = mysql_query('SELECT * FROM '.$table);
$num_fields = mysql_num_fields($result);
$return.= 'DROP TABLE '.$table.';';
$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
$return.= "nn".$row2[1].";nn";
while($row = mysql_fetch_row($result))
{
$return.= 'INSERT INTO '.$table.' VALUES(';
for($j=0; $j<$num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = preg_replace("#n#","n",$row[$j]);
if (isset($row[$j]))
{
$return.= '"'.$row[$j].'"' ;
}
else
{
$return.= '""';
}
if ($j<($num_fields-1)) { $return.= ','; }
}
$return.= ");n";
}
$return.="nnn";
}
//save file
$handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');
fwrite($handle,$return);
fclose($handle);
}
if (glob("*.sql") != false)
{
$filecount = count(glob("*.sql"));
$arr_file = glob("*.sql");
for($j=0;$j<$filecount;$j++)
{
$res = $zip->open($arr_file[$j].".zip", ZipArchive::CREATE);
if ($res === TRUE)
{
$zip->addFile($arr_file[$j]);
$zip->close();
unlink($arr_file[$j]);
}
}
}
//get the current folder name-start
$path = dirname($_SERVER['PHP_SELF']);
$position = strrpos($path,'/') + 1;
$folder_name = substr($path,$position);
//get the current folder name-end
$zipname = date('Y/m/d');
$str = "stark-".$zipname.".zip";
$str = str_replace("/", "-", $str);
// open archive
if ($zip->open($str, ZIPARCHIVE::CREATE) !== TRUE)
{
die ("Could not open archive");
}
// initialize an iterator
// pass it the directory to be processed
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("../$folder_name/"));
// iterate over the directory
// add each file found to the archive
foreach ($iterator as $key=>$value)
{
if( strstr(realpath($key), "stark") == FALSE)
{
$zip->addFile(realpath($key), $key) or die ("ERROR: Could not add file: $key");
}
}
// close and save archive
$zip->close();
echo "Archive created successfully.";
if(glob("*.sql.zip") != false)
{
$filecount = count(glob("*.sql.zip"));
$arr_file = glob("*.sql.zip");
for($j=0;$j<$filecount;$j++)
{
unlink($arr_file[$j]);
}
}
//get the array of zip files
if(glob("*.zip") != false)
{
$arr_zip = glob("*.zip");
}
//copy the backup zip file to site-backup-stark folder
foreach ($arr_zip as $key => $value) //error here
{
if (strstr($value, "stark"))
{
$delete_zip[] = $value;
copy("$value", "$dir/$value");
}
}
for ($i=0; $i < count($delete_zip); $i++) //error here
{
unlink($delete_zip[$i]);
}
?>
In this block of code:
//get the array of zip files
if(glob("*.zip") != false)
{
$arr_zip = glob("*.zip");
}
//copy the backup zip file to site-backup-stark folder
foreach ($arr_zip as $key => $value) //error here
If your call to glob("*.zip") returns a 'falsey' value your variable $arr_zip won't be initialised and you'll get an error in the foreach that follows it. Check for false explicitly with
if(glob("*.zip") !== false)
If this continues to fail you need to investigate why glob() is failing. I don't have a suggestion for that.
Later, you haven't initialised $delete_zip at all, somewhere you need
$delete_zip = array();

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;
}

update Auth session

How to update user information stored in auth session? without logout and login again.
I think this function will do it.. but is it the best-practice?
function update($field, $value){
$this->Session->write($this->Auth->sessionKey . '.' . $field, $value);
}
Yes.
You could grab the current info array, modify it, and then call $this->Auth->login($newUserData);, but this will also renew the session (no user interaction needed, though). Note: Applies to CakePHP 2.0+ only.
I've completed update function to get an array of new values. with keys (field name):
public function update($fields, $values = null) {
if (empty(parent::$_user) && !CakeSession::check(parent::$sessionKey)) {
return false;
}
if (!empty(parent::$_user)) {
$user = parent::$_user;
} else {
$user = CakeSession::read(parent::$sessionKey);
}
if (is_array($fields)) {
if (is_array($values)) {
$data = array_combine($fields, $values);
} else {
$data = $fields;
}
} else {
$data = array($fields => $values);
}
foreach ($data as $field => $value) {
if (isset($user[$field])) {
$user[$field] = $value;
}
}
return $this->login($user);
}
(thanks to tigrang for login function)

counting occurrences in an array

I am trying to count the number of occurrences in an array of cart items in Magento.
There are several items in the array, all with a price field (either $0 and $10)
What I'm looking to do, is to display the count of those items that have a price of 0
I currently have:
$session = Mage::getSingleton('checkout/session');
$items_array = $session->getQuote()->getAllItems();
foreach($items_array as $item) {
if ($item->getPrice() == 0) {
echo 'Item is free';
}
else {
}
}
This simply outputs all the free items. Ideally, I'd like to display just the count of such items.
Could I use something like array_count_values, but limit it to only count those values that are 0?
You can do that with several ways, but having that code the most easy one will be:
$session = Mage::getSingleton('checkout/session');
$items_array = $session->getQuote()->getAllItems();
$freeItems = 0;
foreach($items_array as $item) {
if ($item->getPrice() == 0) {
$freeItems++;
}
}
echo "There are $freeItems free items";
$session = Mage::getSingleton('checkout/session');
$items_array = $session->getQuote()->getAllItems();
$free = 0;
$notfree = 0;
foreach($items_array as $item) {
if ($item->getPrice() == 0) {
echo 'Item is free';
$free++;
}
else {
$notfree++;
}
}
echo 'total free items = ' . $free;
echo 'total nonfree items = ' . $notfree;

Resources