728x90
Why would the following code produce the above error the 3rd itteration?

while ($row_comp = $comp->fetch_array())
{
      $comp_count++;
      $comp_id = $row_comp['TID'];            
      $SqlString = "select * from pers where TID = \"$comp_id\"";
      echo "str = ".$SqlString."<br>";
      $pers = $conn->query($SqlString);
      while ($row_pers = $pers->fetch_array())
      {

The screen output looks like this:
str = select * from pers where TID = "10019706"
str = select * from pers where TID = "10019771"
str = select * from pers where TID = "10019779"

Fatal error: Call to a member function fetch_array() on a non-object in /home/langsyst/public_html/Lansco/Fix_Data_2A.php on line 58

Line 58 is the 2nd while
breeze351
Asked: 
breeze351
1 Solution
breeze351Author Commented: 
I forgot to add that I checked the 3rd sql statement and it does work.
Kim WalkerWeb Programmer/TechnicianCommented: 
The error means that $pers does not contain a query result possibly due to a problem with the db connection $conn. This could be a scope issue. Is the code you posted part of a function and if so, is the variable $conn defined within that same function?

Otherwise, we have another error to deal with and we need to determine what that is. Do you have error reporting turned on? If it is turned on and you're not seeing an error, please replace your code with the following and take note of the additions I've added for exposing the error. My first change is on line 7 and then I've added code after the end of the second while loop.
while ($row_comp = $comp->fetch_array())
{
      $comp_count++;
      $comp_id = $row_comp['TID'];            
      $SqlString = "select * from pers where TID = \"$comp_id\"";
      echo "str = ".$SqlString."<br>";
      if ($pers = $conn->query($SqlString) ) {
	      while ($row_pers = $pers->fetch_array()) {
	      	...
	      }
	  } else {
	  	if ($conn->error) {
	  		echo "{$conn->error}<br>SQL = $SqlString";
	  	} else {
	  		echo '$conn is a(n) '. gettype($conn);
	  	}
	  }
}

 Open in new window

Dave BaldwinFixer of ProblemsCommented: 
The usual reason is that the query failed.
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

breeze351Author Commented: 
Kim
How do I turn on the error reporting
breeze351Author Commented: 
Kim 
This is weird?!?!?!
I modified the code per your example.  I don't get an error message, however, if I keep refreshing the program, it will give me one more record before it craps out!
Kim WalkerWeb Programmer/TechnicianCommented: 
OK. This suggests that your first query is returning a TID value that doesn't exist in the pers table. In other words, the outer loop doesn't always have the right conditions for the inner loop.

To turn on error reporting, place these two lines at the beginning of your PHP page.
error_reporting(E_ALL);
ini_set('display_errors','on');

 Open in new window

breeze351Author Commented: 
I still don't get an error message other the "Fatal error....."
And again, it keeps giving me one more record before it fails.

I've attached the code.  It's small, I'm just trying to clean up some garbage data.
Thought this would be a piece of cake, after all how hard could it be!
Fix_Data_2A.php
Kim WalkerWeb Programmer/TechnicianCommented: 
Is the fatal error still on the inner while loop (line 61)?
Kim WalkerWeb Programmer/TechnicianCommented: 
One more modification (see lines 13-14, 22-24):
$comp_count = 0;
$per_count = 0;		
$SqlString = "select * from comp where ALFA = \"    \" and COMPANY = \"    \"";
$comp = $conn->query($SqlString);
while ($row_comp = $comp->fetch_array())
{
	$comp_count++;
	$comp_id = $row_comp['TID'];		
	$SqlString = "select * from pers where TID = \"$comp_id\"";
	echo "str = ".$SqlString."<br>";
	if ($pers = $conn->query($SqlString))
	{
		if ($pers->num_rows > 0)
		{
			while ($row_pers = $pers->fetch_array())
			{
				$pers_id = $row_pers['PNID'];
				$SqlString = "delete from pers where TID = '$comp_id' and PNID = '$pers_id'";
				$pers = $conn->query($SqlString);
				$per_count++;
			}
		} else {
			echo "<p>No records found for query $SqlString</p>\n";
		}
	}
	else 
	{
  		if ($conn->error) 
		{
  			echo "{$conn->error}<br>SQL = $SqlString";
	  	} 
		else 
		{
  			echo '$conn is a(n) '. gettype($conn);
  		}
	}
}

 Open in new window

breeze351Author Commented: 
No joy!
I didn't think it would work because it keeps blowing up on the while statement.
Try this yourself (I'm not worried about the data, I have backups and it's really not current).

Go to:
1: http://langsystems.net/Lansco/
(you need to do this for the session vars)
2: http://langsystems.net/Lansco/Fix_Data_2A.php

Look at the last "TID"# in the query, then refresh the page.  You'll get the next record.

There are only 234 records that match the 1st while loop.  Do I have to hit refresh 234 times? :)
Kim WalkerWeb Programmer/TechnicianCommented: 
AHAH! So the while loop iterates once then fails. It is because the while loop is attempting to read another record from the $pers result but the $pers result is being overwritten within the while loop. Change this
				$SqlString = "delete from pers where TID = '$comp_id' and PNID = '$pers_id'";
				$pers = $conn->query($SqlString);

 Open in new window

to
				$SqlString = "delete from pers where TID = '$comp_id' and PNID = '$pers_id'";
				$conn->query($SqlString);

 Open in new window

There is no need to store the results of the delete into a variable unless you need to view results such as affected_rows. If you still want to store those results, store them in a new variable instead of reusing $pers.
breeze351Author Commented: 
Thank you, Thank you!!!!!!!!!!!!!!

I just copied the $conn->query statement from code up above.  I knew how to delete the record but sometimes you can't see something so stupid.

Thank you again.
Glenn


'WEB > jQuery' 카테고리의 다른 글

PHP array_push  (0) 2018.01.14
Fatal error: Call to a member function query() on null  (0) 2018.01.14
달력 - 날짜입력기(Date Picker)  (0) 2018.01.14
javascript comma and uncomma  (0) 2018.01.14
[jQuery] following sidebar  (0) 2018.01.14
728x90
자바스크립트 날짜입력기입니다.
각종 날짜입력 폼에 타이핑 대신 사용하면 됩니다.
원래는 우체국에서 쓰던 팝업소스인데 레이어 스타일로 변경하였습니다.

테스트 :
IE8, 파이어폭스8, 크롬15, 오페라11, 사파리5

&lt;script language="JavaScript" src="date_picker.js"&gt;&lt;/script&gt; &lt;input type="text" name="target_date"&gt; &lt;input type="button" value="달력보기" onClick="datePicker(event,'target_date')"&gt; &lt;br&gt; &lt;input type="text" name="target_date"&gt; &lt;input type="button" value="달력보기" onClick="datePicker(event,'target_date',1)"&gt; 동일한 name의 타겟인 경우 세번째 인자의 키값으로 구분합니다. 세번째 인자가 생략되면 기본값은 0입니다.   
 

date_picker.js





728x90

자바스크립트에서 숫자를 표기할때 3자리마다 콤마를 찍어줘야 할 때가 있다 자주 사용하는 기능인데 매번 만들기란 여간 귀찮은게 아니다.

콤마찍기

1
2
3
4
5
//콤마찍기
function comma(str) {
    str = String(str);
    return str.replace(/(\d)(?=(?:\d{3})+(?!\d))/g, '$1,');
}

콤마풀기

1
2
3
4
5
//콤마풀기
function uncomma(str) {
    str = String(str);
    return str.replace(/[^\d]+/g, '');
}

복사 붙여넣기로 사용하자!

input box에서 사용자 입력시 바로 콤마를 찍어주기 위한 함수도 추가 한다.

1
2
3
4
5
function inputNumberFormat(obj) {
    obj.value = comma(uncomma(obj.value));
}
 
//<input type="text" onkeyup="inputNumberFormat(this)" />

 

728x90

안녕하세요. 오늘은 jQuery 스크립트를 사용해서

따라다니는 사이드바를 만들어 보겠습니다.


예전에 화면에 아예 고정되고 따라다니는 플로팅 메뉴를 만든적이 있긴한데

http://cocosoft.kr/149 - 플로팅메뉴(추천위젯,광고)

오늘은 사이드바의 메뉴 하나 또는 몇개만! 움직이는 따라다니면서 움직이는 형태를 알려드리겠습니다.


당연히 사용 전제 조건으로 jQuery 사용해야겠죠?

요즘 웬만한 스킨이나 티스토리 공식 반응형 웹 스킨등에서도 jQuery를 사용하고 있긴합니다.


완성된 예제 입니다.


스킨의 상관없이 기존 사이드바 div 태그에 값만 설정 추가 해주면

어느 사이드바에서도 사용이 가능합니다.

intro - 사이드바에 대한 고찰

요즘 티스토리에서도 반응형 웹스킨을 공식적으로 지원하고 있고


해외 포럼이나 해외 블로그, 반응형 사이트들을 살펴보면

모바일 디자인과 친화성을 위해서인지 1단 또는 2단형 반응형으로 개발 되는 경우가 많습니다.

구식 브라우저의 호환성도 높이고 깔끔한 디자인으로 포스트 본문에 집중도 잘 되는 것 같습니다.

아예 사이드바 카테고리를 숨겨놓거나 좌측이나 우측 사이드에 고정하는 방식을 많이 사용합니다.



해외 타임지 사이트도 사이드바만 따로 고정되어있는 형태고

티스토리 공식 반은형 스킨도 현재 2가지 형태를 제공하고 있습니다.


저도 이런 깔끔한 디자인이 마음에 들어서

아예 공식 스킨을 사용하거나 2단형식으로 바꿀까?도 고민중입니다.

하지만 이 형식의 단점도 존재합니다.

바로 고정된 사이드바에 광고를 게재시에 애드센스 광고 정책 위반이라는 점입니다.

position: fixed;형식으로 위치하게 되는데 이러한 사이드바 안에

광고를 집어넣게 되면 정책 위반으로 애드센스 수익과 계정이 정지 될 수 있습니다.


지금 티스토리 반응형 웹 공모전 이후 반응형 스킨들이 많이 퍼지면서

고정된 사이드바에 광고를 위치시키는 분들이 많은데

사이드바의 길이가 길어서 스크롤이 되어서 고정된 형태가 아닌 것 처럼 보여도

전부 정책 위반입니다. ㅠ_ㅠ 


저도 만약 사이드바의 애드센스 광고를 달지 않을 경우에는 해당 고정된 형태인 사이드바를 사용을 할 것 같습니다.

애드센스를 사용하시는 분들이라면 항상 정책 위반 ㅠ_ㅠ여부를 염두에 두고 해야합니다.

저도 스킨을 최근에 변경하면서 광고 정책을 위반하지 않으려고 스킨 여백 수정을 하고 있습니다.


만약 CCZ-CROSS 스킨 또는 티스토리 스킨을 사용하시는 분들중


우측이나 좌측에 고정된 형태의 사이드바를 사용하고 싶으신 분들은

SONYLOVE님의 게시글을 참고하세요!

http://sonylove.tistory.com/1132 - 티스토리 스킨 사이드바 고정하는 방법


본격적으로 시작!!!!!!!

이제 본격적으로 사이드바의 메뉴중

하나 또는 여러개만 스크롤을 내릴시 본문콘텐츠에 맞춰서

따라 내려가는 방법에 대해서 알아보겠습니다.

부드럽게 따라다니는 사이드바

우선 자바스크립트 소스를 붙혀넣기 해야됩니다.

해당소스는 http://blog.bits.kr/90 및 http://madebykaus.com/?p=300 를 참고해서

티스토리 블로그에 맞게 수정을 하였으며, 더자세한 속성값은 해당 포스트를 참고바랍니다.


html//css 수정에서 html 제일 하단 부분 </body> 에 붙혀넣기를 하면됩니다.

Markup

<script>
$(function(){
    var $win = $(window);
    var top = $(window).scrollTop(); // 현재 스크롤바의 위치값을 반환합니다.
 
    /*사용자 설정 값 시작*/
    var speed          = 500;     // 따라다닐 속도 : "slow", "normal", or "fast" or numeric(단위:msec)
    var easing         = 'linear'; // 따라다니는 방법 기본 두가지 linear, swing
    var $layer         = $('.float_sidebar'); // 레이어 셀렉팅
    var layerTopOffset = 0;   // 레이어 높이 상한선, 단위:px
    $layer.css('position', 'relative').css('z-index', '1');
    /*사용자 설정 값 끝*/
 
    // 스크롤 바를 내린 상태에서 리프레시 했을 경우를 위해
    if (top > 0 )
        $win.scrollTop(layerTopOffset+top);
    else
        $win.scrollTop(0);
 
    //스크롤이벤트가 발생하면
    $(window).scroll(function(){
        yPosition = $win.scrollTop() - 1100; //이부분을 조정해서 화면에 보이도록 맞추세요
        if (yPosition < 0)
        {
            yPosition = 0;
        }
        $layer.animate({"top":yPosition }, {duration:speed, easing:easing, queue:false});
    });
});
</script>
</body>
</html>

그리고 나서 따라다니게 하고 싶은 사이드바 모듈에

클래스 값 .float_sidebar을 넣어주면 됩니다.

Markup

<div class="float_sidebar"></div>

요런식으로 추가해도 됩니다!!


스크립트 부분에서 yPosition 수치만 잘 조절해주시면 쉽게 따라오는 메뉴를 만들 수 있습니다.

따라다니는 사이드바 메뉴도 마찬가지로 애드센스 영역을 따라다니게 해서는 안됩니다. 애드센스 광고 정책 위반입니다.


+추가 응용편)일정이상 내려가면 나타나게하기

위 방법은 사이드바 중간에 위치한 모듈도 클래스 값을 줘서 내릴 경우

사이드바의 위치 깨짐이 없이 내려가게 가능하나

보기에는 좋지 않겠죠?!ㅎㅎ

다른 사이드바 모듈을 다거치면서 내려오니깐요?


그래서 되도록이면 따라다니는 사이드바를 가장 아래 쪽으로 위치해주거나


아니면 일정 스크롤 이상 내려갔을 경우 나타나게 만들어 주면 되겠죠??

동일한 사이드바를 하나더 만들어서 가장 아래에 배치를 해주고

속성값은 display: none; 값을 줘서 보이지 않게 한 다음


아래 스크립트를 추가해서 일정 이상 내려갔을 경우 나타나게 해주면 되겠죠?


Markup

<script>
$(document).ready(function() {
    $(window).scroll(function() {
        $(this).scrollTop() > 1000 ? $(".float_sidebar").fadeIn() : $(".float_sidebar").fadeOut()
    })
});
</script>


따라다니는 사이드바 메뉴 배너 플로팅 박스들 만드는 방법은 다양하니!!

잘 참고하시면 될 것같아요.

이 방법을 응용 하시면 다양한 연출이 가능 할 것 같습니다.


굳이 부드럽게 이동하는 것을 원하지 않는 분들은 addClassremoveClass잘 사용하셔도

position:와 여백을 수정하게 해서!

고정되어 이동하는 카테고리를 잘 만들 수 있을 거라 생각합니다!!

Markup

<script>
	$(document).ready(function () {  
        var top = $('#float_sidebar').offset().top - parseFloat($('#float_sidebar').css('marginTop').replace(/auto/, 0));
        $(window).scroll(function (event) {
        var y = $(this).scrollTop();
  
       if (y >= top) {
          $('#float_sidebar').addClass('fixed');
       } else {
          $('#float_sidebar').removeClass('fixed');
      }
  });
});
</script>

이런식으로 말이죠.

결론

저도 지금 스킨을 바꾸면서 계속 수정을 하고 변경을 하고 있는 중입니다.

아예 사이드바를 고정할지

아니면 스크롤이 내리더라도 따라다니는 메뉴를 사용해서

 블로그 콘텐츠의 접근성을 높히는 방법을 사용할지


따로 addthis와 같은 추천글 플러그인을 사용해서 사용할지

(addthis는 유로 구매가 아니면 ㅠ 특정 추천글을 선택할 수 없는 아쉬움이 있습니다.)


계속 테스트를 해보고 결정을 해야 할 것 같습니다.

보조 블로그는 최신글 목록만 따라다는 사이드바를 적용 했는데

애드센스의 페이지 RPM이 소폭 증가 한 것을 알 수 있었습니다.


이것 때문이지는 모르겠지만 사이드바의 영역에 어느정도 추천 콘텐츠를 제공하는 것은

 방문객의 페이지 재방문을 조금이나마 높혀줄 수 있다고 생각합니다.!


그럼 다들 블로그에 사이드바 꾸미기를 잘하길 바라겠습니다.



출처: http://cocosoft.kr/361 [코코소프트]

출처: http://cocosoft.kr/361 [코코소프트]

출처: http://cocosoft.kr/361 [코코소프트]

출처: http://cocosoft.kr/361 [코코소프트]

+ Recent posts