Voting Duplicate Votes - php
We currently have a voting system setup that saves the IP address of the person making a vote to stop duplicate votes.
However everyday the IP address is removed from the database so they can re-vote on there favourite item.
Looking through the code below can you see how I can stop this so that a person with a certain IP address can never vote for that certain item again? They are however able to vote on the other entrants, but again only vote once.
Any ideas?
<?php
// Script Voting - http://www.coursesweb.net/
class Voting {
// properties
static protected $conn = false; // stores the connection to mysql
public $affected_rows = 0; // number of affected, or returned rows in SQL query
protected $voter = ''; // the user who vote, or its IP
protected $nrvot = 0; // if it is 1, the user can vote only one item in a day, 0 for multiple items
protected $svoting = 'mysql'; // 'mysql' to register data in database, any other value register in TXT files
public $votitems = 'voting'; // Table /or file_name to store items that are voted
public $votusers = 'votusers'; // Table /or filename that stores the users who voted in current day
protected $tdy; // will store the number of current day
public $eror = false; // to store and check for errors
// constructor
public function __construct() {
// sets $nrvot, $svoting, $voter, and $tdy properties
if(defined('NRVOT')) $this->nrvot = NRVOT;
if(defined('SVOTING')) $this->svoting = SVOTING;
if(defined('USRVOTE') && USRVOTE === 0) { if(defined('VOTER')) $this->voter = VOTER; }
else $this->voter = $_SERVER['REMOTE_ADDR'];
$this->tdy = date('j');
// if set to use TXT files, set the path and name of the files
if($this->svoting != 'mysql') {
$this->votitems = '../votingtxt/'.$this->votitems.'.txt';
$this->votusers = '../votingtxt/'.$this->votusers.'.txt';
}
}
// for connecting to mysql
protected function setConn() {
try {
// Connect and create the PDO object
self::$conn = new PDO("mysql:host=".DBHOST."; dbname=".DBNAME, DBUSER, DBPASS);
// Sets to handle the errors in the ERRMODE_EXCEPTION mode
self::$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
self::$conn->exec('SET CHARACTER SET utf8'); // Sets encoding UTF-8
}
catch(PDOException $e) {
$this->eror = 'Unable to connect to MySQL: '. $e->getMessage();
}
}
// Performs SQL queries
public function sqlExecute($sql) {
if(self::$conn===false OR self::$conn===NULL) $this->setConn(); // sets the connection to mysql
$re = true; // the value to be returned
// if there is a connection set ($conn property not false)
if(self::$conn !== false) {
// gets the first word in $sql, to determine whenb SELECT query
$ar_mode = explode(' ', trim($sql), 2);
$mode = strtolower($ar_mode[0]);
// performs the query and get returned data
try {
if($sqlprep = self::$conn->prepare($sql)) {
// execute query
if($sqlprep->execute()) {
// if $mode is 'select', gets the result_set to return
if($mode == 'select') {
$re = array();
// if fetch() returns at least one row (not false), adds the rows in $re for return
if(($row = $sqlprep->fetch(PDO::FETCH_ASSOC)) !== false){
do {
// check each column if it has numeric value, to convert it from "string"
foreach($row AS $k=>$v) {
if(is_numeric($v)) $row[$k] = $v + 0;
}
$re[] = $row;
}
while($row = $sqlprep->fetch(PDO::FETCH_ASSOC));
}
$this->affected_rows = count($re); // number of returned rows
}
}
else $this->eror = 'Cannot execute the sql query';
}
else {
$eror = self::$conn->errorInfo();
$this->eror = 'Error: '. $eror[2];
}
}
catch(PDOException $e) {
$this->eror = $e->getMessage();
}
}
// sets to return false in case of error
if($this->eror !== false) { echo $this->eror; $re = false; }
return $re;
}
// returns JSON string with item:['vote', 'nvotes', renot] for each element in $items array
public function getVoting($items, $vote = '') {
$votstdy = $this->votstdyCo($items); // gets from Cookie array with items voted by the user today
// if $vote not empty, perform to register the vote, $items contains one item to vote
if(!empty($vote)) {
// if $voter empty means user not loged
if($this->voter === '') return "alert('Vote Not registered.\\nYou must be logged in to can vote')";
else {
// gets array with items voted today from mysql, or txt-files (according to $svoting), and merge unique to $votstdy
if($this->svoting == 'mysql') {
$votstdy = array_unique(array_merge($votstdy, $this->votstdyDb()));
}
else {
$all_votstdy = $this->votstdyTxt(); // get 2 array: 'all'-rows voted today, 'day'-items by voter today
$votstdy = array_unique(array_merge($votstdy, $all_votstdy[$this->tdy]));
}
// if already voted, add in cookie, returns JSON from which JS alert message and will reload the page
// else, accesses the method to add the new vote, in mysql or TXT file
if(in_array($items[0], $votstdy) || ($this->nrvot === 1 && count($votstdy) > 0)) {
$votstdy[] = $items[0];
setcookie("votings", implode(',', array_unique($votstdy)), strtotime('tomorrow'));
return '{"'.$items[0].'":[0,0,3]}';
}
else if($this->svoting == 'mysql') $this->setVotDb($items, $vote, $votstdy); // add the new vote in mysql
else $this->setVotTxt($items, $vote, $all_votstdy); // add the new vote, and voter in TXT files
array_push($votstdy, $items[0]); // adds curent item as voted
}
}
// if $nrvot is 1, and $votstdy has item, set $setvoted=1 (user already voted today)
// else, user can vote multiple items, after Select is checked if already voted the existend $item
$setvoted = ($this->nrvot === 1 && count($votstdy) > 0) ? 1 : 0;
// get array with items and their votings from mysql or TXT file
$votitems = ($this->svoting == 'mysql') ? $this->getVotDb($items, $votstdy, $setvoted) : $this->getVotTxt($items, $votstdy, $setvoted);
return json_encode($votitems);
}
// insert /update rating item in #votitems, delete rows in $votusers which are not from today, insert $voter in $votusers
protected function setVotDb($items, $vote, $votstdy) {
$this->sqlExecute("INSERT INTO `$this->votitems` (`item`, `vote`) VALUES ('".$items[0]."', $vote) ON DUPLICATE KEY UPDATE `vote`=`vote`+$vote, `nvotes`=`nvotes`+1");
$this->sqlExecute("DELETE FROM `$this->votusers` WHERE `day`!=$this->tdy");
$this->sqlExecute("INSERT INTO `$this->votusers` (`day`, `voter`, `item`) VALUES ($this->tdy, '$this->voter', '".$items[0]."')");
// add curent voted item to the others today, and save them as string ',' in cookie (till the end of day)
$votstdy[] = $items[0];
setcookie("votings", implode(',', array_unique($votstdy)), strtotime('tomorrow'));
}
// select 'vote' and 'nvotes' of each element in $items, $votstdy stores items voted by the user today
// returns array with item:['vote', 'nvotes', renot] for each element in $items array
protected function getVotDb($items, $votstdy, $setvoted) {
$re = array_fill_keys($items, array(0,0,$setvoted)); // makes each value of $items as key with an array(0,0,0)
function addSlhs($elm){return "'".$elm."'";} // function to be used in array_map(), adds "'" to each $elm
$resql = $this->sqlExecute("SELECT * FROM `$this->votitems` WHERE `item` IN(".implode(',', array_map('addSlhs', $items)).")");
if($this->affected_rows > 0) {
for($i=0; $i<$this->affected_rows; $i++) {
$voted = in_array($resql[$i]['item'], $votstdy) ? $setvoted + 1 : $setvoted; // add 1 if the item was voted by the user today
$re[$resql[$i]['item']] = array($resql[$i]['vote'], $resql[$i]['nvotes'], $voted);
}
}
return $re;
}
// add /update rating item in TXT file, keep rows from today in $votusers, and add new row with $voter
protected function setVotTxt($items, $vote, $all_votstdy) {
// get the rows from file with items, if exists
if(file_exists($this->votitems)) {
$rows = file($this->votitems, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$nrrows = count($rows);
// if exist rows registered, get array for each row, with - item^vote^nvotes
// if row with item, update it and stop, else, add the row at the end
if($nrrows > 0) {
for($i=0; $i<$nrrows; $i++) {
$row = explode('^', $rows[$i]);
if($row[0] == $items[0]) {
$rows[$i] = $items[0].'^'.($row[1] + $vote).'^'.($row[2] + 1);
$rowup = 1; break;
}
}
}
}
if(!isset($rowup)) $rows[] = $items[0].'^'.$vote.'^1';
file_put_contents($this->votitems, implode(PHP_EOL, $rows)); // save the items in file
// add row with curent item voted and the voter (today^voter^item), and save all the rows
$all_votstdy['all'][] = $this->tdy.'^'.$this->voter.'^'.$items[0];
file_put_contents($this->votusers, implode(PHP_EOL, $all_votstdy['all']));
// add curent voted item to the others today, and save them as string ',' in cookie (till the end of day)
$all_votstdy[$this->tdy][] = $items[0];
setcookie("votings", implode(',', array_unique($all_votstdy[$this->tdy])), strtotime('tomorrow'));
}
// get from TXT 'vote' and 'nvotes' of each element in $items, $votstdy stores items voted by the user today
// returns array with item:['vote', 'nvotes', renot] for each element in $items array
protected function getVotTxt($items, $votstdy, $setvoted) {
$re = array_fill_keys($items, array(0,0,$setvoted)); // makes each value of $items as key with an array(0,0,0)
if(file_exists($this->votitems)) {
$rows = file($this->votitems, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$nrrows = count($rows);
// if exist rows registered, get array for each row, with - item^vote^nvotes
// if row with item is in $items, add its data in $re
if($nrrows > 0) {
for($i=0; $i<$nrrows; $i++) {
$row = explode('^', $rows[$i]);
$voted = in_array($row[0], $votstdy) ? $setvoted + 1 : $setvoted; // add 1 if the item was voted by the user today
if(in_array($row[0], $items)) $re[$row[0]] = array($row[1], $row[2], $voted);
}
}
}
return $re;
}
// gets and returns from Cookie an array with items voted by the user ($voter) today
protected function votstdyCo() {
$votstdy = array();
// if exists cookie 'votings', adds items voted today in $votstdy (array_filter() - removes null, empty elements)
if(isset($_COOKIE['votings'])) {
$votstdy = array_filter(explode(',', $_COOKIE['votings'])); // cookie stores string with: item1, item2, ...
}
return $votstdy;
}
// returns from mysql an array with items voted by the user today
protected function votstdyDb() {
$votstdy = array();
$resql = $this->sqlExecute("SELECT `item` FROM `$this->votusers` WHERE `day`=$this->tdy AND `voter`='$this->voter'");
if($this->affected_rows > 0) {
for($i=0; $i<$this->affected_rows; $i++) {
$votstdy[] = $resql[$i]['item'];
}
}
return $votstdy;
}
// returns from TXT file an array with 2 arrays: all rows voted today, and items voted by the user today
protected function votstdyTxt() {
$re['all'] = array(); $re[$this->tdy] = array();
if(file_exists($this->votusers)) {
$rows = file($this->votusers, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$nrrows = count($rows);
// if exist rows registered, get array for each row, with - day^voter^item , compare 'day', and 'voter'
if($nrrows > 0) {
for($i=0; $i<$nrrows; $i++) {
$row = explode('^', $rows[$i]);
if($row[0] == $this->tdy) {
$re['all'][] = $rows[$i];
if($row[1] == $this->voter) $re[$this->tdy][] = $row[2];
}
}
}
}
return $re;
}
}
Make an SQL database of the IP addresses you want to ban, or if the list is short enough us an array.
Check if the IP address is in the database or array. If it's not allow them to vote. However, if it is let them think they voted put it in the database and make it as voted, but mark the vote as does not count so they will not try to get around your block.
This function seems to be deleting votes that are not from "today":
// insert /update rating item in #votitems, delete rows in $votusers which are not from today, insert $voter in $votusers
protected function setVotDb($items, $vote, $votstdy) {
$this->sqlExecute("INSERT INTO `$this->votitems` (`item`, `vote`) VALUES ('".$items[0]."', $vote) ON DUPLICATE KEY UPDATE `vote`=`vote`+$vote, `nvotes`=`nvotes`+1");
//$this->sqlExecute("DELETE FROM `$this->votusers` WHERE `day`!=$this->tdy");
$this->sqlExecute("INSERT INTO `$this->votusers` (`day`, `voter`, `item`) VALUES ($this->tdy, '$this->voter', '".$items[0]."')");
// add curent voted item to the others today, and save them as string ',' in cookie (till the end of day)
$votstdy[] = $items[0];
setcookie("votings", implode(',', array_unique($votstdy)), strtotime('tomorrow'));
}
I've commented out the delete query. You should test it out before putting it into production.
Your database structure seems a bit confusing, you have a table to count the vote per items and a table to count the vote per user.
You should review your database structure to merge those two tables in one table, with the : item, user, vote fields.
So you could keep a record for each vote of each user for each item as long as you want and eventualy make count() or sum() requests to get the total of votes per item
Related
Is there a way to update 12000+ rows from txt file in less then 2mins?
I need to update a table with more then 12000 row using php Codeigniter and a txt file.. reading the file and the foreach loop are fine but when updating line by line it takes like 30 mins, I guess the problem is I'm searching by name because I have no id in the txt file... Here is my code: controller: $fn = fopen($this->upload->data('full_path'),"r"); $update = true; while(! feof($fn) && $update) { $pieces = explode("|", fgets($fn)); if(sizeof($pieces) == 9 && is_numeric(trim($pieces[1]))) { $update = $this->model_products->update3s($pieces); } } fclose($fn); Model: public function update3s($product) { if ($product) { $product[2] = trim(str_replace("'","''",$product[2])); $product[1] = trim($product[1]); $product[6] = trim($product[6]); $product[3] = trim($product[3]); $sql = "UPDATE products set qty = $product[3], price_vente = $product[6] where (name = '$product[2]')"; echo $sql.'<br>'; $update = $query = $this->db->query($sql); return $update; } return false; }
You can use transaction and add index for column name in database table. $fn = fopen($this->upload->data('full_path'),"r"); $update = true; $updatedCount = 0; while(! feof($fn) && $update) { $pieces = explode("|", fgets($fn)); if(sizeof($pieces) == 9 && is_numeric(trim($pieces[1]))) { if ($updatedCount == 0) { $databaseInstance->beginTransaction(); } $update = $this->model_products->update3s($pieces); ++$updatedCount; if ($updatedCount > 500) { //in one transaction update 500 rows $databaseInstance->commit(); $updatedCount = 0; } } } if ($updatedCount > 0) { // if we have not commited transaction $databaseInstance->commit(); } fclose($fn);
Some tips Add index to field name Use prepared statements Disable the MySQL forgeign key check Read more
writing sql function can do that even in much lesser time . using feature like : REPLACE() cursors SPLIT_STRING(custom) in a mysql user defined function CREATE FUNCTION update3s(hole_file_content LONGTEXT) RETURNS Boolean BEGIN -----Your implementation(same logic in sql ) ------ END then coll it just by if it is CI 3 $this->db->call_function('update3s', file_get_contents($this->upload->data('full_path'))); else $this->db->query("select update3s(".file_get_contents($this->upload->data('full_path')).")");
Same serial number is generating for different requests
I am inserting a serial number in a table that is increment by one always but when multiple request is coming in same time it is inserting same serial number for different requests.I am using mysql database. I know i am fetching the max serial number too early in the code and if request is come in same time so it will fetching same serial number for both. is it good idea to update serial number after all work done. what if inserting a record for new request and updating the serial number for previous one is in same time. public function add(){ $session = $this->request->session(); $company_id = $session->read('Admin.company_id'); $emp_id = $session->read('Admin.emp_id'); $user_email_id = $session->read('Admin.email_id'); $employee_name = $session->read('Admin.employee_name'); $conn = ConnectionManager::get('default'); if ($this->request->is('post')) { try{ $conn->begin(); $department = $this->request->data['department']; $data = $this->request->data; if(!array_key_exists('is_requisition_for_contractor', $data)){ $is_requisition_for_contractor = 0; } else { $is_requisition_for_contractor = $data['is_requisition_for_contractor']; } if(!array_key_exists('is_requisition_for_employee', $data)){ $is_requisition_for_employee = 0; } else { $is_requisition_for_employee = $data['is_requisition_for_employee']; } if(!array_key_exists('is_boulder_requisition', $data)){ $is_requisition_for_boulder = 0; } else { if($data['is_boulder_requisition'] == ''){ $is_requisition_for_boulder = 0; } else { $is_requisition_for_boulder = $data['is_boulder_requisition']; } } $is_requisition_for_plant = 0; if(!array_key_exists('is_plant_requisition', $data)){ $is_requisition_for_plant = 0; } else { if($data['is_plant_requisition'] == ''){ $is_requisition_for_plant = 0; } else { $is_requisition_for_plant = $data['is_plant_requisition']; } } if(array_key_exists("files",$this->request->data)) { $files = $this->request->data['files']; if (count($files)) { $files_uploading_response = $this->uploadMultipleFiles($files, 'files/requisitions/'); } } $last_material_insert_id = ''; if($this->request->data('material_id')[0] == ''){ if($this->request->data('department') == 1){ $type = 1; } elseif($this->request->data('department') == 3){ $type = 3; } elseif($this->request->data('department') == 2){ $type = 2; } if($this->request->data('department') == 1 || $this->request->data('department') == 3){ $conn->execute("INSERT INTO material (material_name, material_type_id, company_id, status, is_approved_by_admin) VALUES (?,?,?,?,?)",[$this->request->data('material_name'), $type, $company_id, 1,0]); $last_material_insert_id = $conn->execute("SELECT LAST_INSERT_ID() AS last_id")->fetchAll('assoc'); } elseif($this->request->data('department') == 2) { //todo for unapproved material $conn->execute("INSERT INTO material (part_no, material_type_id, company_id, status, is_approved_by_admin,unique_category_id) VALUES (?,?,?,?,?,?)",[$this->request->data('part_no')[0], $type, $company_id, 1,0,$this->request->data('unique_category_id')[0]]); $last_material_insert_id = $conn->execute("SELECT LAST_INSERT_ID() AS last_id")->fetchAll('assoc'); } } // here i am fatching max serial number from table $requistion_number = $conn->execute("SELECT IF(MAX(requisition_no) IS NULL, 0,MAX(requisition_no)) AS requisition_no FROM requisition WHERE site_id = ?",[$this->request->data('site_id')])->fetchAll('assoc'); $Requisition = TableRegistry::get('requisition'); $requisition = $Requisition->newEntity(); $requisition->registered_on = $this->request->data['date']; $requisition->department_id = $this->request->data('department'); $requisition->site_id = $this->request->data('site_id'); $requisition->issues_to_id = $this->request->data['prepared_by_id']; $requisition->prepared_by_id = $this->request->data['prepared_by_id']; $requisition->approved_by_id = $this->request->data['hod_id']; $requisition->hod_id = $this->request->data['hod_id']; $requisition->is_diesel_requisition_for_employee = $is_requisition_for_employee; $requisition->is_diesel_requisition_for_contractor = $is_requisition_for_contractor; $requisition->is_requisition_for_boulder = $is_requisition_for_boulder; $requisition->is_requisition_for_plant = $is_requisition_for_plant; if(array_key_exists('for_tanker_stock', $this->request->data)) { $requisition->for_tanker_stock = 1; } if($last_material_insert_id != ''){ $requisition->is_material_approved_by_admin = 0; } $requisition->status = 1; $site_id = $this->request->data['site_id']; $requisition->requisition_no = $requistion_number[0]['requisition_no'] + 1; $requistionnumber = $requistion_number[0]['requisition_no'] + 1; $saveRequsition = $Requisition->save($requisition); $conn->commit(); } I am expecting the output different serial number for each request.any optimise way to do this. thanks in advance.
Ok, how about the same strategy, setting the $requisition_number after the row has been inserted (see my other answer), but using a single query with the same method you use to determine the new requisition id: $conn->execute("UPDATE requisition SET requisition_no = (SELECT IF(MAX(requisition_no) IS NULL, 0,MAX(requisition_no)) AS requisition_no FROM requisition WHERE site_id = ?) + 1", [$this->request->data('site_id')]); The idea here is that a single query will be executed in one step, without another, similar query, being able to interfere.
What you currently do is to first get the old requistion number like this: $requistion_number = $conn->execute("SELECT IF(MAX(requisition_no) IS NULL, 0,MAX(requisition_no)) AS requisition_no FROM requisition WHERE site_id = ?",[$this->request->data('site_id')])->fetchAll('assoc'); and then increase it before you save and commit. My suggestion is to not set the $requistion_number at all before you save and commit the requisition row, but to determine the $requistion_number afterwards. You now wonder how? Well, you need to count the total number of requisition rows in the table for the site the requisition is for, and add one, like this: $last_requisition_id = $conn->execute("SELECT LAST_INSERT_ID() AS last_id")->fetchAll('assoc'); $site_id = $this->request->data('site_id'); $requisition_number = $conn->execute("SELECT COUNT(*) AS requisitionsCount FROM requisition WHERE <primary_key> <= ? AND site_id = ?", [$last_requisition_id, $site_id]) + 1; $conn->execute("UPDATE requisition SET requisition_no = ? WHERE <primary_key> <= ?", [$requisition_number, $last_requisition_id]); I know this code is not working. The $requisition_number will probably contain an array with the requisitionsCount as a value, but you can correct that. Because you're using data that is already present in the database table you don't run the risk that two rows will get the same $requisition_number. The assumption here is that requisitions are never deleted.
Compare uploaded data in database and raw CSV data
Here is the code after I uploaded the raw file then tried to validate the raw file with the uploaded file to see if they match: while ($db_fetch_row = sqlsrv_fetch_array($database_query)){ $db_eid = $db_fetch_row['eid']; $db_team_lead = $db_fetch_row['team_lead']; $db_role = $db_fetch_row['role']; $db_productivity = $db_fetch_row['productivity']; $db_quality = $db_fetch_row['quality']; $db_assessment = $db_fetch_row['assessment']; $db_staffed_hours = $db_fetch_row['staffed_hours']; $db_kpi_productivity = $db_fetch_row['kpi_productivity']; $db_kpi_quality = $db_fetch_row['kpi_quality']; $db_kpi_assessment = $db_fetch_row['kpi_assessment']; $db_kpi_staffed_hours = $db_fetch_row['kpi_staffed_hours']; for($row = 2; $row <= $lastRow; $row++) { $eid = $worksheet->getCell('A'.$row)->getValue(); $team_lead = $worksheet->getCell('C'.$row)->getValue(); $role = $worksheet->getCell('B'.$row)->getValue(); $productivity = $worksheet->getCell('D'.$row)->getValue(); $productivity1 = chop($productivity,"%"); $quality = $worksheet->getCell('E'.$row)->getValue(); $quality1 = chop($quality,"%"); $assessment = $worksheet->getCell('F'.$row)->getValue(); $assessment1 = chop($assessment,"%"); $staffed_hours = $worksheet->getCell('G'.$row)->getValue(); $staffed_hours1 = chop($staffed_hours,"%"); $kpi_productivity = $worksheet->getCell('H'.$row)->getValue(); $kpi_quality = $worksheet->getCell('I'.$row)->getValue(); $kpi_assessment = $worksheet->getCell('J'.$row)->getValue(); $kpi_staffed_hours = $worksheet->getCell('K'.$row)->getValue(); if($db_eid == $eid) { echo "Raw and Uploaded file Matched"; } else { echo "Did not match"; } } } The output always didn't match, as you can see below:
Of course it outputs that. Let's think it through: For every row in the DB, you are checking EVERY row in the CSV. Presumably there is only ONE row in the CSV that has the same ID as the row in the DB, so that means if there are 100 records in the CSV, it will output "no match" 99 times (assuming there is 1 record in the CSV that does match). One approach is to separate it into a function and attempt to find the matching row, as follows: // Loop over all DB records while ($db_fetch_row = sqlsrv_fetch_array($database_query)) { // call our new function to attempt to find a match $match = find_matching_row( $db_fetch_row, $worksheet ); // If there's no match, output "didn't find a match" if ( ! $match ) { echo '<br>DID NOT FIND A MATCH.'; // If there IS a match, $match represents the row number to use.... } else { var_dump( $match ); // Do your work on the match data... $team_lead = $worksheet->getCell('C'.$match)->getValue(); // ...etc } } /** * Attempt to find a row from the CSV with the same ID as the DB * record passed in. * * #param array $db_fetch_row * #param mixed $worksheet */ function find_matching_row( $db_fetch_row, $worksheet ) { $db_eid = $db_fetch_row['eid']; // Youll need to calculate $lastRow for this to work right.. $lastRow = .... ; // Loop through the CSV records for($row = 2; $row <= $lastRow; $row++) { // If the IDs match, return the row number if($db_eid == $worksheet->getCell('A'.$row)->getValue() ){ return $row; } } // If no match, return FALSE return FALSE; }
Count post data in a CodeIgniter controller
I have five text fields that are not mandatory. Sometimes enter data in one field, sometimes 2 or 3 or 4 or 5. I have to count this data: $sib1=$this->input->post(sib1); $sib2=$this->input->post(sib2); $sib3=$this->input->post(sib3); Like this, I want to count this. Now 3
You can use a for loop with length = number of text fields. Put it to the database afterwards. sibcount is the number of filled entries. $data = array(); $length = 5; $sibcount = 0; for ($i=0;$i<$length;$i++) { $entry = $this->input->post("sib".$i); if (!empty($entry)) { $data["sib".$i] = $entry; $sibcount++; } } $data["sibcount"] = $sibcount; // use in controller or model if (!empty($data)) $this->db->insert('mytable', $data);
this is way to do it: Take an array $arr=array(); $arr['sib1']=$this->input->post("sib1",true); $arr['sib2']=$this->input->post("sib2",true); $arr['sib3']=$this->input->post("sib3",true); $arr['count']=count($this->input->post($arr)); //this will count your post $result = $this->Model_name->model_function($arr); In Model function model_function($arr) { $this->db->insert('tbl',$arr); if ($this->db->affected_rows() > 0) { return true; } else { return false; }
Adding another User ID if that wasn't present in a string
I'm using this function; function add_profile_visitor($add_uid,$to_uid,$visitors_list) { global $db; $list = trim($visitors_list); $list_users = explode(",",$list); if (in_array($add_uid,$list_users)) { return; } else { if (strpos($list_users,",") || strlen($list_users) > 0) { $newlist = $list_users.",".intval($add_uid); } else { $newlist = intval($add_uid); } $db->query("UPDATE users SET profile_visitor='".$db->escape_string($newlist)."' WHERE uid=".$to_uid); } } I want to add a User ID if its not present already in the field profile_visitor. For your notice, the profile_visitor list is comma separated list. Here are the variable's legend: $add_uid = The user id that is going to be inserted in profile_visitor if its not present in already. $to_uid = The User ID where profile_visitor column is present and the $add_uid add in if its not present. $visitors_list = The comma separated list of profile visitors. Before adding any User ID that list will be empty (obviously) The issue is: Each time the page loads (where that function is running) the list profile_visitor has the new User ID instead of adding the new User ID to the list. Please help
Change your function to this: function add_profile_visitor($add_uid,$to_uid,$visitors_list) { global $db; $list = trim($visitors_list); $list_users = explode(",",$list); if (in_array($add_uid,$list_users)) { return; } else { if (strpos($list,",") || strlen($list) > 0) { $newlist = $list.",".intval($add_uid); } else { $newlist = intval($add_uid); } $db->query("UPDATE users SET profile_visitor='".$db->escape_string($newlist)."' WHERE uid=".$to_uid); } }