Search Results

Search found 468 results on 19 pages for 'substr'.

Page 7/19 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Insert array to mysql database php

    - by ganjan
    Hi. I want to add an array to my db. I have set up a function that checks if a value in the db (ex. health and money) has changed. If the value is diffrent from the original I add the new value to the $db array. Like this $db['money'] = $money_input + $money_db;. function modify_user_info($conn, $money_input, $health_input){ (...) if ($result = $conn->query($query)) { while ($user = $result->fetch_assoc()) { $money_db = $user["money"]; $health_db = $user["health"]; } $result->close(); //lag array til db med kolonnene som skal fylles ut som keys i array if ($user["money"] != $money_input){ $db['money'] = $money_input + $money_db; //0 - 20 if (!preg_match("/^[[0-9]{0,20}$/i", $db['money'])){ echo "error"; return false; } } if ($user["health"] != $health_input){ $db['health'] = $health_input + $health_db; //0 - 4 if (!preg_match("/^[[0-9]{0,4}$/i", $db['health'])){ echo "error"; return false; } if (($db['health'] < 1) or ($db['health'] > 1000)) { echo "error"; return false; } } The keys in $db represent colums in my database. Now I want to make a function that takes the keys in the array $db and insert them in the db. Something like this ? $query = "INSERT INTO `main_log` ( `id` , "; foreach(range(0, x) as $num) { $query .= array_key.", "; } $query = substr($query, 0, -3); $query .= " VALUES ('', "; foreach(range(0, x) as $num) { $query .= array_value.", "; } $query = substr($query, 0, -3); $query .= ")";

    Read the article

  • replace a random word of a string with a random replacement

    - by tpickett
    I am developing a script that takes an article, searches the article for a "keyword" and then randomly replaces that keyword with an anchor link. I have the script working as it should, however I need to be able to have an array of "replacements" for the function to loop through and insert at the random location. So the first random position would get anchor link #1. The second random position would get anchor link #2. The third random position would get anchor link #3. etc... I found half of the answer to my question here: PHP replace a random word of a string public function replace_random ($str, $search, $replace, $n) { // Get all occurences of $search and their offsets within the string $count = preg_match_all('/\b'.preg_quote($search, '/').'\b/', $str, $matches, PREG_OFFSET_CAPTURE); // Get string length information so we can account for replacement strings that are of a different length to the search string $searchLen = strlen($search); $diff = strlen($replace) - $searchLen; $offset = 0; // Loop $n random matches and replace them, if $n < 1 || $n > $count, replace all matches $toReplace = ($n < 1 || $n > $count) ? array_keys($matches[0]) : (array) array_rand($matches[0], $n); foreach ($toReplace as $match) { $str = substr($str, 0, $matches[0][$match][1] + $offset).$replace.substr($str, $matches[0][$match][1] + $searchLen + $offset); $offset += $diff; } return $str; } So my question is, How can i alter this function to accept an array for the $replace variable?

    Read the article

  • Sorting and Pagination does not work after I build a custom keyword search that is build using relat

    - by Roland
    I recently started to build a custom keyword search using Yii 1.1.x The search works 100%. But as soon as I sort the columns and use pagination in the admin view the search gets lost and all results are shown. So with otherwords it's not filtering so that only the search results show. Somehow it resets it. In my controller my code looks as follows $builder=Messages::model()->getCommandBuilder(); //Table1 Columns $columns1=array('0'=>'id','1'=>'to','2'=>'from','3'=>'message','4'=>'error_code','5'=>'date_send'); //Table 2 Columns $columns2=array('0'=>'username'); //building the Keywords $keywords = explode(' ',$_REQUEST['search']); $count=0; foreach($keywords as $key){ $kw[$count]=$key; ++$count; } $keywords=$kw; $condition1=$builder->createSearchCondition(Messages::model()->tableName(),$columns1,$keywords,$prefix='t.'); $condition2=$builder->createSearchCondition(Users::model()->tableName(),$columns2,$keywords); $condition = substr($condition1,0,-1) . " OR ".substr($condition2,1); $condition = str_replace('AND','OR',$condition); $dataProvider=new CActiveDataProvider('Messages', array( 'pagination'=>array( 'pageSize'=>self::PAGE_SIZE, ), 'criteria'=>array( 'with'=>'users', 'together'=>true, 'joinType'=>'LEFT JOIN', 'condition'=>$condition, ), 'sort'=>$sort, )); $this->render('admin',array( 'dataProvider'=>$dataProvider,'keywords'=>implode(' ',$keywords),'sort'=>$sort )); and my view looks like this $this->widget('zii.widgets.grid.CGridView', array( 'dataProvider'=>$dataProvider, 'columns'=>array( 'id', array( 'name'=>'user_id', 'value'=>'CHtml::encode(Users::model()->getReseller($data->user_id))', 'visible'=>Yii::app()->user->checkAccess('poweradministrator') ), 'to', 'from', 'message', /* 'date_send', */ array( 'name'=>'error_code', 'value'=>'CHtml::encode($data->status($data->error_code))', ), array( 'class'=>'CButtonColumn', 'template'=>'{view} {delete}', ), ), )); I really do not know what do do anymore since I'm terribly lost, any help will be hihsly appreciated

    Read the article

  • comma separated values in oracle function body

    - by dmitry
    I've got following oracle function but it does not work and errors out. I used Ask Tom's way to convert comma separated values to be used in select * from table1 where col1 in <> declared in package header: TYPE myTableType IS table of varchar2 (255); Part of package body: l_string long default iv_value_with_comma_separated|| ','; l_data myTableType := myTableType(); n NUMBER; begin begin LOOP EXIT when l_string is null; n := instr( l_string, ',' ); l_data.extend; l_data(l_data.count) := ltrim( rtrim( substr( l_string, 1, n-1 ) ) ); l_string := substr( l_string, n+1 ); END LOOP; end; OPEN my_cursor FOR select * from table_a where column_a in (select * from table (l_data)); CLOSE my_cursor END; above fails but it works fine when I remove select * from table (l_data) Can someone please tell me what I might be doing wrong here??

    Read the article

  • Finding multiple values in a string Jquery / Javascript

    - by user257503
    I have a three strings of categories "SharePoint,Azure,IT"; "BizTalk,Finance"; "SharePoint,Finance"; I need to find a way to check if a string contains for example "SharePoint" and "IT", or "BizTalk" and "Finance". The tests are individual strings themselces. How would i loop through all the category strings (1 - 3) and only return the ones which have ALL instances of the souce. i have tried the following function doesExist(source, filterArray) { var substr = filterArray.split(" "); jQuery.each(substr, function() { var filterTest = this; if(source.indexOf(filterTest) != -1 ) { alert("true"); return true; }else { alert("false"); return false; } }); } with little success...the code above checks one at a time rather than both so the results returned are incorrect. Any help would be great. Thanks Chris UPDATE: here is a link to a work in progress version..http://www.invisiblewebdesign.co.uk/temp/filter/#

    Read the article

  • jQuery / Loading content into div and changing url's (working but buggy)

    - by Bruno
    This is working, but I'm not being able to set an index.html file on my server root where i can specify the first page to go. It also get very buggy in some situations. Basically it's a common site (menu content) but the idea is to load the content without refreshing the page, defining the div to load the content, and make each page accessible by the url. One of the biggest problems here it's dealing with all url situations that may occur. The ideal would be to have a rel="divToLoadOn" and then pass it on my loadContent() function... so I would like or ideas/solutions for this please. Thanks in advance! //if page comes from URL if(window.location.hash != ''){ var url = window.location.hash; url = '..'+url.substr(1, url.length); loadContent(url); } //if page comes from an internal link $("a:not([target])").click(function(e){ e.preventDefault(); var url = $(this).attr("href"); if(url != '#'){ loadContent($(this).attr("href")); } }); //LOAD CONTENT function loadContent(url){ var contentContainer = $("#content"); //set load animation $(contentContainer).ajaxStart(function() { $(this).html('loading...'); }); $.ajax({ url: url, dataType: "html", success: function(data){ //store data globally so it can be used on complete window.data = data; }, complete: function(){ var content = $(data).find("#content").html(); var contentTitle = $(data).find("title").text(); //change url var parsedUrl = url.substr(2,url.length) window.location.hash = parsedUrl; //change title var titleRegex = /(.*)<\/title/.exec(data); contentTitle = titleRegex[1]; document.title = contentTitle; //renew content $(contentContainer).fadeOut(function(){ $(this).html(content).fadeIn(); }); }); }

    Read the article

  • Why is this MySQL INSERT INTO running twice?

    - by stuboo
    I'm attempting to use the mysql insert statement below to add information to a database table. When I execute the script, however, the insert statement is run twice. Here's the URL mysite.com/save.php?Body=p220,c180 Thanks in advance. <?php //tipping fees application require('base.inc.php'); require('functions.inc.php'); // connect to the database & save this message there try { $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass); //$number = formatPhone($_REQUEST['From']); //if($number != 'xxx-xxx-xxxx'){die('SMS from unknown number');} // kill this if from anyone but mike $message = $_REQUEST['Body']; //$Sid = $_REQUEST['SmsSid']; $now = time(); echo $message; $message = explode(",",$message); echo '<pre>'; print_r($message); echo 'message count = '.count($message); echo '</pre>'; $i = 0; $j = count($message); while($i<$j){ $quantity =$message[$i]; $material = substr($quantity, 0, 1); $amount = substr($quantity, 1); switch ($material) { case 'p': $m = "paper"; break; case 'c': $m = "containers"; break; default: $m = "other"; } $count = $dbh->exec("INSERT INTO tippingtotals(sid,time,material,weight) VALUES('$i+$j','$now','$m','$amount')"); echo $count; echo '<br />'; $i++; } //close the database connection $dbh = null; } catch(PDOException $e) { echo $e->getMessage(); } ?>

    Read the article

  • no instance of overloaded function getline c++

    - by Dave
    I'm a bit confused as to what i have incorrect with my script that is causing this error. I have a function which calls a fill for game settings but it doesn't like my getline. Also i should mention these are the files i have included for it: #include <fstream> #include <cctype> #include <map> #include <iostream> #include <string> #include <algorithm> #include <vector> using namespace std;' This is what i have: std::map<string, string> loadSettings(std::string file){ ifstream file(file); string line; std::map<string, string> config; while(std::getline(file, line)) { int pos = line.find('='); if(pos != string::npos) { string key = line.substr(0, pos); string value = line.substr(pos + 1); config[trim(key)] = trim(value); } } return (config); } The function is called like this from my main.cpp //load settings for game std::map<string, string> config = loadSettings("settings.txt"); //load theme for game std::map<string, string> theme = loadSettings("theme.txt"); Where did i go wrong ? Please help! The error: settings.h(61): error C2784: 'std::basic_istream<_Elem,_Traits> &std::getline(std::basic_istream<_Elem,_Traits> &&,std::basic_string<_Elem,_Traits,_Alloc> &)' : could not deduce template argument for 'std::basic_istream<_Elem,_Traits> &&' from 'std::string'

    Read the article

  • How do I call this function in CodeIgniter controller?

    - by Jason Shultz
    I've got this code, but I'm not sure I make it work: /** * Function: youtube data grabber * * @description : * @param $ : video code, url type (embed/url) * @return : data array * @author : Mamun. * @last -modified-by: Mamun. */ if (! function_exists('youtube_data_grabber')) { function youtube_data_grabber($video_code, $link_type = "embed") { if ($video_code != '') { if ($link_type == "embed") { $splited_data = explode("=",$video_code); $video_unique_code = substr(strrchr($splited_data[4],"/"),1,-strlen(strrchr($splited_data[4],"&"))); } else if ($link_type == "url") { $splited_data = explode("=",$video_code); $video_unique_code = substr($splited_data[1],0,-strlen(strrchr($splited_data[1],"&"))); } else { return; } // set feed URL $feedURL = 'http://gdata.youtube.com/feeds/api/videos/'.$video_unique_code; // read feed into SimpleXML object $sxml = simplexml_load_file($feedURL); return $sxml; } } } // End Youtube Function I'm not sure how to activate it is what I'm trying to say. I placed it in the controller and it's within a function for one of my pages. I don't have any syntax errors. I just don't know how to wake it up and make it work. I thought I could just put youtube_data_grabber('http://www.youtube.com/watch?v=LAcrFym10ZI', 'url'); but that didn't work. I got the code from here: http://bit.ly/b7YnDt and I have the zend functionality working. I tested it earlier and had no errors. I'm just having trouble with this youtube part. Any ideas?

    Read the article

  • got undefined variable in php code

    - by Newbie New
    I got a error message when I run my php however the result is come out this is my code function cart() { foreach($_SESSION as $name => $value) { if ($value>0) { if (substr($name, 0, 5) == 'cart_'){ $id = substr($name, 5, (strlen($name)-5)); $get = mysql_query('SELECT id, name, price FROM products WHERE id=' .mysql_real_escape_string((int)$id)); while ($get_row = mysql_fetch_assoc($get)){ $sub = $get_row['price'] * $value; echo $get_row['name'].' x '.$value.' @ &pound'.number_format($get_row['price'], 2).' = &pound'.number_format($sub, 2).' <a href="cart.php?remove='.$id.'">[-]</a> <a href="cart.php?add='.$id.'">[+]</a> <a href="cart.php?delete='.$id.'">[Delete]</a><br />' ; } } $total += $sub; } } echo $total; } ?> I got a error message Notice: Undefined variable: total in C:\xampp\htdocs\shoppingcart\cart.php on line 54 which line 54 is echo $total; what's wrong with my code?? I think I have defined the code in $total += $sub; thanks for helping me :)

    Read the article

  • Should I change $_REQUEST to $_POST

    - by Scarface
    Hey guys quick question, I have a checkbox system where a list of items can be checked and deleted on the click of a button. I currently use request and it does the job but I was wondering if $_REQUEST was some sort of security risk or improper. If anyone has any advice I would appreciate it. Should I change to $_POST? If so, what is the best way to go about it? foreach ($_REQUEST as $key=>$value) { if (substr($key,0,3)==="img") { $id = substr($key,3); if(isset($_REQUEST['Delete'])) { $sql = 'SELECT file_name,username FROM images WHERE id=?'; $stmt = $conn->prepare($sql); $result=$stmt->execute(array($id)); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $image=$row['file_name']; $user=$row['username']; $myFile = "$user/images/$image"; unlink($myFile); } <input id=\"img".$id."\" name=\"img".$id."\" type=\"checkbox\">

    Read the article

  • Coffeescript getting proper scope from callback method

    - by pandabrand
    I've searched for this and can't seem to find an successful answer, I'm using a jQuerey ajax call and I can't get the response out to the callback. Here's my coffeescript code: initialize: (@blog, @posts) -> _url = @blog.url _simpleName = _url.substr 7, _url.length _avatarURL = exports.tumblrURL + _simpleName + 'avatar/128' $.ajax url: _avatarURL dataType: "jsonp" jsonp: "jsonp" (data, status) => handleData(data) handleData: (data) => console.log data @avatar = data Here's the compiled JS: Blog.prototype.initialize = function(blog, posts) { var _avatarURL, _simpleName, _url, _this = this; this.blog = blog; this.posts = posts; _url = this.blog.url; _simpleName = _url.substr(7, _url.length); _avatarURL = exports.tumblrURL + _simpleName + 'avatar/128'; return $.ajax({ url: _avatarURL, dataType: "jsonp", jsonp: "jsonp" }, function(data, status) { return handleData(data); }); }; Blog.prototype.handleData = function(data) { console.log(data); return this.avatar = data; }; I've tried a dozen variations and I can't figure out how to write this? Thanks.

    Read the article

  • php:: apply backticks to first word in sentence

    - by Hailwood
    Hi guys, basically what I am trying to do is, I have an array that looks something like this: array( array( 'select' =>'first string', 'escape' => true ), array( 'select' =>'second', 'escape' => true ), array( 'select' =>'the third string', 'escape' => true ), array( 'select' =>'fourth string', 'escape' => false ), ) I am looping over it and I want to end up with this output array( array( 'select' =>'`first` string', 'escape' => true ), array( 'select' =>'`second`', 'escape' => true ), array( 'select' =>'`the` third string', 'escape' => true ), array( 'select' =>'fourth string', 'escape' => false ), ) so basic rules are backticks are only applied if escape is true backticks are only applied to the first word in a sentence if there is only one word backticks are applied to the word My plan was to use if($item['escape']) { $pos = (strpos($item['select'], ' ') === false ? strlen($item['select']) : strpos($item['select'], ' ')); $item['select'] = '`' . substr($item['select'], 0, $pos) . '`' . substr($item['select'], $pos, strlen($item['select'])); } but the $item['select'] = line seems rather long winded, is there a better way to write it?

    Read the article

  • Problem with mysql_query() ;Says resource expected .

    - by user364651
    I have this php file. The lines marked as bold are showing up the error :"mysql_query() expecets parameter 2 to be a resources. Well, the similar syntax on the line on which I have commented 'No error??' is working just fine. function checkAnswer($answerEntered,$quesId) { //This functions checks whether answer to question having ques_id = $quesId is satisfied by $answerEntered or not $sql2="SELECT keywords FROM quiz1 WHERE ques_id=$quesId"; **$result2=mysql_query($sql2,$conn);** $keywords=explode(mysql_result($result2,0)); $matches=false; foreach($keywords as $currentKeyword) { if(strcasecmp($currentKeyword,$answerEntered)==0) { $matches=true; } } return $matches; } $sql="SELECT answers FROM user_info WHERE user_id = $_SESSION[user_id]"; $result=mysql_query($sql,$conn); // No error?? $answerText=mysql_result($result,0); //Retrieve answers entered by the user $answerText=str_replace('<','',$answerText); $answerText=str_replace('>',',',$answerText); $answerText=substr($answerText,0,(strlen($answerText)-1)); $answers=explode(",",$answerText); //Get the questions that have been assigned to the user. $sql1="SELECT questions FROM user_info WHERE user_id = $_SESSION[user_id]"; **$result1=mysql_query($sql1,$conn);** $quesIdList=mysql_result($result1,0); $quesIdList=substr($quesIdList,0,(strlen($quesIdList)-1)); $quesIdArray=explode(",",$quesIdList); $reportCard=""; $i=0; foreach($quesIdArray as $currentQuesId) { $answerEnteredByUser=$answers[$i]; if(checkAnswer($answerEnteredByUser,$currentQuesId)) { $reportCard=$reportCard+"1"; } else { $reportCard=$reportCard+"0"; } $i++; } echo $reportCard; ?> Here is the file connect.php. It is working just fine for other PHP documents. <?php $conn= mysql_connect("localhost","root","password"); mysql_select_db("quiz",$conn); ?>

    Read the article

  • PHP looping problem?

    - by NeVeR
    I'm trying to display the first row in one color and the second row in another color but my code displays the result twice in both colors for example lets say I have 5 results my code will double the results by displaying 10 results. How can I fix this problem? Here is the php code. while ($row = mysqli_fetch_assoc($dbc)) { //first row echo '<h3 class="title"><a href="#" title="">' . $row['title'] .'</a></h3>'; echo '<div class="summary"><a href="#" title="">' . substr($row['content'],0,255) . '</a></div>'; //second row echo '<h3 class="title-2"><a href="#" title="">' . $row['title'] .'</a></h3>'; echo '<div class="summary-2"><a href="#" title="">' . substr($row['content'],0,255) . '</a></div>'; }

    Read the article

  • Save Cookies, Then Open Link in New Tab

    - by speedplane
    I have some javascript code that saves a cookie. However, if after saving the cookie, the user opens a new tab, it appears that the cookie is not saved. The new tab is on the same domain. Here is my cookie setting/getting code: function setCookie(c_name,value,exdays) { var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); document.cookie=c_name + "=" + c_value; } function getCookie(c_name) { var i,x,y,ARRcookies=document.cookie.split(";"); for (i=0;i<ARRcookies.length;i++) { x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1); x=x.replace(/^\s+|\s+$/g,""); if (x==c_name) { return unescape(y); } } } If some javascript calls setCookie('mycookie', 1) and then the user clicks on a link where the _target is set to _blank, the cookie does not load in the new tab. So getCookie('mycookie') will not return 1. What is the problem here?

    Read the article

  • CBO????????

    - by Liu Maclean(???)
    ???Itpub????????CBO??????????, ????????: SQL> create table maclean1 as select * from dba_objects; Table created. SQL> update maclean1 set status='INVALID' where owner='MACLEAN'; 2 rows updated. SQL> commit; Commit complete. SQL> create index ind_maclean1 on maclean1(status); Index created. SQL> exec dbms_stats.gather_table_stats('SYS','MACLEAN1',cascade=>true); PL/SQL procedure successfully completed. SQL> explain plan for select * from maclean1 where status='INVALID'; Explained. SQL> set linesize 140 pagesize 1400 SQL> select * from table(dbms_xplan.display()); PLAN_TABLE_OUTPUT --------------------------------------------------------------------------- Plan hash value: 987568083 ------------------------------------------------------------------------------ | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time | ------------------------------------------------------------------------------ | 0 | SELECT STATEMENT | | 11320 | 1028K| 85 (0)| 00:00:02 | |* 1 | TABLE ACCESS FULL| MACLEAN1 | 11320 | 1028K| 85 (0)| 00:00:02 | ------------------------------------------------------------------------------ Predicate Information (identified by operation id): --------------------------------------------------- 1 - filter("STATUS"='INVALID') 13 rows selected. 10053 trace Access path analysis for MACLEAN1 *************************************** SINGLE TABLE ACCESS PATH   Single Table Cardinality Estimation for MACLEAN1[MACLEAN1]   Column (#10): STATUS(     AvgLen: 7 NDV: 2 Nulls: 0 Density: 0.500000   Table: MACLEAN1  Alias: MACLEAN1     Card: Original: 22639.000000  Rounded: 11320  Computed: 11319.50  Non Adjusted: 11319.50   Access Path: TableScan     Cost:  85.33  Resp: 85.33  Degree: 0       Cost_io: 85.00  Cost_cpu: 11935345       Resp_io: 85.00  Resp_cpu: 11935345   Access Path: index (AllEqRange)     Index: IND_MACLEAN1     resc_io: 185.00  resc_cpu: 8449916     ix_sel: 0.500000  ix_sel_with_filters: 0.500000     Cost: 185.24  Resp: 185.24  Degree: 1   Best:: AccessPath: TableScan          Cost: 85.33  Degree: 1  Resp: 85.33  Card: 11319.50  Bytes: 0 ?????10053????????????,?????Density = 0.5 ?? 1/ NDV ??? ??????????????STATUS='INVALID"???????????, ????????????????? ????”STATUS”=’INVALID’ condition???2?,?status??????,??????dbms_stats?????????????,???CBO????INDEX Range ind_maclean1,???????,??????opitimizer?????? ?????????????????????????,????????,??????????status=’INVALID’???????card??,????????: [oracle@vrh4 ~]$ sqlplus / as sysdba SQL*Plus: Release 11.2.0.2.0 Production on Mon Oct 17 19:15:45 2011 Copyright (c) 1982, 2010, Oracle. All rights reserved. Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production With the Partitioning, OLAP, Data Mining and Real Application Testing options SQL> select * from v$version; BANNER -------------------------------------------------------------------------------- Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production PL/SQL Release 11.2.0.2.0 - Production CORE 11.2.0.2.0 Production TNS for Linux: Version 11.2.0.2.0 - Production NLSRTL Version 11.2.0.2.0 - Production SQL> show parameter optimizer_fea NAME TYPE VALUE ------------------------------------ ----------- ------------------------------ optimizer_features_enable string 11.2.0.2 SQL> select * from global_name; GLOBAL_NAME -------------------------------------------------------------------------------- www.oracledatabase12g.com & www.askmaclean.com SQL> drop table maclean; Table dropped. SQL> create table maclean as select * from dba_objects; Table created. SQL> update maclean set status='INVALID' where owner='MACLEAN'; 2 rows updated. SQL> commit; Commit complete. SQL> create index ind_maclean on maclean(status); Index created. SQL> exec dbms_stats.gather_table_stats('SYS','MACLEAN',cascade=>true, method_opt=>'FOR ALL COLUMNS SIZE 2'); PL/SQL procedure successfully completed. ???????2?bucket????, ??????????????? ???Quest???Guy Harrison???????FREQUENCY????????,??????: rem rem Generate a histogram of data distribution in a column as recorded rem in dba_tab_histograms rem rem Guy Harrison Jan 2010 : www.guyharrison.net rem rem hexstr function is from From http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:707586567563 set pagesize 10000 set lines 120 set verify off col char_value format a10 heading "Endpoint|value" col bucket_count format 99,999,999 heading "bucket|count" col pct format 999.99 heading "Pct" col pct_of_max format a62 heading "Pct of|Max value" rem col endpoint_value format 9999999999999 heading "endpoint|value" CREATE OR REPLACE FUNCTION hexstr (p_number IN NUMBER) RETURN VARCHAR2 AS l_str LONG := TO_CHAR (p_number, 'fm' || RPAD ('x', 50, 'x')); l_return VARCHAR2 (4000); BEGIN WHILE (l_str IS NOT NULL) LOOP l_return := l_return || CHR (TO_NUMBER (SUBSTR (l_str, 1, 2), 'xx')); l_str := SUBSTR (l_str, 3); END LOOP; RETURN (SUBSTR (l_return, 1, 6)); END; / WITH hist_data AS ( SELECT endpoint_value,endpoint_actual_value, NVL(LAG (endpoint_value) OVER (ORDER BY endpoint_value),' ') prev_value, endpoint_number, endpoint_number, endpoint_number - NVL (LAG (endpoint_number) OVER (ORDER BY endpoint_value), 0) bucket_count FROM dba_tab_histograms JOIN dba_tab_col_statistics USING (owner, table_name,column_name) WHERE owner = '&owner' AND table_name = '&table' AND column_name = '&column' AND histogram='FREQUENCY') SELECT nvl(endpoint_actual_value,endpoint_value) endpoint_value , bucket_count, ROUND(bucket_count*100/SUM(bucket_count) OVER(),2) PCT, RPAD(' ',ROUND(bucket_count*50/MAX(bucket_count) OVER()),'*') pct_of_max FROM hist_data; WITH hist_data AS ( SELECT endpoint_value,endpoint_actual_value, NVL(LAG (endpoint_value) OVER (ORDER BY endpoint_value),' ') prev_value, endpoint_number, endpoint_number, endpoint_number - NVL (LAG (endpoint_number) OVER (ORDER BY endpoint_value), 0) bucket_count FROM dba_tab_histograms JOIN dba_tab_col_statistics USING (owner, table_name,column_name) WHERE owner = '&owner' AND table_name = '&table' AND column_name = '&column' AND histogram='FREQUENCY') SELECT hexstr(endpoint_value) char_value, bucket_count, ROUND(bucket_count*100/SUM(bucket_count) OVER(),2) PCT, RPAD(' ',ROUND(bucket_count*50/MAX(bucket_count) OVER()),'*') pct_of_max FROM hist_data ORDER BY endpoint_value; ?????,??????????FREQUENCY?????: ??dbms_stats ?????STATUS=’INVALID’ bucket count=9 percent = 0.04 ,??????10053 trace????????: SQL> explain plan for select * from maclean where status='INVALID'; Explained. SQL>  select * from table(dbms_xplan.display()); PLAN_TABLE_OUTPUT ------------------------------------- Plan hash value: 3087014066 ------------------------------------------------------------------------------------------- | Id  | Operation                   | Name        | Rows  | Bytes | Cost (%CPU)| Time     | ------------------------------------------------------------------------------------------- |   0 | SELECT STATEMENT            |             |     9 |   837 |     2   (0)| 00:00:01 | |   1 |  TABLE ACCESS BY INDEX ROWID| MACLEAN     |     9 |   837 |     2   (0)| 00:00:01 | |*  2 |   INDEX RANGE SCAN          | IND_MACLEAN |     9 |       |     1   (0)| 00:00:01 | ------------------------------------------------------------------------------------------- Predicate Information (identified by operation id): ---------------------------------------------------    2 - access("STATUS"='INVALID') ??????????????CBO???????STATUS=’INVALID’?cardnality?? , ??????????? ,??index range scan??Full table scan? ????????????????10053 trace: SQL> alter system flush shared_pool; System altered. SQL> oradebug setmypid; Statement processed. SQL> oradebug event 10053 trace name context forever ,level 1; Statement processed. SQL> explain plan for select * from maclean where status='INVALID'; Explained. SINGLE TABLE ACCESS PATH Single Table Cardinality Estimation for MACLEAN[MACLEAN] Column (#10): NewDensity:0.000199, OldDensity:0.000022 BktCnt:22640, PopBktCnt:22640, PopValCnt:2, NDV:2 ???NewDensity= bucket_count / SUM(bucket_count) /2 Column (#10): STATUS( AvgLen: 7 NDV: 2 Nulls: 0 Density: 0.000199 Histogram: Freq #Bkts: 2 UncompBkts: 22640 EndPtVals: 2 Table: MACLEAN Alias: MACLEAN Card: Original: 22640.000000 Rounded: 9 Computed: 9.00 Non Adjusted: 9.00 Access Path: TableScan Cost: 85.30 Resp: 85.30 Degree: 0 Cost_io: 85.00 Cost_cpu: 10804625 Resp_io: 85.00 Resp_cpu: 10804625 Access Path: index (AllEqRange) Index: IND_MACLEAN resc_io: 2.00 resc_cpu: 20763 ix_sel: 0.000398 ix_sel_with_filters: 0.000398 Cost: 2.00 Resp: 2.00 Degree: 1 Best:: AccessPath: IndexRange Index: IND_MACLEAN Cost: 2.00 Degree: 1 Resp: 2.00 Card: 9.00 Bytes: 0 ???????????2 bucket?????CBO????????????,???????????????????,???dbms_stats.DEFAULT_METHOD_OPT????????????????????? ???dbms_stats?????????????????????col_usage$??????predicate???????,??col_usage$??<????????SMON??(?):??col_usage$????>? ??????????dbms_stats????????,col_usage$????????????predicate???,??dbms_stats??????????????????, ?: SQL> drop table maclean; Table dropped. SQL> create table maclean as select * from dba_objects; Table created. SQL> update maclean set status='INVALID' where owner='MACLEAN'; 2 rows updated. SQL> commit; Commit complete. SQL> create index ind_maclean on maclean(status); Index created. ??dbms_stats??method_opt??maclean? SQL> exec dbms_stats.gather_table_stats('SYS','MACLEAN'); PL/SQL procedure successfully completed. @histogram.sql Enter value for owner: SYS old  12:    WHERE owner = '&owner' new  12:    WHERE owner = 'SYS' Enter value for table: MACLEAN old  13:      AND table_name = '&table' new  13:      AND table_name = 'MACLEAN' Enter value for column: STATUS old  14:      AND column_name = '&column' new  14:      AND column_name = 'STATUS' no rows selected ????col_usage$?????,????????status????? declare begin for i in 1..500 loop execute immediate ' alter system flush shared_pool'; DBMS_STATS.FLUSH_DATABASE_MONITORING_INFO; execute immediate 'select count(*) from maclean where status=''INVALID'' ' ; end loop; end; / PL/SQL procedure successfully completed. SQL> select obj# from obj$ where name='MACLEAN';       OBJ# ----------      97215 SQL> select * from  col_usage$ where  OBJ#=97215;       OBJ#    INTCOL# EQUALITY_PREDS EQUIJOIN_PREDS NONEQUIJOIN_PREDS RANGE_PREDS LIKE_PREDS NULL_PREDS TIMESTAMP ---------- ---------- -------------- -------------- ----------------- ----------- ---------- ---------- ---------      97215          1              1              0                 0           0          0          0 17-OCT-11      97215         10            499              0                 0           0          0          0 17-OCT-11 SQL> exec dbms_stats.gather_table_stats('SYS','MACLEAN'); PL/SQL procedure successfully completed. @histogram.sql Enter value for owner: SYS Enter value for table: MACLEAN Enter value for column: STATUS Endpoint        bucket         Pct of value            count     Pct Max value ---------- ----------- ------- -------------------------------------------------------------- INVALI               2     .04 VALIC3           5,453   99.96  *************************************************

    Read the article

  • $_POST data returns empty when headers are > POST_MAX_SIZE

    - by Jared
    Hi Hopefully someone here might have an answer to my question. I have a basic form that contains simple fields, like name, number, email address etc and 1 file upload field. I am trying to add some validation into my script that detects if the file is too large and then rejects the user back to the form to select/upload a smaller file. My problem is, if a user selects a file that is bigger than my validation file size rule and larger than php.ini POST_MAX_SIZE/UPLOAD_MAX_FILESIZE and pushes submit, then PHP seems to try process the form only to fail on the POST_MAX_SIZE settings and then clears the entire $_POST array and returns nothing back to the form. Is there a way around this? Surely if someone uploads something than the max size configured in the php.ini then you can still get the rest of the $_POST data??? Here is my code. <?php function validEmail($email) { $isValid = true; $atIndex = strrpos($email, "@"); if (is_bool($atIndex) && !$atIndex) { $isValid = false; } else { $domain = substr($email, $atIndex+1); $local = substr($email, 0, $atIndex); $localLen = strlen($local); $domainLen = strlen($domain); if ($localLen < 1 || $localLen > 64) { // local part length exceeded $isValid = false; } else if ($domainLen < 1 || $domainLen > 255) { // domain part length exceeded $isValid = false; } else if ($local[0] == '.' || $local[$localLen-1] == '.') { // local part starts or ends with '.' $isValid = false; } else if (preg_match('/\\.\\./', $local)) { // local part has two consecutive dots $isValid = false; } else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) { // character not valid in domain part $isValid = false; } else if (preg_match('/\\.\\./', $domain)) { // domain part has two consecutive dots $isValid = false; } else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) { // character not valid in local part unless // local part is quoted if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) { $isValid = false; } } } return $isValid; } //setup post variables @$name = htmlspecialchars(trim($_REQUEST['name'])); @$emailCheck = htmlspecialchars(trim($_REQUEST['email'])); @$organisation = htmlspecialchars(trim($_REQUEST['organisation'])); @$title = htmlspecialchars(trim($_REQUEST['title'])); @$phone = htmlspecialchars(trim($_REQUEST['phone'])); @$location = htmlspecialchars(trim($_REQUEST['location'])); @$description = htmlspecialchars(trim($_REQUEST['description'])); @$fileError = 0; @$phoneError = ""; //setup file upload handler $target_path = 'uploads/'; $filename = basename( @$_FILES['uploadedfile']['name']); $max_size = 8000000; // maximum file size (8mb in bytes) NB: php.ini max filesize upload is 10MB on test environment. $allowed_filetypes = Array(".pdf", ".doc", ".zip", ".txt", ".xls", ".docx", ".csv", ".rtf"); //put extensions in here that should be uploaded only. $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename. if(!is_writable($target_path)) die('You cannot upload to the specified directory, please CHMOD it to 777.'); //Check if we can upload to the specified upload folder. //display form function function displayForm($name, $emailCheck, $organisation, $phone, $title, $location, $description, $phoneError, $allowed_filetypes, $ext, $filename, $fileError) { //make $emailCheck global so function can get value from global scope. global $emailCheck; global $max_size; echo '<form action="geodetic_form.php" method="post" name="contact" id="contact" enctype="multipart/form-data">'."\n". '<fieldset>'."\n".'<div>'."\n"; //name echo '<label for="name"><span class="mandatory">*</span>Your name:</label>'."\n". '<input type="text" name="name" id="name" class="inputText required" value="'. $name .'" />'."\n"; //check if name field is filled out if (isset($_REQUEST['submit']) && empty($name)) { echo '<label for="name" class="error">Please enter your name.</label>'."\n"; } echo '</div>'."\n". '<div>'."\n"; //Email echo '<label for="email"><span class="mandatory">*</span>Your email:</label>'."\n". '<input type="text" name="email" id="email" class="inputText required email" value="'. $emailCheck .'" />'."\n"; // check if email field is filled out and proper format if (isset($_REQUEST['submit']) && validEmail($emailCheck) == false) { echo '<label for="email" class="error">Invalid email address entered.</label>'."\n"; } echo '</div>'."\n". '<div>'."\n"; //organisation echo '<label for="phone">Organisation:</label>'."\n". '<input type="text" name="organisation" id="organisation" class="inputText" value="'. $organisation .'" />'."\n"; echo '</div>'."\n". '</fieldset>'."\n".'<fieldset>'. "\n" . '<div>'."\n"; //title echo '<label for="phone">Title:</label>'."\n". '<input type="text" name="title" id="title" class="inputText" value="'. $title .'" />'."\n"; echo '</div>'."\n". '</fieldset>'."\n".'<fieldset>'. "\n" . '<div>'."\n"; //phone echo '<label for="phone"><span class="mandatory">*</span>Phone <br /><span class="small">(include area code)</span>:</label>'."\n". '<input type="text" name="phone" id="phone" class="inputText required" value="'. $phone .'" />'."\n"; // check if phone field is filled out that it has numbers and not characters if (isset($_REQUEST['submit']) && $phoneError == "true" && empty($phone)) echo '<label for="email" class="error">Please enter a valid phone number.</label>'."\n"; echo '</div>'."\n". '</fieldset>'."\n".'<fieldset>'. "\n" . '<div>'."\n"; //Location echo '<label class="location" for="location"><span class="mandatory">*</span>Location:</label>'."\n". '<textarea name="location" id="location" class="required">'. $location .'</textarea>'."\n"; //check if message field is filled out if (isset($_REQUEST['submit']) && empty($_REQUEST['location'])) echo '<label for="location" class="error">This field is required.</label>'."\n"; echo '</div>'."\n". '</fieldset>'."\n".'<fieldset>'. "\n" . '<div>'."\n"; //description echo '<label class="description" for="description">Description:</label>'."\n". '<textarea name="description" id="queryComments">'. $description .'</textarea>'."\n"; echo '</div>'."\n". '</fieldset>'."\n".'<fieldset>'. "\n" . '<div>'."\n"; //file upload echo '<label class="uploadedfile" for="uploadedfile">File:</label>'."\n". '<input type="file" name="uploadedfile" id="uploadedfile" value="'. $filename .'" />'."\n"; // Check if the filetype is allowed, if not DIE and inform the user. switch ($fileError) { case "1": echo '<label for="uploadedfile" class="error">The file you attempted to upload is not allowed.</label>'; break; case "2": echo '<label for="uploadedfile" class="error">The file you attempted to upload is too large.</label>'; break; } echo '</div>'."\n". '</fieldset>'; //end of form echo '<div class="submit"><input type="submit" name="submit" value="Submit" id="submit" /></div>'. '<div class="clear"><p><br /></p></div>'; } //end function //setup error validations if (isset($_REQUEST['submit']) && !empty($_REQUEST['phone']) && !is_numeric($_REQUEST['phone'])) $phoneError = "true"; if (isset($_REQUEST['submit']) && $_FILES['uploadedfile']['error'] != 4 && !in_array($ext, $allowed_filetypes)) $fileError = 1; if (isset($_REQUEST['submit']) && $_FILES["uploadedfile"]["size"] > $max_size) $fileError = 2; echo "this condition " . $fileError; $POST_MAX_SIZE = ini_get('post_max_size'); $mul = substr($POST_MAX_SIZE, -1); $mul = ($mul == 'M' ? 1048576 : ($mul == 'K' ? 1024 : ($mul == 'G' ? 1073741824 : 1))); if ($_SERVER['CONTENT_LENGTH'] > $mul*(int)$POST_MAX_SIZE && $POST_MAX_SIZE) echo "too big!!"; echo $POST_MAX_SIZE; if(empty($name) || empty($phone) || empty($location) || validEmail($emailCheck) == false || $phoneError == "true" || $fileError != 0) { displayForm($name, $emailCheck, $organisation, $phone, $title, $location, $description, $phoneError, $allowed_filetypes, $ext, $filename, $fileError); echo $fileError; echo "max size is: " .$max_size; echo "and file size is: " . $_FILES["uploadedfile"]["size"]; exit; } else { //copy file from temp to upload directory $path_of_uploaded_file = $target_path . $filename; $tmp_path = $_FILES["uploadedfile"]["tmp_name"]; echo $tmp_path; echo "and file size is: " . filesize($_FILES["uploadedfile"]["tmp_name"]); exit; if(is_uploaded_file($tmp_path)) { if(!copy($tmp_path,$path_of_uploaded_file)) { echo 'error while copying the uploaded file'; } } //test debug stuff echo "sending email..."; exit; } ?> PHP is returning this error in the log: [29-Apr-2010 10:32:47] PHP Warning: POST Content-Length of 57885895 bytes exceeds the limit of 10485760 bytes in Unknown on line 0 Excuse all the debug stuff :) FTR, I am running PHP 5.1.2 on IIS. TIA Jared

    Read the article

  • Removing the last digits in string [migrated]

    - by Ruriko
    I have a string that looks like this: [APPLE PIE] Sei Shoujo Sentai Lakers 3 Battle Team Lakers 3 (100% FULL-PIC)_20121104_032834 I want to remove the digits at the end of the string, basically the 16 digits at the end of the string. In the end it should look like this: [APPLE PIE] Sei Shoujo Sentai Lakers 3 Battle Team Lakers 3 (100% FULL-PIC) This is my code that I have written so far var str="[APPLE PIE] Sei Shoujo Sentai Lakers 3 Battle Team Lakers 3 (100% FULL-PIC)_20121104_032834"; var n=str.substr(1,74); document.write(n); The problem is the string will be different so each will have different amount of characters. So how I remove the digits at the end of the string in javascript?

    Read the article

  • Yii , show tooltip in cgridview( table ) value

    - by Kiran
    I want to show tooltip in cgridview value as on hover on column it have to show whole contant stored in variable. I want to show contant in variable $data["comment"] as a tooltip ( title ), and currently it shows whole string as - $data["comment"]. array( 'name'=>'Comment', 'header'=>'Comment', 'value'=>'(strlen($data["comment"])>35)?substr($data["comment"], 0, 35)."..":$data["comment"];', 'htmlOptions'=>array('title'=>'$data["comment"]'), // this what i have do ),

    Read the article

  • convert clob to varchar2

    - by Shamik
    I have a Oracle table whose column is a CLOB datatype. I want to read the content of this table as a text. I tried select dbms_lob.substr( sqltext, 4000, 1 ) from test but this one selects only the first 4000 bytes. How to read the entire content ? there are more than 4000 characters in the sqltext column. Please advise.

    Read the article

  • Managing timezone in php with ics date/time format

    - by John
    Ok, I'm using an ICS parser utility to parse google calendar ICS files. It works great, except google is feeding me the times of the events at UCT.. so I need to subtract 5 hours now, and 6 hours when daylight savings happens. To get the start time I'm using: $timestart = date("g:iA",strtotime(substr($event['DTSTART'], 9, -3))); //$event['DTSTART'] feeds me back the date in ICS format: 20100406T200000Z So any suggestions how to handle timezone and daylight savings time? Thanks in advance

    Read the article

  • IMDB Grabber PHP

    - by user272899
    I am recieving an error: Notice: Undefined variable: content in C:\wamp\www\includes\imdbgrabber.php on line 17 When using this code: <?php //url $url = 'http://www.imdb.com/title/tt0367882/'; //get the page content $imdb_content = get_data($url); //parse for product name $name = get_match('/<title>(.*)<\/title>/isU',$imdb_content); $director = strip_tags(get_match('/<h5[^>]*>Director:<\/h5>(.*)<\/div>/isU',$imdb_content)); $plot = get_match('/<h5[^>]*>Plot:<\/h5>(.*)<\/div>/isU',$imdb_content); $release_date = get_match('/<h5[^>]*>Release Date:<\/h5>(.*)<\/div>/isU',$imdb_content); $mpaa = get_match('/<a href="\/mpaa">MPAA<\/a>:<\/h5>(.*)<\/div>/isU',$imdb_content); $run_time = get_match('/Runtime:<\/h5>(.*)<\/div>/isU',$imdb_content); //build content line 17 --> $content.= '<h2>Film</h2><p>'.$name.'</p>'; $content.= '<h2>Director</h2><p>'.$director.'</p>'; $content.= '<h2>Plot</h2><p>'.substr($plot,0,strpos($plot,'<a')).'</p>'; $content.= '<h2>Release Date</h2><p>'.substr($release_date,0,strpos($release_date,'<a')).'</p>'; $content.= '<h2>MPAA</h2><p>'.$mpaa.'</p>'; $content.= '<h2>Run Time</h2><p>'.$run_time.'</p>'; $content.= '<h2>Full Details</h2><p><a href="'.$url.'" rel="nofollow">'.$url.'</a></p>'; echo $content; //gets the match content function get_match($regex,$content) { preg_match($regex,$content,$matches); return $matches[1]; } //gets the data from a URL function get_data($url) { $ch = curl_init(); $timeout = 5; curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); $data = curl_exec($ch); curl_close($ch); return $data; } ?>

    Read the article

  • Move to next message

    - by demas
    I have a messages line this: message 1 answer 1.1 answer 1.1.1 answer 1.2 answer 1.3 massage 2 ... and I have the line in my .gnus.el: (global-set-key [f9] (lambda () (interactive) (gnus-summary-lower-score-by-subj-substr-temp))) When I select "message 1" and press F9 next lines: message1 answer 1.1 answer 1.1.1 answer 1.2 answer 1.3 change the score. But I need the selection move to next message (message 2) when I press F9. How can I get it?

    Read the article

  • Convert JSON flattened for forms back to an object

    - by George Jempty
    I am required (please therefore no nit-picking the requirement, I've already nit-picked it, and this is the req) to convert certain form fields that have "object nesting" embedded in the field names, back to the object(s) themselves. Below are some typical form field names: phones_0_patientPhoneTypeId phones_0_phone phones_1_patientPhoneTypeId phones_1_phone The form fields above were derived from an object such as the one toward the bottom (see "Data"), and that is the format of the object I need to reassemble. It can be assumed that any form field with a name that contains the underscore _ character needs to undergo this conversion. Also that the segment of the form field between underscores, if numeric, signifies a Javascript array, otherwise an object. I found it easy to devise a (somewhat naive) implementation for the "flattening" of the original object for use by the form, but am struggling going in the other direction; below the object/data below I'm pasting my current attempt. One problem (perhaps the only one?) with it is that it does not currently properly account for array indexes, but this might be tricky because the object will subsequently be encoded as JSON, which will not account for sparse arrays. So if "phones_1" exists, but "phones_0" does not, I would nevertheless like to ensure that a slot exists for phones[0] even if that value is null. Implementations that tweak what I have begun, or are entirely different, encouraged. If interested let me know if you'd like to see my code for the "flattening" part that is working. Thanks in advance Data: var obj = { phones: [{ "patientPhoneTypeId": 4, "phone": "8005551212" }, { "patientPhoneTypeId": 2, "phone": "8885551212" }]}; Code to date: var unflattened = {}; for (var prop in values) { if (prop.indexOf('_') > -1) { var lastUnderbarPos = prop.lastIndexOf('_'); var nestedProp = prop.substr(lastUnderbarPos + 1); var nesting = prop.substr(0, lastUnderbarPos).split("_"); var nestedRef, isArray, isObject; for (var i=0, n=nesting.length; i<n; i++) { if (i===0) { nestedRef = unflattened; } if (i < (n-1)) { // not last if (/^\d+$/.test(nesting[i+1])) { isArray = true; isObject = false; } else { isArray = true; isObject = false; } var currProp = nesting[i]; if (!nestedRef[currProp]) { if (isArray) { nestedRef[currProp] = []; } else if (isObject) { nestedRef[currProp] = {}; } } nestedRef = nestedRef[currProp]; } else { nestedRef[nestedProp] = values[prop]; } } }

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >