728x90

Overview

An interactive candlestick chart.

A candlestick chart is used to show an opening and closing value overlaid on top of a total variance. Candlestick charts are often used to show stock value behavior. In this chart, items where the opening value is less than the closing value (a gain) are drawn as filled boxes, and items where the opening value is more than the closing value (a loss) are drawn as hollow boxes.

Example

<html>
 
<head>
   
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
   
<script type="text/javascript">
      google
.charts.load('current', {'packages':['corechart']});
      google
.charts.setOnLoadCallback(drawChart);

 
function drawChart() {
   
var data = google.visualization.arrayToDataTable([
     
['Mon', 20, 28, 38, 45],
     
['Tue', 31, 38, 55, 66],
     
['Wed', 50, 55, 77, 80],
     
['Thu', 77, 77, 66, 50],
     
['Fri', 68, 66, 22, 15]
     
// Treat first row as data as well.
   
], true);

   
var options = {
      legend
:'none'
   
};

   
var chart = new google.visualization.CandlestickChart(document.getElementById('chart_div'));

    chart
.draw(data, options);
 
}
   
</script>
 
</head>
 
<body>
   
<div id="chart_div" style="width: 900px; height: 500px;"></div>
 
</body>
</html>

Waterfall charts

With the right set of options, candlestick charts can be made to resemble simple waterfall charts.

In the code below, we're eliminating the top wicks by having the same values in the first and second columns, and the bottom wicks by having the same values in the third and fourth columns. We set bar.groupWidth to '100%' to remove the space between the bars.

<html>
 
<head>
   
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
   
<script type="text/javascript">
      google
.charts.load('current', {'packages':['corechart']});
      google
.charts.setOnLoadCallback(drawChart);
     
function drawChart() {
       
var data = google.visualization.arrayToDataTable([
         
['Mon', 28, 28, 38, 38],
         
['Tue', 38, 38, 55, 55],
         
['Wed', 55, 55, 77, 77],
         
['Thu', 77, 77, 66, 66],
         
['Fri', 66, 66, 22, 22]
         
// Treat the first row as data.
       
], true);

       
var options = {
          legend
: 'none',
          bar
: { groupWidth: '100%' }, // Remove space between bars.
          candlestick
: {
            fallingColor
: { strokeWidth: 0, fill: '#a52714' }, // red
            risingColor
: { strokeWidth: 0, fill: '#0f9d58' }   // green
         
}
       
};

       
var chart = new google.visualization.CandlestickChart(document.getElementById('chart_div'));
        chart
.draw(data, options);
     
}
   
</script>
 
</head>
 
<body>
   
<div id="chart_div" style="width: 900px; height: 500px;"></div>
 
</body>
</html>

There is currently no easy way to label the bars. The best option is to use overlays.

Loading

google.charts.load package name is "corechart".

  google.charts.load('current', {packages: ['corechart']});

The visualization's class name is google.visualization.

CandlestickChart.

  var visualization = new google.visualization.CandlestickChart(container);

Data format

Five or more columns, where the first column defines X-axis values or group labels, and each multiple of four data columns after that defines a different series.

  • Col 0: String (discrete) used as a group label on the X axis, or number, date, datetime, or timeofday (continuous) used as a value on the X axis.
  • Col 1: Number specifying the low/minimum value of this marker. This is the base of the candle's center line. The column label is used as the series label in the legend (while the labels of the other columns are ignored).
  • Col 2: Number specifying the opening/initial value of this marker. This is one vertical border of the candle. If less than the column 3 value, the candle will be filled; otherwise it will be hollow.
  • Col 3: Number specifying the closing/final value of this marker. This is the second vertical border of the candle. If less than the column 2 value, the candle will be hollow; otherwise it will be filled.
  • Col 4: Number specifying the high/maximum value of this marker. This is the top of the candle's center line.
  • Col 5 [Optional]: A tooltip or style column for the candlestick.

In order to have more series, it is possible to add additional sets of 4 columns, with a similar structure to columns 1-4. Each such set represents another series of candlesticks. The total number of columns should be 4 times the number of series plus 1 (and any optional tooltip columns).

Configuration options

Name
aggregationTarget
How multiple data selections are rolled up into tooltips:
  • 'category': Group selected data by x-value.
  • 'series': Group selected data by series.
  • 'auto': Group selected data by x-value if all selections have the same x-value, and by series otherwise.
  • 'none': Show only one tooltip per selection.
aggregationTarget will often be used in tandem with selectionMode and tooltip.trigger, e.g.:
var options = {
 
// Allow multiple
 
// simultaneous selections.
 
selectionMode: 'multiple',
 
// Trigger tooltips
 
// on selections.
 
tooltip: {trigger: 'selection'},
 
// Group selections
 
// by x-value.
 
aggregationTarget: 'category',
};
   
Type: string
Default: 'auto'
animation.duration

The duration of the animation, in milliseconds. For details, see the animation documentation.

Type: number
Default: 0
animation.easing

The easing function applied to the animation. The following options are available:

  • 'linear' - Constant speed.
  • 'in' - Ease in - Start slow and speed up.
  • 'out' - Ease out - Start fast and slow down.
  • 'inAndOut' - Ease in and out - Start slow, speed up, then slow down.
Type: string
Default: 'linear'
animation.startup

Determines if the chart will animate on the initial draw. If true, the chart will start at the baseline and animate to its final state.

Type: boolean
Default false
axisTitlesPosition

Where to place the axis titles, compared to the chart area. Supported values:

  • in - Draw the axis titles inside the chart area.
  • out - Draw the axis titles outside the chart area.
  • none - Omit the axis titles.
Type: string
Default: 'out'
backgroundColor

The background color for the main area of the chart. Can be either a simple HTML color string, for example: 'red' or '#00cc00', or an object with the following properties.

Type: string or object
Default: 'white'
backgroundColor.stroke

The color of the chart border, as an HTML color string.

Type: string
Default: '#666'
backgroundColor.strokeWidth

The border width, in pixels.

Type: number
Default: 0
backgroundColor.fill

The chart fill color, as an HTML color string.

Type: string
Default: 'white'
bar.groupWidth
The width of a group of candlesticks, specified in either of these formats:
  • Pixels (e.g. 50).
  • Percentage of the available width for each group (e.g. '20%'), where '100%' means that groups have no space between them.
Type: number or string
Default: The golden ratio, approximately '61.8%'.
candlestick.hollowIsRising

If true, rising candles will appear hollow and falling candles will appear solid, otherwise, the opposite.

Type: boolean
Default: false (will later be changed to true)
candlestick.fallingColor.fill

The fill color of falling candles, as an HTML color string.

Type: string
Default: auto (depends on the series color and hollowIsRising)
candlestick.fallingColor.stroke

The stroke color of falling candles, as an HTML color string.

Type: string
Default: auto (the series color)
candlestick.fallingColor.strokeWidth

The stroke width of falling candles, as an HTML color string.

Type: 2
Default: number
candlestick.risingColor.fill

The fill color of rising candles, as an HTML color string.

Type: string
Default: auto (white or the series color, depending on hollowIsRising)
candlestick.risingColor.stroke

The stroke color of rising candles, as an HTML color string.

Type: string
Default: auto (the series color or white, depending on hollowIsRising)
candlestick.risingColor.strokeWidth

The stroke width of rising candles, as an HTML color string.

Type: number
Default: 2
chartArea

An object with members to configure the placement and size of the chart area (where the chart itself is drawn, excluding axis and legends). Two formats are supported: a number, or a number followed by %. A simple number is a value in pixels; a number followed by % is a percentage. Example: chartArea:{left:20,top:0,width:'50%',height:'75%'}

Type: object
Default: null
chartArea.backgroundColor
Chart area background color. When a string is used, it can be either a hex string (e.g., '#fdc') or an English color name. When an object is used, the following properties can be provided:
  • stroke: the color, provided as a hex string or English color name.
  • strokeWidth: if provided, draws a border around the chart area of the given width (and with the color of stroke).
Type: string or object
Default: 'white'
chartArea.left

How far to draw the chart from the left border.

Type: number or string
Default: auto
chartArea.top

How far to draw the chart from the top border.

Type: number or string
Default: auto
chartArea.width

Chart area width.

Type: number or string
Default: auto
chartArea.height

Chart area height.

Type: number or string
Default: auto
colors

The colors to use for the chart elements. An array of strings, where each element is an HTML color string, for example: colors:['red','#004411'].

Type: Array of strings
Default: default colors
enableInteractivity

Whether the chart throws user-based events or reacts to user interaction. If false, the chart will not throw 'select' or other interaction-based events (but will throw ready or error events), and will not display hovertext or otherwise change depending on user input.

Type: boolean
Default: true
focusTarget

The type of the entity that receives focus on mouse hover. Also affects which entity is selected by mouse click, and which data table element is associated with events. Can be one of the following:

  • 'datum' - Focus on a single data point. Correlates to a cell in the data table.
  • 'category' - Focus on a grouping of all data points along the major axis. Correlates to a row in the data table.

In focusTarget 'category' the tooltip displays all the category values. This may be useful for comparing values of different series.

Type: string
Default: 'datum'
fontSize

The default font size, in pixels, of all text in the chart. You can override this using properties for specific chart elements.

Type: number
Default: automatic
fontName

The default font face for all text in the chart. You can override this using properties for specific chart elements.

Type: string
Default: 'Arial'
forceIFrame

Draws the chart inside an inline frame. (Note that on IE8, this option is ignored; all IE8 charts are drawn in i-frames.)

Type: boolean
Default: false
hAxis

An object with members to configure various horizontal axis elements. To specify properties of this object, you can use object literal notation, as shown here:

{ title: 'Hello', titleTextStyle: { color: '#FF0000' } }
Type: object
Default: null
hAxis.baseline

The baseline for the horizontal axis.

This option is only supported for a continuous axis.

Type: number
Default: automatic
hAxis.baselineColor

The color of the baseline for the horizontal axis. Can be any HTML color string, for example:'red' or '#00cc00'.

This option is only supported for a continuous axis.

Type: number
Default: 'black'
hAxis.direction

The direction in which the values along the horizontal axis grow. Specify -1 to reverse the order of the values.

Type: 1 or -1
Default: 1
hAxis.format

A format string for numeric or date axis labels.

For number axis labels, this is a subset of the decimal formatting ICU pattern set . For instance, {format:'#,###%'} will display values "1,000%", "750%", and "50%" for values 10, 7.5, and 0.5. You can also supply any of the following:

  • {format: 'none'}: displays numbers with no formatting (e.g., 8000000)
  • {format: 'decimal'}: displays numbers with thousands separators (e.g., 8,000,000)
  • {format: 'scientific'}: displays numbers in scientific notation (e.g., 8e6)
  • {format: 'currency'}: displays numbers in the local currency (e.g., $8,000,000.00)
  • {format: 'percent'}: displays numbers as percentages (e.g., 800,000,000%)
  • {format: 'short'}: displays abbreviated numbers (e.g., 8M)
  • {format: 'long'}: displays numbers as full words (e.g., 8 million)

For date axis labels, this is a subset of the date formatting ICU pattern set . For instance, {format:'MMM d, y'} will display the value "Jul 1, 2011" for the date of July first in 2011.

The actual formatting applied to the label is derived from the locale the API has been loaded with. For more details, see loading charts with a specific locale .

This option is only supported for a continuous axis.

Type: string
Default: auto
hAxis.gridlines

An object with members to configure the gridlines on the horizontal axis. To specify properties of this object, you can use object literal notation, as shown here:

{color: '#333', count: 4}

This option is only supported for a continuous axis.

Type: object
Default: null
hAxis.gridlines.color

The color of the horizontal gridlines inside the chart area. Specify a valid HTML color string.

Type: string
Default: '#CCC'
hAxis.gridlines.count

The number of horizontal gridlines inside the chart area. Minimum value is 2. Specify -1 to automatically compute the number of gridlines.

Type: number
Default: 5
hAxis.gridlines.units

Overrides the default format for various aspects of date/datetime/timeofday data types when used with chart computed gridlines. Allows formatting for years, months, days, hours, minutes, seconds, and milliseconds.

General format is:

gridlines: { units: { years: {format: [/*format strings here*/]}, months: {format: [/*format strings here*/]}, days: {format: [/*format strings here*/]} hours: {format: [/*format strings here*/]} minutes: {format: [/*format strings here*/]} seconds: {format: [/*format strings here*/]}, milliseconds: {format: [/*format strings here*/]}, } }

Additional information can be found in Dates and Times.

Type: object
Default: null
hAxis.minorGridlines

An object with members to configure the minor gridlines on the horizontal axis, similar to the hAxis.gridlines option.

This option is only supported for a continuous axis.

Type: object
Default: null
hAxis.minorGridlines.color

The color of the horizontal minor gridlines inside the chart area. Specify a valid HTML color string.

Type: string
Default: A blend of the gridline and background colors
hAxis.minorGridlines.count

The number of horizontal minor gridlines between two regular gridlines.

Type: number
Default: 0
hAxis.minorGridlines.units

Overrides the default format for various aspects of date/datetime/timeofday data types when used with chart computed minorGridlines. Allows formatting for years, months, days, hours, minutes, seconds, and milliseconds.

General format is:

gridlines: { units: { years: {format: [/*format strings here*/]}, months: {format: [/*format strings here*/]}, days: {format: [/*format strings here*/]} hours: {format: [/*format strings here*/]} minutes: {format: [/*format strings here*/]} seconds: {format: [/*format strings here*/]}, milliseconds: {format: [/*format strings here*/]}, } }

Additional information can be found in Dates and Times.

Type: object
Default: null
hAxis.logScale

hAxis property that makes the horizontal axis a logarithmic scale (requires all values to be positive). Set to true for yes.

This option is only supported for a continuous axis.

Type: boolean
Default: false
hAxis.scaleType

hAxis property that makes the horizontal axis a logarithmic scale. Can be one of the following:

  • null - No logarithmic scaling is performed.
  • 'log' - Logarithmic scaling. Negative and zero values are not plotted. This option is the same as setting hAxis: { logscale: true }.
  • 'mirrorLog' - Logarithmic scaling in which negative and zero values are plotted. The plotted value of a negative number is the negative of the log of the absolute value. Values close to 0 are plotted on a linear scale.

This option is only supported for a continuous axis.

Type: string
Default: null
hAxis.textPosition

Position of the horizontal axis text, relative to the chart area. Supported values: 'out', 'in', 'none'.

Type: string
Default: 'out'
hAxis.textStyle

An object that specifies the horizontal axis text style. The object has this format:

{ color: <string>, fontName: <string>, fontSize: <number>, bold: <boolean>, italic: <boolean> }

The color can be any HTML color string, for example: 'red' or '#00cc00'. Also see fontName and fontSize.

Type: object
Default: {color: 'black', fontName: <global-font-name>, fontSize: <global-font-size>}
hAxis.ticks

Replaces the automatically generated X-axis ticks with the specified array. Each element of the array should be either a valid tick value (such as a number, date, datetime, or timeofday), or an object. If it's an object, it should have a v property for the tick value, and an optional f property containing the literal string to be displayed as the label.

Examples:

  • hAxis: { ticks: [5,10,15,20] }
  • hAxis: { ticks: [{v:32, f:'thirty two'}, {v:64, f:'sixty four'}] }
  • hAxis: { ticks: [new Date(2014,3,15), new Date(2013,5,15)] }
  • hAxis: { ticks: [16, {v:32, f:'thirty two'}, {v:64, f:'sixty four'}, 128] }

This option is only supported for a continuous axis.

Type: Array of elements
Default: auto
hAxis.title

hAxis property that specifies the title of the horizontal axis.

Type: string
Default: null
hAxis.titleTextStyle

An object that specifies the horizontal axis title text style. The object has this format:

{ color: <string>, fontName: <string>, fontSize: <number>, bold: <boolean>, italic: <boolean> }

The color can be any HTML color string, for example: 'red' or '#00cc00'. Also see fontName and fontSize.

Type: object
Default: {color: 'black', fontName: <global-font-name>, fontSize: <global-font-size>}
hAxis.allowContainerBoundaryTextCufoff

If false, will hide outermost labels rather than allow them to be cropped by the chart container. If true, will allow label cropping.

This option is only supported for a discrete axis.

Type: boolean
Default: false
hAxis.slantedText

If true, draw the horizontal axis text at an angle, to help fit more text along the axis; if false, draw horizontal axis text upright. Default behavior is to slant text if it cannot all fit when drawn upright. Notice that this option is available only when the hAxis.textPosition is set to 'out' (which is the default).

This option is only supported for a discrete axis.

Type: boolean
Default: automatic
hAxis.slantedTextAngle

The angle of the horizontal axis text, if it's drawn slanted. Ignored if hAxis.slantedTextis false, or is in auto mode, and the chart decided to draw the text horizontally.

This option is only supported for a discrete axis.

Type: number, 1—90
Default: 30
hAxis.maxAlternation

Maximum number of levels of horizontal axis text. If axis text labels become too crowded, the server might shift neighboring labels up or down in order to fit labels closer together. This value specifies the most number of levels to use; the server can use fewer levels, if labels can fit without overlapping.

This option is only supported for a discrete axis.

Type: number
Default: 2
hAxis.maxTextLines

Maximum number of lines allowed for the text labels. Labels can span multiple lines if they are too long, and the number of lines is, by default, limited by the height of the available space.

This option is only supported for a discrete axis.

Type: number
Default: auto
hAxis.minTextSpacing

Minimum horizontal spacing, in pixels, allowed between two adjacent text labels. If the labels are spaced too densely, or they are too long, the spacing can drop below this threshold, and in this case one of the label-unclutter measures will be applied (e.g, truncating the lables or dropping some of them).

This option is only supported for a discrete axis.

Type: number
Default: The value of hAxis.textStyle.fontSize
hAxis.showTextEvery

How many horizontal axis labels to show, where 1 means show every label, 2 means show every other label, and so on. Default is to try to show as many labels as possible without overlapping.

This option is only supported for a discrete axis.

Type: number
Default: automatic
hAxis.maxValue

Moves the max value of the horizontal axis to the specified value; this will be rightward in most charts. Ignored if this is set to a value smaller than the maximum x-value of the data.hAxis.viewWindow.max overrides this property.

This option is only supported for a continuous axis.

Type: number
Default: automatic
hAxis.minValue

Moves the min value of the horizontal axis to the specified value; this will be leftward in most charts. Ignored if this is set to a value greater than the minimum x-value of the data.hAxis.viewWindow.min overrides this property.

This option is only supported for a continuous axis.

Type: number
Default: automatic
hAxis.viewWindowMode

Specifies how to scale the horizontal axis to render the values within the chart area. The following string values are supported:

  • 'pretty' - Scale the horizontal values so that the maximum and minimum data values are rendered a bit inside the left and right of the chart area. This will causehaxis.viewWindow.min and haxis.viewWindow.max to be ignored.
  • 'maximized' - Scale the horizontal values so that the maximum and minimum data values touch the left and right of the chart area. This will cause haxis.viewWindow.min and haxis.viewWindow.max to be ignored.
  • 'explicit' - A deprecated option for specifying the left and right scale values of the chart area. (Deprecated because it's redundant with haxis.viewWindow.min andhaxis.viewWindow.max.) Data values outside these values will be cropped. You must specify an hAxis.viewWindow object describing the maximum and minimum values to show.

This option is only supported for a continuous axis.

Type: string
Default: Equivalent to 'pretty', but haxis.viewWindow.min andhaxis.viewWindow.max take precedence if used.
hAxis.viewWindow

Specifies the cropping range of the horizontal axis.

Type: object
Default: null
hAxis.viewWindow.max
  • For a continuous axis:

    The maximum horizontal data value to render.

  • For a discrete axis:

    The zero-based row index where the cropping window ends. Data points at this index and higher will be cropped out. In conjunction with vAxis.viewWindowMode.min, it defines a half-opened range [min, max) that denotes the element indices to display. In other words, every index such that min <= index < max will be displayed.

Ignored when hAxis.viewWindowMode is 'pretty' or 'maximized'.

Type: number
Default: auto
hAxis.viewWindow.min
  • For a continuous axis:

    The minimum horizontal data value to render.

  • For a discrete axis:

    The zero-based row index where the cropping window begins. Data points at indices lower than this will be cropped out. In conjunction with vAxis.viewWindowMode.max, it defines a half-opened range [min, max) that denotes the element indices to display. In other words, every index such that min <= index < max will be displayed.

Ignored when hAxis.viewWindowMode is 'pretty' or 'maximized'.

Type: number
Default: auto
height

Height of the chart, in pixels.

Type: number
Default: height of the containing element
legend

An object with members to configure various aspects of the legend. To specify properties of this object, you can use object literal notation, as shown here:

{position: 'top', textStyle: {color: 'blue', fontSize: 16}}
Type: object
Default: null
legend.alignment

Alignment of the legend. Can be one of the following:

  • 'start' - Aligned to the start of the area allocated for the legend.
  • 'center' - Centered in the area allocated for the legend.
  • 'end' - Aligned to the end of the area allocated for the legend.

Start, center, and end are relative to the style -- vertical or horizontal -- of the legend. For example, in a 'right' legend, 'start' and 'end' are at the top and bottom, respectively; for a 'top' legend, 'start' and 'end' would be at the left and right of the area, respectively.

The default value depends on the legend's position. For 'bottom' legends, the default is 'center'; other legends default to 'start'.

Type: string
Default: automatic
legend.maxLines

Maximum number of lines in the legend. Set this to a number greater than one to add lines to your legend. Note: The exact logic used to determine the actual number of lines rendered is still in flux.

This option currently works only when legend.position is 'top'.

Type: number
Default: 1
legend.position

Position of the legend. Can be one of the following:

  • 'bottom' - Below the chart.
  • 'left' - To the left of the chart, provided the left axis has no series associated with it. So if you want the legend on the left, use the option targetAxisIndex: 1.
  • 'in' - Inside the chart, by the top left corner.
  • 'none' - No legend is displayed.
  • 'right' - To the right of the chart. Incompatible with the vAxes option.
  • 'top' - Above the chart.
Type: string
Default: 'right'
legend.textStyle

An object that specifies the legend text style. The object has this format:

{ color: <string>, fontName: <string>, fontSize: <number>, bold: <boolean>, italic: <boolean> }

The color can be any HTML color string, for example: 'red' or '#00cc00'. Also see fontName and fontSize.

Type: object
Default: {color: 'black', fontName: <global-font-name>, fontSize: <global-font-size>}
orientation

The orientation of the chart. When set to 'vertical', rotates the axes of the chart so that (for instance) a column chart becomes a bar chart, and an area chart grows rightward instead of up:

Type: string
Default: 'horizontal'
reverseCategories

If set to true, will draw series from right to left. The default is to draw left-to-right.

This option is only supported for a discrete major axis.

Type: boolean
Default: false
selectionMode

When selectionMode is 'multiple', users may select multiple data points.

Type: string
Default: 'single'
series

An array of objects, each describing the format of the corresponding series in the chart. To use default values for a series, specify an empty object {}. If a series or a value is not specified, the global value will be used. Each object supports the following properties:

  • color - The color to use for this series. Specify a valid HTML color string.
  • fallingColor.fill - Overrides the global candlestick.fallingColor.fillvalue for this series.
  • fallingColor.stroke - Overrides the globalcandlestick.fallingColor.stroke value for this series.
  • fallingColor.strokeWidth - Overrides the globalcandlestick.fallingColor.strokeWidth value for this series.
  • labelInLegend - The description of the series to appear in the chart legend.
  • risingColor.fill - Overrides the global candlestick.risingColor.fill value for this series.
  • risingColor.stroke - Overrides the global candlestick.risingColor.strokevalue for this series.
  • risingColor.strokeWidth - Overrides the globalcandlestick.risingColor.strokeWidth value for this series.
  • targetAxisIndex - Which axis to assign this series to, where 0 is the default axis, and 1 is the opposite axis. Default value is 0; set to 1 to define a chart where different series are rendered against different axes. At least one series much be allocated to the default axis. You can define a different scale for different axes.
  • visibleInLegend - A boolean value, where true means that the series should have a legend entry, and false means that it should not. Default is true.

You can specify either an array of objects, each of which applies to the series in the order given, or you can specify an object where each child has a numeric key indicating which series it applies to. For example, the following two declarations are identical, and declare the first series as black and absent from the legend, and the fourth as red and absent from the legend:

series: [ {color: 'black', visibleInLegend: false}, {}, {}, {color: 'red', visibleInLegend: false} ] series: { 0:{color: 'black', visibleInLegend: false}, 3:{color: 'red', visibleInLegend: false} }
Type: Array of objects, or object with nested objects
Default: {}
theme

A theme is a set of predefined option values that work together to achieve a specific chart behavior or visual effect. Currently only one theme is available:

  • 'maximized' - Maximizes the area of the chart, and draws the legend and all of the labels inside the chart area. Sets the following options:
    chartArea: {width: '100%', height: '100%'}, legend: {position: 'in'}, titlePosition: 'in', axisTitlesPosition: 'in', hAxis: {textPosition: 'in'}, vAxis: {textPosition: 'in'}
Type: string
Default: null
title

Text to display above the chart.

Type: string
Default: no title
titlePosition

Where to place the chart title, compared to the chart area. Supported values:

  • in - Draw the title inside the chart area.
  • out - Draw the title outside the chart area.
  • none - Omit the title.
Type: string
Default: 'out'
titleTextStyle

An object that specifies the title text style. The object has this format:

{ color: <string>, fontName: <string>, fontSize: <number>, bold: <boolean>, italic: <boolean> }

The color can be any HTML color string, for example: 'red' or '#00cc00'. Also see fontName and fontSize.

Type: object
Default: {color: 'black', fontName: <global-font-name>, fontSize: <global-font-size>}
tooltip

An object with members to configure various tooltip elements. To specify properties of this object, you can use object literal notation, as shown here:

{textStyle: {color: '#FF0000'}, showColorCode: true}
Type: object
Default: null
tooltip.ignoreBounds

If set to true, allows the drawing of tooltips to flow outside of the bounds of the chart on all sides.

Note: This only applies to HTML tooltips. If this is enabled with SVG tooltips, any overflow outside of the chart bounds will be cropped. See Customizing Tooltip Content for more details.

Type: boolean
Default: false
tooltip.isHtml

If set to true, use HTML-rendered (rather than SVG-rendered) tooltips. See Customizing Tooltip Content for more details.

Note: customization of the HTML tooltip content via the tooltip column data role is not supported by the Bubble Chart visualization.

Type: boolean
Default: false
tooltip.showColorCode

If true, show colored squares next to the series information in the tooltip. The default is true when focusTarget is set to 'category', otherwise the default is false.

Type: boolean
Default: automatic
tooltip.textStyle

An object that specifies the tooltip text style. The object has this format:

{ color: <string>, fontName: <string>, fontSize: <number>, bold: <boolean>, italic: <boolean> }

The color can be any HTML color string, for example: 'red' or '#00cc00'. Also see fontName and fontSize.

Type: object
Default: {color: 'black', fontName: <global-font-name>, fontSize: <global-font-size>}
tooltip.trigger

The user interaction that causes the tooltip to be displayed:

  • 'focus' - The tooltip will be displayed when the user hovers over the element.
  • 'none' - The tooltip will not be displayed.
Type: string
Default: 'focus'
vAxes

Specifies properties for individual vertical axes, if the chart has multiple vertical axes. Each child object is a vAxis object, and can contain all the properties supported by vAxis. These property values override any global settings for the same property.

To specify a chart with multiple vertical axes, first define a new axis usingseries.targetAxisIndex, then configure the axis using vAxes. The following example assigns series 2 to the right axis and specifies a custom title and text style for it:

{ series: { 2: { targetAxisIndex:1 } }, vAxes: { 1: { title:'Losses', textStyle: {color: 'red'} } } }

This property can be either an object or an array: the object is a collection of objects, each with a numeric label that specifies the axis that it defines--this is the format shown above; the array is an array of objects, one per axis. For example, the following array-style notation is identical to the vAxis object shown above:

vAxes: [ {}, // Nothing specified for axis 0 { title:'Losses', textStyle: {color: 'red'} // Axis 1 } ]
Type: Array of object, or object with child objects
Default: null
vAxis

An object with members to configure various vertical axis elements. To specify properties of this object, you can use object literal notation, as shown here:

{title: 'Hello', titleTextStyle: {color: '#FF0000'}}
Type: object
Default: null
vAxis.baseline

vAxis property that specifies the baseline for the vertical axis. If the baseline is larger than the highest grid line or smaller than the lowest grid line, it will be rounded to the closest gridline.

Type: number
Default: automatic
vAxis.baselineColor

Specifies the color of the baseline for the vertical axis. Can be any HTML color string, for example: 'red' or '#00cc00'.

Type: number
Default: 'black'
vAxis.direction

The direction in which the values along the vertical axis grow. Specify -1 to reverse the order of the values.

Type: 1 or -1
Default: 1
vAxis.format

A format string for numeric axis labels. This is a subset of the ICU pattern set . For instance, {format:'#,###%'} will display values "1,000%", "750%", and "50%" for values 10, 7.5, and 0.5. You can also supply any of the following:

  • {format: 'none'}: displays numbers with no formatting (e.g., 8000000)
  • {format: 'decimal'}: displays numbers with thousands separators (e.g., 8,000,000)
  • {format: 'scientific'}: displays numbers in scientific notation (e.g., 8e6)
  • {format: 'currency'}: displays numbers in the local currency (e.g., $8,000,000.00)
  • {format: 'percent'}: displays numbers as percentages (e.g., 800,000,000%)
  • {format: 'short'}: displays abbreviated numbers (e.g., 8M)
  • {format: 'long'}: displays numbers as full words (e.g., 8 million)

The actual formatting applied to the label is derived from the locale the API has been loaded with. For more details, see loading charts with a specific locale .

Type: string
Default: auto
vAxis.gridlines

An object with members to configure the gridlines on the vertical axis. To specify properties of this object, you can use object literal notation, as shown here:

{color: '#333', count: 4}
Type: object
Default: null
vAxis.gridlines.color

The color of the vertical gridlines inside the chart area. Specify a valid HTML color string.

Type: string
Default: '#CCC'
vAxis.gridlines.count

The number of vertical gridlines inside the chart area. Minimum value is 2. Specify -1 to automatically compute the number of gridlines.

Type: number
Default: 5
vAxis.gridlines.units

Overrides the default format for various aspects of date/datetime/timeofday data types when used with chart computed gridlines. Allows formatting for years, months, days, hours, minutes, seconds, and milliseconds.

General format is:

gridlines: { units: { years: {format: [/*format strings here*/]}, months: {format: [/*format strings here*/]}, days: {format: [/*format strings here*/]} hours: {format: [/*format strings here*/]} minutes: {format: [/*format strings here*/]} seconds: {format: [/*format strings here*/]}, milliseconds: {format: [/*format strings here*/]}, } }

Additional information can be found in Dates and Times.

Type: object
Default: null
vAxis.minorGridlines

An object with members to configure the minor gridlines on the vertical axis, similar to the vAxis.gridlines option.

Type: object
Default: null
vAxis.minorGridlines.color

The color of the vertical minor gridlines inside the chart area. Specify a valid HTML color string.

Type: string
Default: A blend of the gridline and background colors
vAxis.minorGridlines.count

The number of vertical minor gridlines between two regular gridlines.

Type: number
Default: 0
vAxis.minorGridlines.units

Overrides the default format for various aspects of date/datetime/timeofday data types when used with chart computed minorGridlines. Allows formatting for years, months, days, hours, minutes, seconds, and milliseconds.

General format is:

gridlines: { units: { years: {format: [/*format strings here*/]}, months: {format: [/*format strings here*/]}, days: {format: [/*format strings here*/]} hours: {format: [/*format strings here*/]} minutes: {format: [/*format strings here*/]} seconds: {format: [/*format strings here*/]}, milliseconds: {format: [/*format strings here*/]}, } }

Additional information can be found in Dates and Times.

Type: object
Default: null
vAxis.logScale

If true, makes the vertical axis a logarithmic scale. Note: All values must be positive.

Type: boolean
Default: false
vAxis.scaleType

vAxis property that makes the vertical axis a logarithmic scale. Can be one of the following:

  • null - No logarithmic scaling is performed.
  • 'log' - Logarithmic scaling. Negative and zero values are not plotted. This option is the same as setting vAxis: { logscale: true }.
  • 'mirrorLog' - Logarithmic scaling in which negative and zero values are plotted. The plotted value of a negative number is the negative of the log of the absolute value. Values close to 0 are plotted on a linear scale.

This option is only supported for a continuous axis.

Type: string
Default: null
vAxis.textPosition

Position of the vertical axis text, relative to the chart area. Supported values: 'out', 'in', 'none'.

Type: string
Default: 'out'
vAxis.textStyle

An object that specifies the vertical axis text style. The object has this format:

{ color: <string>, fontName: <string>, fontSize: <number>, bold: <boolean>, italic: <boolean> }

The color can be any HTML color string, for example: 'red' or '#00cc00'. Also see fontName and fontSize.

Type: object
Default: {color: 'black', fontName: <global-font-name>, fontSize: <global-font-size>}
vAxis.ticks

Replaces the automatically generated Y-axis ticks with the specified array. Each element of the array should be either a valid tick value (such as a number, date, datetime, or timeofday), or an object. If it's an object, it should have a v property for the tick value, and an optional f property containing the literal string to be displayed as the label.

Examples:

  • vAxis: { ticks: [5,10,15,20] }
  • vAxis: { ticks: [{v:32, f:'thirty two'}, {v:64, f:'sixty four'}] }
  • vAxis: { ticks: [new Date(2014,3,15), new Date(2013,5,15)] }
  • vAxis: { ticks: [16, {v:32, f:'thirty two'}, {v:64, f:'sixty four'}, 128] }
Type: Array of elements
Default: auto
vAxis.title

vAxis property that specifies a title for the vertical axis.

Type: string
Default: no title
vAxis.titleTextStyle

An object that specifies the vertical axis title text style. The object has this format:

{ color: <string>, fontName: <string>, fontSize: <number>, bold: <boolean>, italic: <boolean> }

The color can be any HTML color string, for example: 'red' or '#00cc00'. Also see fontName and fontSize.

Type: object
Default: {color: 'black', fontName: <global-font-name>, fontSize: <global-font-size>}
vAxis.maxValue

Moves the max value of the vertical axis to the specified value; this will be upward in most charts. Ignored if this is set to a value smaller than the maximum y-value of the data.vAxis.viewWindow.max overrides this property.

Type: number
Default: automatic
vAxis.minValue

Moves the min value of the vertical axis to the specified value; this will be downward in most charts. Ignored if this is set to a value greater than the minimum y-value of the data.vAxis.viewWindow.min overrides this property.

Type: number
Default: null
vAxis.viewWindowMode

Specifies how to scale the vertical axis to render the values within the chart area. The following string values are supported:

  • 'pretty' - Scale the vertical values so that the maximum and minimum data values are rendered a bit inside the top and bottom of the chart area. This will causevaxis.viewWindow.min and vaxis.viewWindow.max to be ignored.
  • 'maximized' - Scale the vertical values so that the maximum and minimum data values touch the top and bottom of the chart area. This will cause vaxis.viewWindow.minand vaxis.viewWindow.max to be ignored.
  • 'explicit' - A deprecated option for specifying the top and bottom scale values of the chart area. (Deprecated because it's redundant with vaxis.viewWindow.min andvaxis.viewWindow.max. Data values outside these values will be cropped. You must specify a vAxis.viewWindow object describing the maximum and minimum values to show.
Type: string
Default: Equivalent to 'pretty', but vaxis.viewWindow.min andvaxis.viewWindow.max take precedence if used.
vAxis.viewWindow

Specifies the cropping range of the vertical axis.

Type: object
Default: null
vAxis.viewWindow.max

The maximum vertical data value to render.

Ignored when vAxis.viewWindowMode is 'pretty' or 'maximized'.

Type: number
Default: auto
vAxis.viewWindow.min

The minimum horizontal data value to render.

Ignored when vAxis.viewWindowMode is 'pretty' or 'maximized'.

Type: number
Default: auto
width

Width of the chart, in pixels.

Type: number
Default: width of the containing element

Methods

Method
draw(data, options)

Draws the chart. The chart accepts further method calls only after the readyevent is fired.Extended description.

Return Type: none
getAction(actionID)

Returns the tooltip action object with the requested actionID.

Return Type: object
getBoundingBox(id)

Returns an object containing the left, top, width, and height of chart element id. The format for idisn't yet documented (they're the return values of event handlers), but here are some examples:

var cli = chart.getChartLayoutInterface();

Height of the chart area
cli.getBoundingBox('chartarea').height
Width of the third bar in the first series of a bar or column chart
cli.getBoundingBox('bar#0#2').width
Bounding box of the fifth wedge of a pie chart
cli.getBoundingBox('slice#4')
Bounding box of the chart data of a vertical (e.g., column) chart:
cli.getBoundingBox('vAxis#0#gridline')
Bounding box of the chart data of a horizontal (e.g., bar) chart:
cli.getBoundingBox('hAxis#0#gridline')

Values are relative to the container of the chart. Call this after the chart is drawn.

Return Type: object
getChartAreaBoundingBox()

Returns an object containing the left, top, width, and height of the chart content (i.e., excluding labels and legend):

var cli = chart.getChartLayoutInterface();

cli.getChartAreaBoundingBox().left
cli.getChartAreaBoundingBox().top
cli.getChartAreaBoundingBox().height
cli.getChartAreaBoundingBox().width

Values are relative to the container of the chart. Call this after the chart is drawn.

Return Type: object
getChartLayoutInterface()

Returns an object containing information about the onscreen placement of the chart and its elements.

The following methods can be called on the returned object:

  • getBoundingBox
  • getChartAreaBoundingBox
  • getHAxisValue
  • getVAxisValue
  • getXLocation
  • getYLocation

Call this after the chart is drawn.

Return Type: object
getHAxisValue(position,optional_axis_index)

Returns the logical horizontal value at position, which is an offset from the chart container's left edge. Can be negative.

Example: chart.getChartLayoutInterface().getHAxisValue(400).

Call this after the chart is drawn.

Return Type: number
getImageURI()

Returns the chart serialized as an image URI.

Call this after the chart is drawn.

See Printing PNG Charts.

Return Type: string
getSelection()

Returns an array of the selected chart entities. Selectable entities are candlesticks, legend entries and categories. For this chart, only one entity can be selected at any given moment. Extended description .

Return Type: Array of selection elements
getVAxisValue(position,optional_axis_index)

Returns the logical vertical value at position, which is an offset from the chart container's top edge. Can be negative.

Example: chart.getChartLayoutInterface().getVAxisValue(300).

Call this after the chart is drawn.

Return Type: number
getXLocation(position,optional_axis_index)

Returns the screen x-coordinate of position relative to the chart's container.

Example: chart.getChartLayoutInterface().getXLocation(400).

Call this after the chart is drawn.

Return Type: number
getYLocation(position,optional_axis_index)

Returns the screen y-coordinate of position relative to the chart's container.

Example: chart.getChartLayoutInterface().getYLocation(300).

Call this after the chart is drawn.

Return Type: number
removeAction(actionID)

Removes the tooltip action with the requested actionID from the chart.

Return Type: none
setAction(action)

Sets a tooltip action to be executed when the user clicks on the action text.

The setAction method takes an object as its action parameter. This object should specify 3 properties: id— the ID of the action being set, text —the text that should appear in the tooltip for the action, and action — the function that should be run when a user clicks on the action text.

Any and all tooltip actions should be set prior to calling the chart's draw() method. Extended description.

Return Type: none
setSelection()

Selects the specified chart entities. Cancels any previous selection. Selectable entities are candlesticks, legend entries and categories. For this chart, only one entity can be selected at a time.Extended description .

Return Type: none
clearChart()

Clears the chart, and releases all of its allocated resources.

Return Type: none

Events

For more information on how to use these events, see Basic InteractivityHandling Events, and Firing Events.

Name
animationfinish

Fired when transition animation is complete.

Properties: none
click

Fired when the user clicks inside the chart. Can be used to identify when the title, data elements, legend entries, axes, gridlines, or labels are clicked.

Properties: targetID
error

Fired when an error occurs when attempting to render the chart.

Properties: id, message
onmouseover

Fired when the user mouses over a visual entity. Passes back the row and column indices of the corresponding data table element. A candlestick correlates to a cell in the data table, a legend entry to a column (row index is null), and a category to a row (column index is null).

Properties: row, column
onmouseout

Fired when the user mouses away from a visual entity. Passes back the row and column indices of the corresponding data table element. A candlestick correlates to a cell in the data table, a legend entry to a column (row index is null), and a category to a row (column index is null).

Properties: row, column
ready

The chart is ready for external method calls. If you want to interact with the chart, and call methods after you draw it, you should set up a listener for this event before you call the draw method, and call them only after the event was fired.

Properties: none
select

Fired when the user clicks a visual entity. To learn what has been selected, call getSelection().

Properties: none


'WEB' 카테고리의 다른 글

[PHP] Parsing  (0) 2018.02.05
[PHP] number with comma  (0) 2018.02.05
[Google Chart] Google Charts - Basic Candlestick Chart  (0) 2018.01.29
[Google Chart] Candle Stick  (0) 2018.01.29
[PHP] addslashes  (0) 2018.01.24
728x90

Following is an example of a basic candlestick chart. A candlestick chart is generally used to show an opening and closing value which are overlaid on top of a total variance. Candlestick charts are often used to show stocks value behavior. In this chart, filled boxes are drawn for items where the opening value is less than the closing value (a gain) and , and hollow boxes are drawn where the opening value of item is more than the closing value (a loss). We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example.

Configurations

We've used CandlestickChart class to show candlestick based chart.

//candlestick chart
var chart = new google.visualization.CandlestickChart
(document.getElementById('container'));

Example

googlecharts_candlestick_basic.htm

<html>
   <head>
      <title>Google Charts Tutorial</title>
      <script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js">
      </script>
      <script type = "text/javascript">
         google.charts.load('current', {packages: ['corechart']});     
      </script>
   </head>
   
   <body>
      <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto">
      </div>
      <script language = "JavaScript">
         function drawChart() {
            // Define the chart to be drawn.
            var data = google.visualization.arrayToDataTable([
               ['Mon', 20, 28, 38, 45],
               ['Tue', 31, 38, 55, 66],
               ['Wed', 50, 55, 77, 80],
               ['Thu', 77, 77, 66, 50],
               ['Fri', 68, 66, 22, 15]
               // Treat first row as data as well.
            ], true);
              
            // Set chart options
            var options = {legend: 'none'};

            // Instantiate and draw the chart.
            var chart = new google.visualization.CandlestickChart(document.getElementById('container'));
            chart.draw(data, options);
         }
         google.charts.setOnLoadCallback(drawChart);
      </script>
   </body>
</html>

Result

Verify the result.

728x90

https://www.wikitechy.com/tutorials/google-charts/google-charts-basic-candlestick-chart

728x90

Description ¶

string addslashes ( string $str )

Returns a string with backslashes added before characters that need to be escaped. These characters are:

  • single quote (')
  • double quote (")
  • backslash (\)
  • NUL (the NUL byte)

A use case of addslashes() is escaping the aforementioned characters in a string that is to be evaluated by PHP:

<?php
$str 
"O'Reilly?";
eval(
"echo '" addslashes($str) . "';");
?>

Prior to PHP 5.4.0, the PHP directive magic_quotes_gpc was on by default and it essentially ran addslashes() on all GET, POST and COOKIE data. addslashes() must not be used on strings that have already been escaped with magic_quotes_gpc, as the strings will be double escaped. get_magic_quotes_gpc() can be used to check if magic_quotes_gpc is on.

The addslashes() is sometimes incorrectly used to try to prevent SQL Injection. Instead, database-specific escaping functions and/or prepared statements should be used.

Parameters ¶

str

The string to be escaped.

Return Values ¶

Returns the escaped string.

Examples ¶

Example #1 An addslashes() example

<?php
$str 
"Is your name O'Reilly?";

// Outputs: Is your name O\'Reilly?
echo addslashes($str);
?>

See Also ¶

add a note add a note

User Contributed Notes 38 notes

wyattstorch42 at outlook dot com ¶
3 years ago
@ mark at hagers dot demon dot nl :

You shouldn't use str_replace() for this. Use a function like htmlentities(), which will properly encode all user input for fields. That way, it will also work if the user types &, <, >, etc.
roysimke at microsoftsfirstmailprovider dot com ¶
7 years ago
Never use addslashes function to escape values you are going to send to mysql. use mysql_real_escape_string or pg_escape at least if you are not using prepared queries yet.

keep in mind that single quote is not the only special character that can break your sql query. and quotes are the only thing which addslashes care.
mark at hagers dot demon dot nl ¶
13 years ago
I was stumped for a long time by the fact that even when using addslashes and stripslashes explicitly on the field values double quotes (") still didn't seem to show up in strings read from a database. Until I looked at the source, and realised that the field value is just truncated at the first occurrence of a double quote. the remainder of the string is there (in the source), but is ignored when the form is displayed and submitted.

This can easily be solved by replacing double quotes with "&quot;" when building the form. like this:
$fld_value =  str_replace ( "\"", "&quot;", $src_string ) ;
The reverse replacement after the form submission is not necessary.
svenr at selfhtml dot org ¶
6 years ago
To output a PHP variable to Javascript, use json_encode().

<?php

$var 
"He said \"Hello O'Reilly\" & disappeared.\nNext line...";
echo 
"alert(".json_encode($var).");\n";

?>

Output:
alert("He said \"Hello O'Reilly\" & disappeared.\nNext line...") ;
hoskerr at nukote dot com ¶
15 years ago
Beware of using addslashes() on input to the serialize() function.   serialize() stores strings with their length; the length must match the stored string or unserialize() will fail.  

Such a mismatch can occur if you serialize the result of addslashes() and store it in a database; some databases (definitely including PostgreSQL) automagically strip backslashes from "special" chars in SELECT results, causing the returned string to be shorter than it was when it was serialized. 

In other words, do this... 

<?php 
$string
="O'Reilly"
$ser=serialize($string);    # safe -- won't count the slash 
$result=addslashes($ser); 
?> 

...and not this... 

<?php 
$string
="O'Reilly"
$add=addslashes($string);   # RISKY!  -- will count the slash 
$result=serialize($add); 
?> 

In both cases, a backslash will be added after the apostrophe in "O'Reilly"; only in the second case will the backslash be included in the string length as recorded by serialize(). 

[Note to the maintainers: You may, at your option, want to link this note to serialize() as well as to addslashes().  I'll refrain from doing such cross-posting myself...]
steve at teamITS dot com ¶
15 years ago
For thelogrus, my testing shows the opposite--that a slashed string is stored correctly by MySQL.  Consider

insert into test (field1) values ('test\'test')

...which is stored as "test'test".  If you were posting "Sir'Weaser" from a form to your script and have magic_quotes_gpc on, then the string is slashed already so if you run addslashes() again you will be entering "Sir\\'Weaser" into MySQL.  In that case "Sir\'Weaser" would be the correct output.

In summary, addslashes() is not necessary if magic_quotes_gpc is on.
Lars ¶
5 years ago
Even for simple json string backslash encodings, do not use this function. Some tests may work fine, but in json the single quote (') must not be escaped.
pulstar at ig dot com dot br ¶
11 years ago
May it is better use the function mysql_real_escape_string instead of addslashes when inserting data into a MySQL database. Check it at:

http://www.php.net/manual/en/function.mysql-real-escape-string.php
sam dot fullman at verizon ¶
10 years ago
There are other functions "kind of" like this one but this should help adding slashes to a form post which also contains arrays (and you can't access runtime quotes), or you need to add slashes to an array which is already stripped:

<?php
    
function addslashes_array($a){
        if(
is_array($a)){
            foreach(
$a as $n=>$v){
                
$b[$n]=addslashes_array($v);
            }
            return 
$b;
        }else{
            return 
addslashes($a);
        }
    }
?>

note this does not add slashes to the keys - you could easily modify to do this..
cliprz at gmail dot com ¶
6 years ago
<?php

/**
* @desc add slashes if use MySQL and check if function addslashes is exits else
* return to escape string in MySQL .
* same way its return to stripslashes function
* @param string $type any string u want to insert in MySQL and display from MySQL
* @param string $type must be add to add slashes and strip to strip slashes
* @author Yousef Ismaeil - cliprz@gmail.com
*/
function PHP_slashes($string,$type='add')
{
    if (
$type == 'add')
    {
        if (
get_magic_quotes_gpc())
        {
            return 
$string;
        }
        else
        {
            if (
function_exists('addslashes'))
            {
                return 
addslashes($string);
            }
            else
            {
                return 
mysql_real_escape_string($string);
            }
        }
    }
    else if (
$type == 'strip')
    {
        return 
stripslashes($string);
    }
    else
    {
        die(
'error in PHP_slashes (mixed,add | strip)');
    }
}

?>
Nate from RuggFamily.com ¶
10 years ago
If you want to add slashes to special symbols that would interfere with a regular expression (i.e., . \ + * ? [ ^ ] $ ( ) { } = ! < > | :), you should use the preg_quote() function.
php at slamb dot org ¶
15 years ago
spamdunk at home dot com, your way is dangerous on PostgreSQL (and presumably MySQL). You're quite correct that ANSI SQL specifies using ' to escape, but those databases also support \ for escaping (in violation of the standard, I think). Which means that if they pass in a string that includes a "\'", you expand it to "\'''" (an escaped quote followed by a non-escaped quote. WRONG! Attackers can execute arbitrary SQL to drop your tables, make themselves administrators, whatever they want.) 

The best way to be safe and correct is to: 

- don't use magic quotes; this approach is bad. For starters, that's making the assumption that you will be using your input in a database query, which is arbitrary. (Why not escape all "<"s with "&lt;"s instead? Cross-site scripting attacks are quite common as well.) It's better to set up a way that does whatever escaping is correct for you when you use it, as below: 

- when inserting into the database, use prepared statements with placeholders. For example, when using PEAR DB: 

<?php 
    $stmt 
$dbh->prepare('update mb_users set password = ? where username = ?'); 
    
$dbh->execute($stmt, array('12345''bob')); 
?> 

Notice that there are no quotes around the ?s. It handles that for you automatically. It's guaranteed to be safe for your database. (Just ' on oracle, \ and ' on PostgreSQL, but you don't even have to think about it.) 

Plus, if the database supports prepared statements (the soon-to-be-released PostgreSQL 7.3, Oracle, etc), several executes on the same prepare can be faster, since it can reuse the same query plan. If it doesn't (MySQL, etc), this way falls back to quoting code that's specifically written for your database, avoiding the problem I mentioned above. 

(Pardon my syntax if it's off. I'm not really a PHP programmer; this is something I know from similar things in Java, Perl, PL/SQL, Python, Visual Basic, etc.)
Adrian C ¶
10 years ago
What happends when you add addslashes(addslashes($str))? This is not a good thing and it may be fixed:

function checkaddslashes($str){        
    if(strpos(str_replace("\'",""," $str"),"'")!=false)
        return addslashes($str);
    else
        return $str;
}

checkaddslashes("aa'bb");  => aa\'bb
checkaddslashes("aa\'bb"); => aa\'bb
checkaddslashes("\'"); => \'
checkaddslashes("'");  => \'

Hope this will help you
Krasimir Slavov kkslavov at yahoo dot com ¶
12 years ago
If you have problems with adding images or other binady data with addslashes() for php 4.3 >= use:

<?php
$search 
= array("\x00""\x0a""\x0d""\x1a""\x09");
$replace = array('\0''\n''\r''\Z' '\t');

$chrData .= str_replace($search$replace$Data );
?>

and put in your SQL field='$chrData' ! please remark quotes
David Spector ¶
4 years ago
If all you want to do is quote a string as you would normally do in PHP (for example, when returning an Ajax result, inside a json string value, or when building a URL with args), don't use addslashes (you don't want both " and ' escaped at the same time). Instead, just use this function:

<?php
function Quote($Str// Double-quoting only
    
{
    
$Str=str_replace('"','\"',$Str);
    return 
'"'.$Str.'"';
    } 
// Quote
?>

Modify this easily to get a single-quoting function.
yoder2 at purdue dot edu ¶
10 years ago
to quote boris-pieper AT t-online DOT de, 15-Jan-2005 06:07,

Note: You should use mysql_real_escape_string() (http://php.net/mysql_real_escape_string) if possible (PHP => 4.3.0) instead of mysql_escape_string().

You may also want to us it instead of addslashes.
phil at internetprojectmanagers dot com ¶
14 years ago
re: problem with mcrypt, addslashes and mysql 

Here is my solution to the problem of characters from mcrypt creating issues with mysql calls (due to characters which aren't cleaned up by addslashes). 

Solution: simply convert your encryption string to hex, then back to binary when you are ready to decrypt. 

<?php 
// ie. 
$encrypted addslashes($string);    
$encrypted bin2hex($encrypted); 

// ... then: 
$decrypted hex2bin($encrypted); 
$decrypted stripslashes($decrypted); 

// where hex2bin() is: 
function hex2bin($hexdata) { 
  
$bindata=""
  
  for (
$i=0;$i<strlen($hexdata);$i+=2) { 
    
$bindata.=chr(hexdec(substr($hexdata,$i,2))); 
  } 

  return 
$bindata

?> 

One word of caution: this will increase the length of your initial data string, so you will need to increase the field length for your mysql database. 

Cheers, Phil 
PS. I knew that I'd eventually be able to give something back to the site!
unsafed ¶
12 years ago
addslashes does NOT make your input safe for use in a database query! It only escapes according to what PHP defines, not what your database driver defines. Any use of this function to escape strings for use in a database is likely an error - mysql_real_escape_string, pg_escape_string, etc, should be used depending on your underlying database as each database has different escaping requirements. In particular, MySQL wants \n, \r and \x1a escaped which addslashes does NOT do. Therefore relying on addslashes is not a good idea at all and may make your code vulnerable to security risks. I really don't see what this function is supposed to do.
hybrid at n0spam dot pearlmagik dot com ¶
16 years ago
Remember to slash underscores (_) and percent signs (%), too, if you're going use the LIKE operator on the variable or you'll get some unexpected results.
DarkHunterj ¶
8 years ago
Based on:
Danijel Pticar
05-Aug-2009 05:22
I recommend this extended version, to replace addslashes altogether(works for both strings and arrays):
<?php
function addslashesextended(&$arr_r)
{
    if(
is_array($arr_r))
    {
        foreach (
$arr_r as &$val)
            
is_array($val) ? addslashesextended($val):$val=addslashes($val);
        unset(
$val);
    }
    else
        
$arr_r=addslashes($arr_r);
}
?>
leocullen at fastmail dot fm ¶
8 years ago
this is my version of an addslashes function, useful for processing $_POST array: 

<?php 
function add_slashes ($an_array) { 
  foreach (
$an_array as $key => $value) { 
    
$new_array[$key] = addslashes($an_array[$key]); 
  } 

?> 

then call it: 

<?php add_slashes($_POST); ?>
stuart at horuskol dot co dot uk ¶
9 years ago
Be careful on whether you use double or single quotes when creating the string to be escaped:

$test = 'This is one line\r\nand this is another\r\nand this line has\ta tab';

echo $test;
echo "\r\n\r\n";
echo addslashes($test);

$test = "This is one line\r\nand this is another\r\nand this line has\ta tab";

echo $test;
echo "\r\n\r\n";
echo addslashes($test);
Raymond Hofman ¶
9 years ago
In addition to the post made by Aditya P Bhatt below. This code works fine for posting a single string but does not work for posting arrays.
Aditya P Bhatt (adityabhai at gmail dot com) ¶
9 years ago
Automagically add slashes to $_POST variables. It helps to prevent some sql injection attacks. Also works with $_GET variables. 

FILE NAME: input_cl.php
<?php
//create array to temporarily grab variables
$input_arr = array();
//grabs the $_POST variables and adds slashes
foreach ($_POST as $key => $input_arr) {
    
$_POST[$key] = addslashes($input_arr);
}
?>

Just put this at the top of your script that gets the variables. Here is an example.

Usage Example
<?php
include("input_cl.php");
// all $_POST variables have slashes added to them
$f_name $_POST["f_name"];
$l_name $_POST["l_name"];
$phone_num $_POST["phone_num"];
$address1 $_POST["address1"];
$address2 $_POST["address2"];
$city $_POST["city"];
$State $_POST["State"];
$zip $_POST["zip"];

//sql insert code goes here.
?>
luciano at vittoretti dot com dot br ¶
12 years ago
Note, this function wont work with mssql or access queries.
Use the function above (work with arrays too).

function addslashes_mssql($str){
    if (is_array($str)) {
        foreach($str AS $id => $value) {
            $str[$id] = addslashes_mssql($value);
        }
    } else {
        $str = str_replace("'", "''", $str);    
    }
    
    return $str;
}

function stripslashes_mssql($str){
    if (is_array($str)) {
        foreach($str AS $id => $value) {
            $str[$id] = stripslashes_mssql($value);
        }
    } else {
        $str = str_replace("''", "'", $str);    
    }

    return $str;
}
thisisroot at gmail dot com ¶
12 years ago
In response to Krasimir Slavov and Luiz Miguel Axcar:

There are several encoding schemes for inserting binary data into places it doesn't typically belong, such as databases and e-mail bodies. Check out the base64_encode() and convert_uuencode() functions for the details.
Luiz Miguel Axcar (lmaxcar at yahoo dot com dot br) ¶
12 years ago
Hello,

If you are getting trouble to SGDB write/read HTML data, try to use this:

<?php

//from html_entity_decode() manual page
function unhtmlentities ($string) {
   
$trans_tbl =get_html_translation_table (HTML_ENTITIES );
   
$trans_tbl =array_flip ($trans_tbl );
   return 
strtr ($string ,$trans_tbl );
}

//read from db
$content stripslashes (htmlspecialchars ($field['content']));

//write to db
$content unhtmlentities (addslashes (trim ($_POST['content'])));

//make sure result of function get_magic_quotes_gpc () == 0, you can get strange slashes in your content adding slashes twice

//better to do this using addslashes
$content = (! get_magic_quotes_gpc ()) ? addslashes ($content) : $content;

?>
hazy underscore fakie at ringwraith dot org ¶
14 years ago
Note that when using addslashes() on a string that includes cyrillic characters, addslashes() totally mixes up the string, rendering it unusable.
phil at internetprojectmanagers dot com ¶
14 years ago
re: encryption, addslashes and mysql

Note that mcrypt encryption may add in an apostrophe from the ascii table which cannot be protected by addslashes. It may not even be on your keyboard.

Because encryption strings are random, you may not discover it unless you test (or stumble?) on the correct sequence which inserts an apostrophe in the encrypted string. 

This means that testing is even more important where encryption is concerned. If I create a solution I'll post it here.

Phil
php at NO_SPAMj-w3 dot com ¶
16 years ago
As mentioned, magic_quotes_gpc automatically adds slashes to POST and GET data and these slashes don't go in the database.  BUT, be careful of this. If you have a form with an error check, make sure you strip the slashes if your form remembers the OK fields, so the user doesn't view these automagically added slashes.
joechrz at gmail dot com ¶
11 years ago
Here's an example of a function that prevents double-quoting, I'm surprised noone has put something like this up yet... (also works on arrays)

<?php
function escape_quotes($receive) {
    if (!
is_array($receive))
        
$thearray = array($receive);
    else
        
$thearray $receive;
    
    foreach (
array_keys($thearray) as $string) {
        
$thearray[$string] = addslashes($thearray[$string]);
        
$thearray[$string] = preg_replace("/[\\/]+/","/",$thearray[$string]);
    }
    
    if (!
is_array($receive)) 
        return 
$thearray[0];
    else
        return 
$thearray;
}
?>
Danijel Pticar ¶
8 years ago
Hi, 
I use this recursive function for POST. It handles multidimensional arrays. 

<?php 
function as_array(&$arr_r

foreach (
$arr_r as &$valis_array($val) ? as_array($val):$val=addslashes($val); 
unset(
$val); 


as_array($_POST); 
?>
Picky ¶
11 years ago
This function is deprecated in PHP 4.0, according to this article:

http://www.newsforge.com/article.pl?sid=06/05/23/2141246

Also, it is worth mentioning that PostgreSQL will soon start to block queries involving escaped single quotes using \ as the escape character, for some cases, which depends on the string's encoding.  The standard way to escape quotes in SQL (not all SQL databases, mind you) is by changing single quotes into two single quotes (e.g, ' ' ' becomes ' '' ' for queries).

You should look into other ways for escaping strings, such as "mysql_real_escape_string" (see the comment below), and other such database specific escape functions.
qeremy [atta] gmail [dotta] com ¶
5 years ago
Actually I prefer to escape the SQL queries completely (then no more challenge for data security);

<?php
function escape_query($str) {
    return 
strtr($str, array(
        
"\0" => "",
        
"'"  => "&#39;",
        
"\"" => "&#34;",
        
"\\" => "&#92;",
        
// more secure
        
"<"  => "&lt;",
        
">"  => "&gt;",
    ));
}
?>

// &#39;&#34;&#92;
echo escape_query("'\"\\\0");

// &lt;script&gt;alert(1)&lt;/script&gt;
echo escape_query("<\0script>alert(1)<\0/script>");

// See more: www.asciitable.com
gv ¶
13 years ago
Regarding the previous note using addslashes/stripslahes with regular expressions and databases it looks as if the purpose of these functions gets mixed.

addslahes encodes data to be sent to a database or something similar. Here you need addslashes because you send commands to the database as command strings that contain data and thus you have to escape characters that are special in the command language like SQL.

Therefore the use of addslahses on a regex does properly store the regex in the database.

stripslashes does the opposite: it decodes an addslashes encoded string. However, retrieving data from a database works differently: it does not go through some string interpretation because you actually retrieve your binary data in your variables. In other words: the data stored in your variable is the unmodified binary data that your database returned. You do not run stripslahes on data returned from a database. That way, the regexs are retrieved correctly, too.

This is different from other data exchange like urlencoded strings that you exchange with your browser. Here the data channel uses the same encodings in both directions: therefore you have to encode data to be sent and you have to decode data received.
Taslim Sohel (sohel62 at yahoo dot com) ¶
9 years ago
About Raymond and Aditya's post

Following code can help you to add slashes with posted array.
I just added a recursive function with Aditya's code.

<?php
//create array to temporarily grab variables
$input_arr = array();
//grabs the $_POST variables and adds slashes
foreach ($_POST as $key => $input_arr) {
    if(
is_array($input_arr)){        
        
$_POST[$key] = addslashes_array($input_arr);
    }else{
        
$_POST[$key] = addslashes($input_arr);
    }
    
}

// Recursive Function to add slashes with posted array.
function addslashes_array($input_arr){
    if(
is_array($input_arr)){
        
$tmp = array();
        foreach (
$input_arr as $key1 => $val){
            
$tmp[$key1] = addslashes_array($val);
        }
        return 
$tmp;
    }else{
        return 
addslashes($input_arr);
    }
}

?>
guy_AT_datalink_DOT_net_DOT_au ¶
15 years ago
If you're trying to escape quotes in a javascript event as such:

<img src="foo.gif" OnMouseOver="alert('<? print $myString ?>')">

It helps to perform this first:

$myString = str_replace("'", "\'", $myString);
$myString = str_replace('"', "'+String.fromCharCode(34)+'", $myString);
boyaqb at gmail dot com ¶
6 years ago
so you can use replace single quote and double quote with HTML Entities

for example

<?php
/**
* replcae quotes to HTML entities by names or numbers
*
* @param (string) escaped string value
* @param (string) default ='number' will be return to number entities you can use ='name' to return name entities
* Note : don't use ='name' coz (&apos;) (does not work in IE)
*/
function quote2entities($string,$entities_type='number')
{
    
$search                     = array("\"","'");
    
$replace_by_entities_name   = array("&quot;","&apos;");
    
$replace_by_entities_number = array("&#34;","&#39;");
    
$do null;
    if (
$entities_type == 'number')
    {
        
$do str_replace($search,$replace_by_entities_number,$string);
    }
    else if (
$entities_type == 'name')
    {
        
$do str_replace($search,$replace_by_entities_name,$string);
    }
    else
    {
        
$do addslashes($string);
    }
    return 
$do;
}

echo 
quote2entities("I love 'PHP' for ever");
// will return I love 'PHP' for ever in browsere
// but in view code and database will be  I love &#34;PHP&#34; for ever in source
?>


+ Recent posts