728x90
자바스크립트 날짜입력기입니다.
각종 날짜입력 폼에 타이핑 대신 사용하면 됩니다.
원래는 우체국에서 쓰던 팝업소스인데 레이어 스타일로 변경하였습니다.

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

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

date_picker.js





728x90


I am running a PHP script, and keep getting errors like:

Notice: Undefined variable: my_variable_name in C:\wamp\www\mypath\index.php on line 10

Notice: Undefined index: my_index C:\wamp\www\mypath\index.php on line 11

Line 10 and 11 looks like this:

echo "My variable value is: " . $my_variable_name;
echo "My index value is: " . $my_array["my_index"];

What do these errors mean?

Why do they appear all of a sudden? I used to use this script for years and I've never had any problem.

What do I need to do to fix them?

This is a General Reference question for people to link to as duplicate, instead of having to explain the issue over and over again. I feel this is necessary because most real-world answers on this issue are very specific.

Related Meta discussion:

shareimprove this question
6 
2 
the variable might not have been initialized. Are you initializing the variable from a post or get or any array? If that's the case you might not have an field in that array. That your accessing. – ASK Dec 15 '15 at 13:12
1 
@ChrisJJ, Robbie's answer explains this very well. – Leith Nov 24 '16 at 7:29
3 
@Pekka웃 - I noticed the edit adding the "and "Notice: Undefined offset"" - Wouldn't it make more sense using "PHP: “Undefined variable”, “Undefined index”, “Undefined offset” notices" (even take out the PHP, since it is tagged as "php". Plus, the URL gets cut off at and-notice-undef, just a suggestion so that the URL doesn't get cut off. Maybe even removing the (too many) quotes. Or PHP: “Undefined variable/index/offset” notices – Funk Forty Niner Jan 20 '17 at 15:24 
2 
@Fred I guess an argument can be made for both variations. THere's a chance that newbies will enter the entire line, including the "Notice:" into their search query, which I'm sure is the main traffic generator for this question. If the messages are there in full, that's likely to improve visibility in search engines – Pekka 웃 Jan 20 '17 at 15:34 
up vote783down voteaccepted

Notice: Undefined variable

From the vast wisdom of the PHP Manual:

Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset()language construct can be used to detect if a variable has been already initialized. Additionally and more ideal is the solution of empty() since it does not generate a warning or error message if the variable is not initialized.

From PHP documentation:

No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.

This means that you could use only empty() to determine if the variable is set, and in addition it checks the variable against the following, 0,"",null.

Example:

$o = [];
@$var = ["",0,null,1,2,3,$foo,$o['myIndex']];
array_walk($var, function($v) {
    echo (!isset($v) || $v == false) ? 'true ' : 'false';
    echo ' ' . (empty($v) ? 'true' : 'false');
    echo "\n";
});

Test the above snippet in the 3v4l.org online PHP editor

Although PHP does not require a variable declaration, it does recommend it in order to avoid some security vulnerabilities or bugs where one would forget to give a value to a variable that will be used later in the script. What PHP does in the case of undeclared variables is issue a very low level error, E_NOTICE, one that is not even reported by default, but the Manual advises to allow during development.

Ways to deal with the issue:

  1. Recommended: Declare your variables, for example when you try to append a string to an undefined variable. Or use isset() / !empty() to check if they are declared before referencing them, as in:

    //Initializing variable
    $value = ""; //Initialization value; Examples
                 //"" When you want to append stuff later
                 //0  When you want to add numbers later
    //isset()
    $value = isset($_POST['value']) ? $_POST['value'] : '';
    //empty()
    $value = !empty($_POST['value']) ? $_POST['value'] : '';

    This has become much cleaner as of PHP 7.0, now you can use the null coalesce operator:

    // Null coalesce operator - No need to explicitly initialize the variable.
    $value = $_POST['value'] ?? '';
  2. Set a custom error handler for E_NOTICE and redirect the messages away from the standard output (maybe to a log file):

    set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT)
  3. Disable E_NOTICE from reporting. A quick way to exclude just E_NOTICE is:

    error_reporting( error_reporting() & ~E_NOTICE )
  4. Suppress the error with the @ operator.

Note: It's strongly recommended to implement just point 1.

Notice: Undefined index / Undefined offset

This notice appears when you (or PHP) try to access an undefined index of an array.

Ways to deal with the issue:

  1. Check if the index exists before you access it. For this you can use isset() or array_key_exists():

    //isset()
    $value = isset($array['my_index']) ? $array['my_index'] : '';
    //array_key_exists()
    $value = array_key_exists('my_index', $array) ? $array['my_index'] : '';
  2. The language construct list() may generate this when it attempts to access an array index that does not exist:

    list($a, $b) = array(0 => 'a');
    //or
    list($one, $two) = explode(',', 'test string');

Two variables are used to access two array elements, however there is only one array element, index 0, so this will generate:

Notice: Undefined offset: 1

$_POST / $_GET / $_SESSION variable

The notices above appear often when working with $_POST$_GET or $_SESSION. For $_POSTand $_GET you just have to check if the index exists or not before you use them. For $_SESSIONyou have to make sure you have the session started with session_start() and that the index also exists.

Also note that all 3 variables are superglobals. This means they need to be written in uppercase.

Related:


728x90


Functionality:

Have created a simple browsing page navigation function. This is how the function should work:

1.) When a user click a "Start" button in page1, it will navigate the user to the 2nd page

2.) 2nd page is a games page whereby, upon navigation from the 1st page, a starting countdown timer will automatically display to notify the user that the game is starting in 3 seconds. Therefore, the display upon being navigated to page 2 should have 4 separate slides, each slides will display '3', '2', '1' and 'start'.

Hence I would like to ask for help how can I incorporate the fade-in counter code into my existing <script>??

Thanks

Code:

function fadeInCounter() {
  // Define "slides" and the "state" of the animation.
  var State = "Start1";
  // Global parameters for text.
  textSize(20);
  fill(139, 69, 19);

  var draw = function() {
    // Slide 1.
    if (State === "Start1") {
      background(205, 201, 201);
      text("3", 200, 200);
      Slide1 -= 5;
      if (Slide1 <= 0) {
        background(205, 201, 201);
        State = "Start2";
      }
    }
    // Slide 2.
    if (State === "Start2") {
      background(205, 201, 201);
      text("2", 200, 200);
      Slide2 -= 5;
      if (Slide2 <= 0) {
        background(205, 201, 201);
        State = "Start3";
      }
    }
    // Slide 3.
    if (State === "Start3") {
      background(205, 201, 201);
      text("1", 200, 200);
      Slide3 -= 5;
      if (Slide3 <= 0) {
        background(205, 201, 201);
        State = "End";
      }
    }

    // Ending frame.
    if (State === "End") {
      background(205, 201, 201);
      text("Start.", 180, 200);
    }
  };

}
<div id="page2" class="img-wrapper" align="center" style=" position: relative; background-image: url(Image/Page2.png); background-repeat: no-repeat; display: none; width: 100%;height: 100%;">

  <div id="fadeinCountDown"></div>


  <canvas id="canvas" width="300" height="300">
  </canvas>
  <canvas id="Counter" width="300" height="300">
  </canvas>
  <img id="roller" style="position:relative; top:1250px;" src="Image/Roller.png">
  <img id="scroll" style="position:absolute; top: 1250px; left: 380px; overflow-y: auto;" src="Image/Scroll.png">
</div>

shareimprove this question
   
where is the js code you have tried so far? can you set up a jsfiddle with your attempt too? – Lelio Faieta Nov 12 '15 at 9:28
   
@LelioFaieta I have added in what I have tried but I have no idea how to incorporate it in\. Please help – Luke Nov 12 '15 at 9:45

Following is a fade in/out timer. JSFiddle.

Also I have taken liberty to use single div instead of multiple divs.

var count = 3;

function updateTimer(){
    if(count > 0){
        $("#content").fadeOut('slow', function(){
        	$("#content").text(count);
            $("#content").fadeIn();
            count--;
        });
        
    }
    else if(count == 0){
        $("#content").fadeOut('slow', function(){
        	$("#content").text("Start");
            $("#content").fadeIn();
            count--;
        });
        
    }
    else {
    	$("#content").fadeOut();
        clearInterval(interval);
    }
    
}

var interval = setInterval(function(){updateTimer()},2000)
#content{
    font-size:26px;
    color:red;
    text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="content"></div>


728x90

(PHP 5, PHP 7)

mysqli_result::fetch_array -- mysqli_fetch_array — Fetch a result row as an associative, a numeric array, or both

설명 ¶

객체 기반 형식

mixed mysqli_result::fetch_array ([ int $resulttype = MYSQLI_BOTH ] )

절차식 형식

mixed mysqli_fetch_array ( mysqli_result $result [, int $resulttype = MYSQLI_BOTH ] )

Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter.

mysqli_fetch_array() is an extended version of the mysqli_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.

Note이 함수가 반환하는 필드 이름은 대소문자를 구별합니다.

Note이 함수는 NULL 필드를 PHP NULL 값으로 설정합니다.

If two or more columns of the result have the same field names, the last column will take precedence and overwrite the earlier data. In order to access multiple columns with the same name, the numerically indexed version of the row must be used.

인수 ¶

result

순차 형식 전용: mysqli_query()나 mysqli_store_result()나 mysqli_use_result()가 반환한 결과셋 식별자.

resulttype

This optional parameter is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MYSQLI_ASSOCMYSQLI_NUM, or MYSQLI_BOTH.

By using the MYSQLI_ASSOC constant this function will behave identically to the mysqli_fetch_assoc(), while MYSQLI_NUM will behave identically to the mysqli_fetch_row() function. The final option MYSQLI_BOTH will create a single array with the attributes of both.

반환값 ¶

Returns an array of strings that corresponds to the fetched row or NULL if there are no more rows in resultset.

예제 ¶

Example #1 객체 기반 형식

<?php
$mysqli 
= new mysqli("localhost""my_user""my_password""world");

/* check connection */
if ($mysqli->connect_errno) {
    
printf("Connect failed: %s\n"$mysqli->connect_error);
    exit();
}

$query "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result $mysqli->query($query);

/* numeric array */
$row $result->fetch_array(MYSQLI_NUM);
printf ("%s (%s)\n"$row[0], $row[1]);

/* associative array */
$row $result->fetch_array(MYSQLI_ASSOC);
printf ("%s (%s)\n"$row["Name"], $row["CountryCode"]);

/* associative and numeric array */
$row $result->fetch_array(MYSQLI_BOTH);
printf ("%s (%s)\n"$row[0], $row["CountryCode"]);

/* free result set */
$result->free();

/* close connection */
$mysqli->close();
?>

Example #2 절차식 형식

<?php
$link 
mysqli_connect("localhost""my_user""my_password""world");

/* check connection */
if (mysqli_connect_errno()) {
    
printf("Connect failed: %s\n"mysqli_connect_error());
    exit();
}

$query "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result mysqli_query($link$query);

/* numeric array */
$row mysqli_fetch_array($resultMYSQLI_NUM);
printf ("%s (%s)\n"$row[0], $row[1]);

/* associative array */
$row mysqli_fetch_array($resultMYSQLI_ASSOC);
printf ("%s (%s)\n"$row["Name"], $row["CountryCode"]);

/* associative and numeric array */
$row mysqli_fetch_array($resultMYSQLI_BOTH);
printf ("%s (%s)\n"$row[0], $row["CountryCode"]);

/* free result set */
mysqli_free_result($result);

/* close connection */
mysqli_close($link);
?>

위 예제들의 출력:

Kabul (AFG)
Qandahar (AFG)
Herat (AFG)

참고 ¶

add a note add a note

User Contributed Notes 4 notes

Jammerx2 ¶
7 years ago
Putting multiple rows into an array:

<?php
$mysqli 
= new mysqli("localhost""my_user""my_password""world");

/* check connection */
if (mysqli_connect_errno()) {
    
printf("Connect failed: %s\n"mysqli_connect_error());
    exit();
}

$query "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result $mysqli->query($query);

while(
$row $result->fetch_array())
{
$rows[] = $row;
}

foreach(
$rows as $row)
{
echo 
$row['CountryCode'];
}

/* free result set */
$result->close();

/* close connection */
$mysqli->close();
?>
Duncan ¶
4 years ago
Note that the array returned contains only strings.

E.g. when a MySQL field is an INT you may expect the field to be returned as an integer, however all fields are simply returned as strings.

What this means: use double-equals not triple equals when comparing numbers.

<?php
print $array_from_mysqli_fetch_array['id'] == "true" "false"// true
print $array_from_mysqli_fetch_array['id'] === "true" "false"// false
?>
meaje at msn dot com ¶
1 month ago
Please note that under PHP 5.x there appears to be a globally defined variable MYSQL_ASSOC, MYSQL_NUM, or MYSQL_BOTH which is the equivalent of MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH!!! Yet under PHP 7.x this is NOT the case and will cause a failure in trying to retrieve the result set!

This can cause severe headaches when trying to find out why you are getting the error: 
- mysqli_result::fetch_array() expects parameter 1 to be integer, string given in 'Filename' on line 'XX'
ahouston at gmail dot com ¶
6 years ago
Here is a function to return an associative array with multiple columns as keys to the array.

This is a rough approximation of the perl DBI->fetchall_hashref function - something I find myself using quite a bit.

Given a simple mySQL table:

mysql> select * from city;
+----------------+----------------+------------------+------------+
| country        | region         | city             | hemisphere |
+----------------+----------------+------------------+------------+
| South Africa   | KwaZulu-Natal  | Durban           | South      |
| South Africa   | Gauteng        | Johannesburg     | South      |
| South Africa   | Gauteng        | Tshwane          | South      |
| South Africa   | KwaZulu-Natal  | Pietermaritzburg | South      |
| United Kingdom | Greater London | City of London   | North      |
| United Kingdom | Greater London | Wimbledon        | North      |
| United Kingdom | Lancashire     | Liverpool        | North      |
| United Kingdom | Lancashire     | Manchester       | North      |
+----------------+----------------+------------------+------------+

*Note* - this is a simple function that makes no attempt to keep multiple values per key, so you need to specify all the unique keys you require.

<?php

        $link 
mysqli_connect("localhost""username""password""test");
        
$result mysqli_query($link"select * from city");
        
$results_arr fetch_all_assoc($result,array('hemisphere','country','region','city'));

function 
fetch_all_assoc(& $result,$index_keys) {

  
// Args :    $result = mysqli result variable (passed as reference to allow a free() at the end
  //           $indexkeys = array of columns to index on
  // Returns : associative array indexed by the keys array

  
$assoc = array();             // The array we're going to be returning

  
while ($row mysqli_fetch_array($resultMYSQLI_ASSOC)) {

        
$pointer = & $assoc;            // Start the pointer off at the base of the array

        
for ($i=0$i<count($index_keys); $i++) {
        
                
$key_name $index_keys[$i];
                if (!isset(
$row[$key_name])) {
                        print 
"Error: Key $key_name is not present in the results output.\n";
                        return(
false);
                }

                
$key_val= isset($row[$key_name]) ? $row[$key_name]  : "";
        
                if (!isset(
$pointer[$key_val])) {               

                        
$pointer[$key_val] = "";                // Start a new node
                        
$pointer = & $pointer[$key_val];                // Move the pointer on to the new node
                
}
                else {
                        
$pointer = & $pointer[$key_val];            // Already exists, move the pointer on to the new node
                
}

        } 
// for $i

        // At this point, $pointer should be at the furthest point on the tree of keys
        // Now we can go through all the columns and place their values on the tree
        // For ease of use, include the index keys and their values at this point too

        
foreach ($row as $key => $val) {
                        
$pointer[$key] = $val;
        }

  } 
// $row

  /* free result set */
  
$result->close();

  return(
$assoc);               
}

?>


'DB' 카테고리의 다른 글

SQL Database Performance Tuning for Developers  (0) 2018.04.10
[MSSQL]sqlsrv_fetch_array  (0) 2018.02.05
[MSSQL]sqlsrv_execute  (0) 2018.02.05
jQuery mouseleave()  (0) 2018.01.14
mysqli::query  (0) 2018.01.14

+ Recent posts