Replacing "NA" and blanks by either similuating data or using blanks - php

I am very new to php and MYSQL so this is probably a very simple thing for a lot of people but is taking me hours.
My developer created the below code which is used to parse a csv file into some MYSQL tables.
Once the data is parsed into the MYSQL table, I have a separate script which I use to create some search forms on the data. For example, users can select all data where column X is between -50 and +50.
I want to accomplish 2 things:
In instances where there is either a "NA" or blank in the csv file for a particular column, I want this NOT be recognized as 0 in the database, which is what is currently happening. For example, if I run a search where I select all values to be between -10 and 10 for column A and column A contains blanks or "NAs", then these blanks or "NAs" should not be recognized in the search output (and database) as 0s. However, they should show up in every search result. Regardless, in the search form, I do not want to see the "NAs". I am sure I am not the first problem to encounter this problem and that there is a best practices method for this.
I want to replace all instances of " in the csv file with a blank. I know I can use the "preg_replace" function for this but I don't know the best place to put it.
Thanks!
<?php
ini_set('max_execution_time', 0);
ini_set('display_errors', 'On');
ini_set('error_reporting', E_ALL & ~E_NOTICE);
$global_start = microtime(true);
include_once('db.php');
$full_path = #dirname(__FILE__) . '/';
$distinct_fields = array('g', 'i', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 'y', 'z', 'aa', 'ab', 'ac', 't', 'u', 'v');
if (isset($_POST['truncate'])) {
mysqli_query($mysqli, 'TRUNCATE TABLE odesk_nj_data');
mysqli_query($mysqli, 'TRUNCATE TABLE odesk_nj_catalog');
}
if (isset($_POST['filename']) && is_file($full_path . $_POST['filename'])) {
$separator = $_POST['separator'];
$handle = fopen($full_path . $_POST['filename'], "r");
$fields = array();
$i = 0;
$proccess_iteration = 0;
mysqli_autocommit($mysqli, false);
while (($data = fgetcsv($handle, 0, $separator)) !== FALSE) {
if ($i == 0) {
$fields = $data;
} elseif ($data[0] != '') {
$branch_id = GetBranchId($data[0]);
$qs = 'INSERT INTO odesk_nj_data SET branch_id=' . $branch_id;
foreach ($fields as $index => $field_name)
{
if (strtolower($field_name) != 'a' /*&& strtolower($field_name)!='ad'*/)
{
$tmp = explode(',', $data[$index]);
// if ($data[$index] == '' || $data[$index] == 'NA')
// {
// $value = -1000.99;
// }
// elseif (count($tmp) == 2 && is_numeric($tmp[0]) && is_numeric($tmp[1]))
if (count($tmp) == 2 && is_numeric($tmp[0]) && is_numeric($tmp[1]))
{
$value = implode('.', $tmp);
} else {
$value = $data[$index];
}
$qs .= ', `' . strtolower($field_name) . '`="' . $value . '"';
}
if (in_array(strtolower($field_name), $distinct_fields)) {
SaveToCatalog(strtolower($field_name), $value);
}
}
mysqli_query($mysqli, $qs);
}
$i++;
$proccess_iteration++;
if ($proccess_iteration > 300) {
mysqli_commit($mysqli);
$proccess_iteration = 0;
mysqli_autocommit($mysqli, false);
}
}
mysqli_commit($mysqli);
echo 'Upload Complete! Was uploaded ' . ($i - 1) . ' rows.';
exit;
}
function SaveToCatalog($FieldName, $Value)
{
global $mysqli;
static $data;
if (!isset($data[$FieldName])) {
$result = mysqli_query($mysqli, 'SELECT * FROM odesk_nj_catalog WHERE field="' . $FieldName . '" ');
while ($item = mysqli_fetch_assoc($result)) {
$data[$FieldName][base64_encode($item['field_value'])] = true;
}
}
if (!isset($data[$FieldName][base64_encode($Value)])) {
$result = mysqli_query($mysqli, 'SELECT * FROM odesk_nj_catalog WHERE field="' . $FieldName . '" AND field_value="' . mysqli_real_escape_string($mysqli, $Value) . '"');
$info = mysqli_fetch_assoc($result);
if (isset($info['id']) && $info['id'] > 0) {
$data[$FieldName][base64_encode($Value)] = true;
} else {
mysqli_commit($mysqli);
mysqli_autocommit($mysqli, true);
$qs = 'INSERT INTO odesk_nj_catalog SET field="' . $FieldName . '", field_value="' . $Value . '"';
mysqli_query($mysqli, $qs);
if (mysqli_insert_id($mysqli) > 0) {
$data[$FieldName][base64_encode($Value)] = true;
}
mysqli_autocommit($mysqli, false);
}
}
}
function GetBranchId($BranchName)
{
global $mysqli;
static $branches;
if (empty($companies)) {
$result = mysqli_query($mysqli, 'SELECT * FROM odesk_nj_branches ');
while ($item = mysqli_fetch_assoc($result)) {
$branches[$item['branch_name']] = $item['branch_id'];
}
}
if (!isset($branches[$BranchName])) {
$result = mysqli_query($mysqli, 'SELECT * FROM odesk_nj_branches WHERE branch_name="' . $BranchName . '"');
$company_info = mysqli_fetch_assoc($result);
if (isset($company_info['branch_id']) && $company_info['branch_id'] > 0) {
$branches[$BranchName] = $company_info['branch_id'];
} else {
mysqli_commit($mysqli);
mysqli_autocommit($mysqli, true);
$qs = 'INSERT INTO odesk_nj_branches SET branch_name="' . $BranchName . '"';
mysqli_query($mysqli, $qs);
$branches[$BranchName] = mysqli_insert_id($mysqli);
mysqli_autocommit($mysqli, false);
}
}
return $branches[$BranchName];
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form enctype="multipart/form-data" method="post" action="nj_load.php">
Filename to parse: <input type="text" name="filename" value="Table.csv"><br/>
CSV Separator: <input type="text" name="separator" value=","><br/>
Truncate Table before parsing: <input type="checkbox" name="truncate" checked=""><br/>
<input type="submit" value="Parse">
</form>
</body>
</html>

Use NULL instead of "NA", and then a numeric column. UPDATE table SET col1=NULL where col1='NA'
After import, UPDATE table SET col1=NULL where col1=''. Otherwise, i don't really know what the difference between '' and a blank is.

Related

Object of type mysqli_result error in old vBulletin product

I am trying to update an old vBulletin product and it keeps throwing an error for me.
Cannot use object of type mysqli_result as array in C:\wamp\www\mem_payment.php on line 124
Line 124:
$vbma->setCustomerNumber(unserialize($purchase['info']), $product['pur_group'], false, $userinfo);
Line 102 - 130
$purchase = $vbulletin->db->query_first("SELECT * FROM " . TABLE_PREFIX .
"ma_purchases WHERE id = '" . $id . "'");
$order = unserialize($purchase['order']);
if ($order[0] !== $vbulletin->GPC['business'])
{
$status_code = '503 Service Unavailable';
// Paypal likes to get told its message has been received
if (SAPI_NAME == 'cgi' or SAPI_NAME == 'cgi-fcgi')
{
header('Status: ' . $status_code);
}
else
{
header('HTTP/1.1 ' . $status_code);
}
}
unset($order[0]);
if ($purchase and !in_array($order[1], array('renew', 'upgrade')))
{
$product = $vbulletin->db->query_read("SELECT pur_group FROM " . TABLE_PREFIX .
"ma_products WHERE id = '" . $order[1] . "'");
$userinfo = fetch_userinfo($purchase['userid']);
$vbma->setCustomerNumber(unserialize($purchase['info']), $product['pur_group'], false,
$userinfo);
$rand = rand($vbulletin->options['memarea_numstart'], $vbulletin->options['memarea_numend']);
$licnum = substr(md5($prodid . rand(0, 20000) . $rand . $rand), 0, rand(10, $vbulletin->
options['memarea_custnumleng']));
$licensedm = datamanager_init('License', $vbulletin, ERRTYPE_ARRAY);
$licensedm->setr('userid', $userinfo['userid']);
I have been reading numerous questions regarding this error stating to essentially:
define your query
query your query
then associate the query
IE:
$query = "SELECT 1";
$result = $mysqli->query($query);
$followingdata = $result->fetch_assoc()
Almost all of the answers are along those lines, although I am failing to see where this needs to be done.
I'm not sure if it has anything to do with the function, but I will add that as well:
function setCustomerNumber($ma_info, $usergroup = '', $usevb = true, $userinfo = '')
{
if ($usevb == false)
{
$this->vbulletin->userinfo = &$userinfo;
}
$fcust = $this->fields['custnum'];
$fpass = $this->fields['mpassword'];
$finfo = $this->fields['info'];
$userdm = datamanager_init('User', $this->vbulletin, ERRTYPE_ARRAY);
$userinfo = fetch_userinfo($this->vbulletin->userinfo['userid']);
$userdm->set_existing($userinfo);
if (!$this->vbulletin->userinfo["$fcust"] and !$this->vbulletin->userinfo["$fpass"])
{
$rand = rand($this->vbulletin->options['memarea_numstart'], $this->vbulletin->
options['memarea_numend']);
$num = $this->vbulletin->options['custnum_prefix'] . substr(md5($rand), 0, $this->
vbulletin->options['memarea_custnumleng'] - strlen($this->vbulletin->options['custnum_prefix']));
$userdm->set($fcust, $num);
$pass = substr(md5(time() . $num . $rand . rand(0, 2000)), 0, $this->vbulletin->
options['memarea_custnumleng']);
$userdm->set($fpass, $pass);
$this->sendCustomerInfo($this->vbulletin->userinfo['userid'], $this->vbulletin->
userinfo['username'], $this->vbulletin->userinfo['email'], $num, $pass);
}
if ($usergroup or $usergroup !== '' or $usergroup !== '0')
{
if ($usergroup != $this->vbulletin->userinfo['usergroupid'])
{
$ma_info['oldgroup'] = $this->vbulletin->userinfo['usergroupid'];
$userdm->set('usergroupid', $usergroup);
}
}
if ($ma_info)
{
$ma_info = serialize($ma_info);
$userdm->set($finfo, $ma_info);
}
$userdm->pre_save();
if (count($userdm->errors) == 0)
{
$userdm->save();
return true;
}
else
{
var_dump($userdm->errors);
return false;
}
}
Why am I getting this error? In your answer could you please explain to me what needs to be changed.
query_read returns mysqli_result&, you need convert it to an array first.
$query_result = $vbulletin->db->query_read(...);
$product = $query_result->fetch_assoc();

PHP Random Name instead of sequence

I have a basic URL shortener script but I am having an issue. Each time I enter a new url to shorten the script just adds the next letter to the database (i.e. http://www.both.com/a then http://www.both.com/b then http://www.both.com/c etc). The problem is I don't want to people to be able to view those links by simply going in sequential order. How can I make it so each new url has a random 6 digit alpha and numerical name created? Also, I wanted to make the alpha both random upper and lower case.
<?php
require 'config.php';
header('Content-Type: text/plain;charset=UTF-8');
$url = isset($_GET['url']) ? urldecode(trim($_GET['url'])) : '';
if (in_array($url, array('', 'about:blank', 'undefined', 'http://localhost/'))) {
die('Enter a URL.');
}
if (strpos($url, SHORT_URL) === 0) {
die($url);
}
function nextLetter(&$str) {
$str = ('z' == $str ? 'a' : ++$str);
}
function getNextShortURL($s) {
$a = str_split($s);
$c = count($a);
if (preg_match('/^z*$/', $s)) { // string consists entirely of `z`
return str_repeat('a', $c + 1);
}
while ('z' == $a[--$c]) {
nextLetter($a[$c]);
}
nextLetter($a[$c]);
return implode($a);
}
$db = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE);
$db->set_charset('utf8mb4');
$url = $db->real_escape_string($url);
$result = $db->query('SELECT slug FROM redirect WHERE url = "' . $url . '" LIMIT 1');
if ($result && $result->num_rows > 0) { // If there’s already a short URL for this URL
die(SHORT_URL . $result->fetch_object()->slug);
} else {
$result = $db->query('SELECT slug, url FROM redirect ORDER BY date DESC, slug DESC LIMIT 1');
if ($result && $result->num_rows > 0) {
$slug = getNextShortURL($result->fetch_object()->slug);
if ($db->query('INSERT INTO redirect (slug, url, date, hits) VALUES ("' . $slug . '", "' . $url . '", NOW(), 0)')) {
header('HTTP/1.1 201 Created');
echo SHORT_URL . $slug;
$db->query('OPTIMIZE TABLE `redirect`');
}
}
}
?>
try something like this :
function generateString($length) {
$alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$alphabetLength = strlen($alphabet);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $alphabet[rand(0, $alphabetLength - 1)];
}
return $randomString;
}
$short = generateRandomString(6);

SQLSTATE[42000]: Syntax error or access violation: 1064?

What is the problem to the code? I cannot upload to database. It comes the message:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ACQUA'))' at line 2
query was:
SELECT `vals`.*, `opt`.*
FROM `eav_attribute_option_value` AS `vals`
INNER JOIN `eav_attribute_option` AS `opt` ON opt.option_id = vals.option_id
WHERE (opt.attribute_id='191')
AND (vals.value in ('ALESSANDRO DELL'ACQUA'))
PHP Code:
<?php
/**
* Adapted by Christopher Shennan
* http://www.chrisshennan.com
*
* Date: 20/04/2011
*
* Adaptered from original post by Srinigenie
* Original Post - http://www.magentocommerce.com/boards/viewthread/9391/
*/
class Mage_Eav_Model_Import extends Mage_Eav_Model_Mysql4_Entity_Attribute {
private $fileName;
private $delimiter = '|';
private $enclosure = '"';
private function &getCsv() {
$file = fopen($this->fileName, "r");
while (!feof($file)) {
$csvArr[] = fgetcsv($file, 0, $this->delimiter, $this->enclosure);
}
fclose($file);
return $csvArr;
}
protected function populateOptionTable($attribId) {
echo "Upload Begin<br/>";
$fields = array();
$values = array(); // store id => values
$optionValues = array(); // option id => $values
$option = array('value' => $optionValues);
$updateOptionValId;
$values = null;
$row = null;
$disCounter = 0;
$optionTable = $this->getTable('attribute_option');
$optionValueTable = $this->getTable('attribute_option_value');
$write = $this->_getWriteAdapter();
$csvStoreArr = array();
// Get CSV into Array
$csv = & $this->getCsv();
$read = $this->_getReadAdapter();
// exit if the csv file is empty or if it contains only the headers
if (count($csv) < 1 or count($csv) == 1)
return;
$fields = $csv[0]; // get the field headers from first row of CSV
// get the store Ids
$stores = Mage::getModel('core/store')
->getResourceCollection()
->setLoadDefault(true)
->load();
// determine the stores for which option values are being uploaded for
foreach ($fields as $hdr) {
if ($hdr === 'position' || $hdr === 'isDefault' || $hdr === 'ERROR') {
continue;
}
foreach ($stores as $store) {
if ($store->getCode() === $hdr)
$csvStoreArr[$hdr] = $store->getId();
}
}
// start reading the option values - from row 1 (note that 0 represents headers)
for ($indx = 1; $indx < count($csv); $indx++) {
$values = null; // initialize to null
$row = $csv[$indx]; // get row
if (isset($row) && count($row) > 0) {
//escape the single quote
//$whereParam = $read->quote($row);
if (is_array($row))
$whereParam = '(\'' . implode($row, '\',\'') . '\')';
else if (strlen($row))
$whereParam = '(\'' . $row . '\')';
$select = $read->select()->from(array('vals' => $optionValueTable))
->join(array('opt' => $optionTable), 'opt.option_id=vals.option_id')
->where('opt.attribute_id=?', $attribId);
$select = $select
->where('vals.value in ' . $whereParam);
$optionValData = $read->fetchAll($select);
unset($select);
// get the option Id for this option
if (count($optionValData) > 0) {
$optionValDataRow = $optionValData[0];
$optionId = $optionValDataRow['option_id'];
} else
$optionId = null;
$intOptionId = (int) $optionId;
if (!$intOptionId) {
$data = array(
'attribute_id' => $attribId,
'sort_order' => isset($option['order'][$optionId]) ? $option['order'][$optionId] : 0,
);
try {
$write->insert($optionTable, $data);
$intOptionId = $write->lastInsertId();
} catch (Exception $e) {
Mage::log($e->getMessage());
}
} else {
$data = array(
'sort_order' => isset($option['order'][$optionId]) ? $option['order'][$optionId] : 0,
);
$write->update($optionTable, $data, $write->quoteInto('option_id=?', $intOptionId));
}
$colIndx = 0; //initialize row's column index
if (isset($row) && is_array($row) && count($row) > 0) {
foreach ($row as $optVal) {
if ($fields[$colIndx] !== 'position' || $fields[$colIndx] !== 'isDefault' || $fields[$colIndx] !== 'ERROR') {
$values[$csvStoreArr[$fields[$colIndx]]] = $optVal; // store id => option value
}
$colIndx++;
}
}
}
if (isset($values) && is_array($values) && count($values) > 0) {
foreach ($values as $storeId => $value) {
if (!empty($value) || strlen($value) > 0) {
$value = trim($value);
$data = array(
'option_id' => $intOptionId,
'store_id' => $storeId,
'value' => $value,
);
$optionValInsert = true;
$optionValUpdate = false;
foreach ($optionValData as $valData) {
if ((int) $valData['option_id'] === $intOptionId &&
(int) $valData['store_id'] === $storeId) {
$optionValInsert = false;
if (strcasecmp(trim($valData['value']), $value) !== 0) {
$optionValUpdate = true;
$updateOptionValId = $valData['value_id'];
}
break;
}
}
if ($optionValInsert) {
$write->insert($optionValueTable, $data);
Mage::log('Inserted Value -' . $value);
} else if ($optionValUpdate) {
$write->update($optionValueTable, $data, $write->quoteInto('option_id=?', $updateOptionValId));
Mage::log('Updated Value -' . $value);
}
}
}
}
$optionValues[$optionId] = $values;
if ($indx % 20 == 0) {
echo "" . $indx . ' - uploaded!!<br />';
Mage::log($indx . ' - attributes uploaded!!', null, $this->fileName . '.log');
}
}
echo "" . $indx . ' - uploaded!!<br />';
echo '<b> Attribute Upload Finished </b><br />';
$option['value'] = $optionValues;
return null;
}
/**
* Enter description here...
*
* #param Mage_Core_Model_Abstract $object
* #return Mage_Eav_Model_Mysql4_Entity_Attribute
*/
public function saveOptionValues($attributeId, $fn) {
$option = array();
$this->fileName = $fn;
echo '<strong>Importing Attributes</strong><br/><br/>Reading file contents - ' . $this->fileName . '<br />';
Mage::log("Upload Begin", null, $this->fileName . '.log');
// Step 1 -- Get attribute Id from attribute code
$atrribId = $attributeId; //569
// Step 2 Obtain the option values into an array
$option = $this->populateOptionTable($atrribId);
}
}
Error is because of single Quotes in the string : 'ALESSANDRO DELL'ACQUA.
SELECT vals., opt. FROM eav_attribute_option_value AS vals INNER JOIN
eav_attribute_option AS opt ON opt.option_id=vals.option_id WHERE
(opt.attribute_id='191') AND (vals.value in ('ALESSANDRO
DELL'ACQUA'))
Try using double quotes.
String Literals in MySQL [ https://dev.mysql.com/doc/refman/5.0/en/string-literals.html ]
' single quote is reserved character in MySQL and there are several ways to include quote characters within a string:
A "'" inside a string quoted with "'" may be written as ""''".
A """ inside a string quoted with """ may be written as """".
Precede the quote character by an escape character (""\").
A "'" inside a string quoted with """ needs no special treatment and
need not be doubled or escaped. In the same way, """ inside a string
quoted with "'" needs no special treatment.
To avoid this use PreparedStatement in PHP http://www.w3schools.com/php/php_mysql_prepared_statements.asp
In your query is should be like 'ALESSANDRO DELL''ACQUA' instead of 'ALESSANDRO DELL'ACQUA'

Previous/next button in PHP

I´m pretty much entirely new to PHP, so please bear with me.
I´m trying to build a website running on a cms called Core. I'm trying to make it so that the previous/next buttons cycle through tags rather than entries. Tags are stored in a database as core_tags. Each tag has it own tag_id, which is a number. I've tried changing the excisting code for thep previous/next buttons, but it keeps giving me 'Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /home/core/functions/get_entry.php on line 50'.'
Any help would be greatly appreciated.
Get_entry.php:
<?php
$b = $_SERVER['REQUEST_URI'];
if($entry) {
$b = substr($b,0,strrpos($b,"/")) . "/core/";
$id = $entry;
$isPerma = true;
} else {
$b = substr($b,0,mb_strrpos($b,"/core/")+6);
$id = $_REQUEST["id"];
}
$root = $_SERVER['DOCUMENT_ROOT'] . $b;
$http = "http://" . $_SERVER['HTTP_HOST'] . substr($b,0,strlen($b)-5);
require_once($root . "user/configuration.php");
require_once($root . "themes/".$theme."/configuration.php");
require_once($root . "functions/session.php");
if(is_numeric($id)) {
$type = "entry";
} else {
$type = "page";
}
$id = secure($id);
if($type == "page") {
$data = mysql_query("SELECT p.* FROM core_pages p WHERE p.page_title = \"$id\"");
$page_clicks = 0;
while($p = mysql_fetch_array($data)) {
$url = $p["page_url"];
$path = $root . "user/pages/" . $url;
$page_clicks = $p['hits']+1;
require($path);
}
mysql_query("UPDATE core_pages p SET
p.hits = $page_clicks
WHERE p.page_title = $id");
}
if($type == "entry") {
// queries the dbase
$data_tags = mysql_query("SELECT entry_id,entry_title FROM core_entries WHERE entry_show = 1 ORDER BY entry_position DESC") or die(mysql_error());
$navArr=array();
while($tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC)){
array_push($navArr,$tmparray['entry_id']);
}
function array_next_previous($array, $value) {
$index = array_search($value,$array);
//if user clicked to view the very first entry
if($value == reset($array)){
$return['prev'] = end($array);
$return['next'] = $array[$index + 1];
//if user clicked to view the very last entry
}else if($value == end($array)){
$return['prev'] = $array[$index - 1];
reset($array);
$return['next'] = current($array);
}else{
$return['next'] = $array[$index + 1];
$return['prev'] = $array[$index - 1];
}
return $return;
}
$data = mysql_query("SELECT e.* FROM core_entries e WHERE e.entry_id = $id AND e.entry_show = 1");
$entry_clicks = 0;
if(#mysql_num_rows($data) < 1) {
die("Invalid id, no entry to be shown");
}
while($e = mysql_fetch_array($data)) {
$nextPrevProject = array_next_previous($navArr,$id);
$entry_id = $e['entry_id'];
$entry_title = $e['entry_title'];
// DATE
$t = $e["entry_date"];
$y = substr($t,0,4);
$m = substr($t,5,2);
$d = substr($t,8,2);
$entry_date = date($date_format,mktime(0,0,0,$m,$d,$y));
$entry_text = $e['entry_text'];
$entry_extra1 = $e['entry_extra1'];
$entry_extra2 = $e['entry_extra2'];
$entry_client = $e['entry_client'];
$entry_position = $e['entry_position'];
$entry_hits = $e['hits']+1;
$entry_new = $e['entry_new'];
if($entry_new == 1) {
$isNew = true;
} else {
$isNew = false;
}
if($nice_permalinks) {
$entry_perma = "$http".$entry_id;
} else {
$entry_perma = "$http"."?entry=$entry_id";
}
$data_e2t = #mysql_query("SELECT e2t.tag_id FROM core_entry2tag e2t WHERE e2t.entry_id = $entry_id");
$tag_str = "";
while($e2t = #mysql_fetch_array($data_e2t)) {
$tag_id = $e2t["tag_id"];
$data_tags = #mysql_query("SELECT t.tag_text FROM core_tags t WHERE t.tag_id = $tag_id");
while($t = #mysql_fetch_array($data_tags)) {
$tag_text = $t["tag_text"];
$tag_str = $tag_str . "<a class=\"tag-link\" name=\"tag".$tag_id."\" href=\"#tag-"._encode($tag_text)."\">".$tag_text."</a>".$separator_tags;
}
}
$entry_tags = substr($tag_str,0,strlen($tag_str)-strlen($separator_tags));
$layout_path = $root . "user/uploads/" . treat_string($entry_title) . "/layout.php";
if(is_file($layout_path) && (#filesize($layout_path) > 0)) {
require($layout_path);
} else {
require($theme_path . "parts/entry.php");
}
}
mysql_query("UPDATE core_entries e SET
e.hits = $entry_hits
WHERE e.entry_id = $id");
}
if($isPerma) {
echo "<a class=\"index-link\" href=\"$http\">back to index</a>";
}
?>
You have not defined $data_entries, before using it here:
while($tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC)){
array_push($navArr,$tmparray['entry_id']);
}
That is why you get the very descriptive error message.
Did you mean to use $data_tags?
Use: "SELECT p.* FROM core_pages p WHERE p.page_title = '".$id."'
Note: mysql_connect is not sql-injection save. If you use mysql_connect, change to PDO.
$data_entries is not defined on line 50, then mysql_fetch_array return an exception of null value given.
Try to change $tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC) to $tmparray = mysql_fetch_array($data_tags,MYSQL_ASSOC).
Hope this help!

Uploading .csv file with include and exclude row and col

Is it possible to remove extra rows when uploading in .csv file in PHP or removing specific words?
Please take a look at my screen shot. I want to exclude those encircled when I process uploading in MySQL.
Full Size
Here's my code found over the net.
<?php
$message = null;
$allowed_extensions = array('csv');
$upload_path = '';
if (!empty($_FILES['file'])) {
if ($_FILES['file']['error'] == 0) {
// check extension
$file = explode(".", $_FILES['file']['name']);
$extension = array_pop($file);
if (in_array($extension, $allowed_extensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_path.'/'.$_FILES['file']['name'])) {
if (($handle = fopen($upload_path.'/'.$_FILES['file']['name'], "r")) !== false) {
$keys = array();
$out = array();
$insert = array();
$line = 1;
while (($row = fgetcsv($handle, 0, ',', '"')) !== FALSE) {
foreach($row as $key => $value) {
if ($line === 1) {
$keys[$key] = $value;
} else {
$out[$line][$key] = $value;
}
}
$line++;
}
fclose($handle);
if (!empty($keys) && !empty($out)) {
$db = new PDO('mysql:host=localhost;dbname=attendance', 'root', 'root');
$db->exec("SET CHARACTER SET utf8");
foreach($out as $key => $value) {
$sql = "INSERT INTO `report` (`";
$sql .= implode("`, `", $keys);
$sql .= "`) VALUES (";
$sql .= implode(", ", array_fill(0, count($keys), "?"));
$sql .= ")";
$statement = $db->prepare($sql);
$statement->execute($value);
}
$message = '<span class="green">File has been uploaded successfully</span>';
}
}
}
} else {
$message = '<span class="red">Only .csv file format is allowed</span>';
}
} else {
$message = '<span class="red">There was a problem with your file</span>';
}
}
?>
Well, without more info - it looks like the rows you want to exclude have less rows than the others (I'm assuming you don't want the blank rows either).
You can use the function
$arr= str_getcsv();
to read a line of CSV data into an array the do
if(sizeof($arr)!=$validCount)
on the resulting array you get to exclude lines not of a certain length ($validCount).
Obviously we could get much more in depth for exclusion, but I'm guessing this will get your started.
Note - this requires PHP5.3 or greater.
HTH
R

Categories