Retrieving the data from database for google charts using PHP - php

I have return an php code which is used to connect my MYSQL database and get the data from DB. This data will be used in the google charts for generating a chart.
But my problem was I was getting an errors "Failed to load resource file:///C:/wamp/www/jquery-1.6.2.min.js " and "Uncaught Error: Invalid JSON string: "
I know that they are many things available still I could not able to understand my problem. means how to rectify it.
My data base is like
id Q1-ans q2-ans
21 50 40
23 40 60
My code follows here
<html>
<head>
<title></title>
</head>
<?php
$con=mysql_connect("localhost","root","") or die("Failed to connect with database!!!!");
mysql_select_db("mobiledb", $con);
// The Chart table contains two fields: weekly_task and percentage
// This example will display a pie chart. If you need other charts such as a Bar chart, you will need to modify the code a little to make it work with bar chart and other charts
$sth = mysql_query("SELECT `id`, `Q1`, `Q2` FROM `table2` WHERE `id`=8710058770");
$rows = array();
//flag is not needed
$flag = true;
$table = array();
$table['cols'] = array(
// Labels for your chart, these represent the column titles
// Note that one column is in "string" format and another one is in "number" format as pie chart only required "numbers" for calculating percentage and string will be used for column title
array('label' => 'id', 'type' => 'number'),
array('label' => 'Q1', 'type' => 'number'),
array('label' => 'Q2', 'type' => 'number')
);
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$temp = array();
// the following line will be used to slice the Pie chart
$temp[] = array('v' => (int) $r['id']);
// Values of each slice
$temp[] = array('v' => (int) $r['Q1']);
$temp[] = array('v' => (int) $r['Q2']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
?>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="jquery-1.6.2.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable('<?=$jsonTable?>');
var options = {
title: 'My values',
is3D: 'true',
width: 800,
height: 600
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
<body>
<!--Div that will hold the chart-->
<div id="chart_div" ></div>
</body>
</html>

I suspect that the problem is the quotes in this line:
data.addRows('<?php $data ?>');
as they are taking what should be an array of arrays and turning it into a string. Try removing the quotes:
data.addRows(<?php $data ?>);
and running the script again. If that doesn't fix the problem, either post a link to the page or the generated javascript (open the page in a browser, copy the source code from there) so I can take a look.

you must change:
var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);

Related

How to use <?php echo $data; ?> in order to populate a Google chart

I am currently working on a project at university which involves sampling values
(CO2, temperature, humidity ...) to a SQLite3 database with a Raspberry Pi and using a webinterface to show the data.
I'm fairly new to php/html, but I have no problems understanding what the code does.
I already found a german tutorial describing how to create a php/html script which imports the data from the SQLite database and uses Google Graphs in order to display it. I used the provided code as the base for my script.
This is what I have so far:
<?php
require_once("config.php");
require_once("functions.php");
//------------------------ PHP Settings ----------------------------------------
ini_set('track_errors', 1);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set("memory_limit","64M");
ini_set("max_execution_time","30");
#ob_implicit_flush(true);
#ob_end_flush();
$_SELF=$_SERVER['PHP_SELF'];
$SQL="SELECT CO2, Temperature FROM value";
$db = db_con($DBfile);
$q = db_query($SQL);
$data = "var data = new google.visualization.DataTable();<br>"
."data.addColumn('number', 'CO2');<br>"
."data.addColumn('number', 'Temperature');<br><br>"
."data.addRows([<br>";
while ($res = $q->fetch(PDO::FETCH_ASSOC)) {
$temp = (int)$res['Temperature'];
$co2 = (int)$res['CO2'];
$data = $data." [".$temp.", ".$co2."],<br>";
}
$data = $data."]);<br>";
//Print data to check if data from database is loaded
echo $data;
?>
<html>
<head>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></sc$
<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() {
<?php echo $data; ?>
var options = {
title: 'Air Quality',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('temp_curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="temp_curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>
Now the problem is, that the graph does not show up.
If I add echo $data;the content of the variable shows up in the browser, which means that the import part is working, but I just can't get it to display the graph.
var data = new google.visualization.DataTable();
data.addColumn('number', 'CO2');
data.addColumn('number', 'Temperature');
data.addRows([
[23, 500],
[23, 500],
[25, 600],
]);
I suspect it has something to do with the following line of code or with the way the $data variable is set up:
function drawChart() {
<?php echo $data; ?>
If I replace it with code from the example provided by Google, it shows the graph just fine.
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
I already spent hours trying to get it work, but I just can't get it right.
Any help/tips would be greatly appreciated!
Thanks in advance!
I found two things:
first is this line
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></sc$
must be
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
secondly remove all
<br>
in your JavaScript and replace (not necessary, because it is just an visual effect in the source code) with \n\r
like
$data = "var data = new google.visualization.DataTable();\n\r"
."data.addColumn('number', 'CO2');\n\r"
."data.addColumn('number', 'Temperature');\n\r\n\r"
."data.addRows([\n\r";
while ($res = $q->fetch(PDO::FETCH_ASSOC)) {
$temp = (int)$res['Temperature'];
$co2 = (int)$res['CO2'];
$data = $data." [".$temp.", ".$co2."],\n\r";
}
$data = $data."]);\n\r";
And you will get a nice looking graph!

Google CHARTS using json and $_GET and $_POST method

I need some help,I'm using google charts api but when I try to get some parameters using POST and GET it doesn't draw the chart.
How can I improve the code to achieve the task?
Thanks in advance
sql query:
SELECT answers,COUNT(*) as count FROM surveys
where company_area ='human resources' and date >= '2014-11-01' and
date <= '2014-12-31'GROUP BY answers ORDER BY count DESC
phpmyadmin's result after run the query.
Answers count(*)
YES 23
NO 1
json output.
{"cols":
[ {"label":"Answers",
"type":"string"},{"label":"Answers","type":"number"}],
"rows":[
{"c":[{"v":"YES"},{"v":23}]},
{"c":[{"v":"NO"},{"v":1}]
}]}
get_json.php
<?php
$con = mysql_connect('localhost', 'root', '') or die('Error connecting to server');
mysql_select_db('sistema_encuestas', $con);
$q = $_GET['q'];
$a = $_GET['a'];
// write your SQL query here (you may use parameters from $_GET or $_POST if you need them)
$query = mysql_query("SELECT areas_evaluacion.nombre_area, AVG(encuestas.respuestas) AS Promedio
FROM encuestas
INNER JOIN areas_evaluacion on areas_evaluacion.id = encuestas.id_area_evaluacion
WHERE encuestas.fechaentrevista>='".$q."' and encuestas.fechaentrevista<='".$a."'
Group by encuestas.id_area_evaluacion
");
$table = array();
$table['cols'] = array(
array('label' => 'respuestas', 'type' => 'string'),
array('label' => 'Respuestas', 'type' => 'number')
);
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$temp = array();
// each column needs to have data inserted via the $temp array
$temp[] = array('v' => $r['nombre_area']);
//$temp[] = array('v' => (int)$r['id_area_evaluacion']);
$temp[] = array('v' => (float)$r['Promedio']); // typecast all numbers to the appropriate type (int or float) as needed - otherwise they are input as strings
// insert the temp array into $rows
$rows[] = array('c' => $temp);
}
// populate the table with rows of data
$table['rows'] = $rows;
// encode the table as JSON
$jsonTable = json_encode($table);
// set up header; first two prevent IE from caching queries
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
// return the JSON data
echo $jsonTable;
?>
chart.php
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart(num,num2) {
var json = $.ajax({
url: 'get_json_areas_por_dia.php', // make this url point to the data file
dataType: 'json',
data: "q="+num ,"a="+num2,
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(json);
var options = {
title: 'Estadísticas por Áreas Por dia',
is3D: 'true',
width: 800,
height: 600
};
// Instantiate and draw our chart, passing in some options.
//do not forget to check ur div ID
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<form>
<input type="date" name="date1" onchange="drawChart(this.value)">
<input type="date" name="date2" onchange="drawChart(this.value)">
<select name="users" onchange="drawChart(this.value)">
</form>
<div id="chart_div"></div>
</body>
</html>
I fixed it by adding the missing ' in the json url
PHP
echo ' {"cols":
[ {"label":"Answers",
"type":"string"},{"label":"Answers","type":"number"}],
"rows":[
{"c":[{"v":"YES"},{"v":23}]},
{"c":[{"v":"NO"},{"v":1}]
}]}';
HTML
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var json = $.ajax({
url: 'get_json.php', // make this url point to the data file
dataType: 'json',
async: false,
type: 'GET'
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(json);
var options = {
title: 'My Weekly Plan',
is3D: 'true',
width: 800,
height: 600
};
// Instantiate and draw our chart, passing in some options.
//do not forget to check ur div ID
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
setInterval(drawChart, 500 );
}
</script>
<div id="chart_div"></div>
</body>
</html>

Google Chart - how to user php variable to change data source

Using basic Google Chart php/mysql/javascript/html setup, where php used to retrieve data from mysql, javascript to setup chart, and then html and div pull chart in html.
But I want to change the datasource based on a user input. So i thought i would use a php variable sent via url.
I thought I would watch for the variable in my 'dbconnect.php' file, which is included in the php file that retrieves mysql data, using $_GET['var'], to change datasource based on the variable sent in url eg php?var (using a switch statement). This works fine, I can see var sent in url with an echo.
However, I expected that the javascript url: "getDataUsers.php" part would run the getDataUsers.php file to get the data from different datasource based on url passed variable. But instead nothing happens.
What am i missing? Thanks.
My index.php file:
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
//added javascript variable for site from php url
**var vsite = "<?php echo $_GET['site']; ?>";**
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChartUsers);
function drawChartUsers() {
var jsonDataUsers = $.ajax({
url: "getDataUsers.php",
dataType:"json",
async: false**,
//added data value for site from js variable vsite
data: {site: vsite }**
}).responseText;
// Create our data table out of JSON data loaded from server.
var dataUsers = new google.visualization.DataTable(jsonDataUsers);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('users_chart_div'));
chart.draw(dataUsers, {
title:'# New Registered Users',
width: 1000,
height: 300,
legend : 'none',
vAxis:{title:'# users',textStyle:{color: '#005500',fontSize: '10', paddingRight: '100',marginRight: '100'}},
hAxis: { title: 'Date', textStyle: { color: '#005500', fontSize: '10', paddingRight: '100', marginRight: '100'} }});
}
</script>
</head>
<body>
<p>
a-details a</br>
b-details b</br>
c-details c</br>
d-details d</br>
</p>
<!--Div that will hold the charts-->
<div id="users_chart_div"></div>
</body>
</html>
My dbconnect.php file:
<?php
$site = $_GET['site'];
//echo "<p>I connected. The variable is: " . $site . "</p>";
switch ($site)
{
case 'a':
$server = 'server.com';
$username='a';
$password='a';
$database='a';
break;
case 'b':
$server = 'server.com';
$username='b';
$password='b';
$database='b';
break;
case 'c':
$server = 'server.com';
$username='c';
$password='c';
$database='c';
break;
case 'd':
$server = 'server.com';
$username='d';
$password='d';
$database='d';
break;
default:
echo "No database selected";
}
mysql_connect($server,$username,$password);
#mysql_select_db($database) or die( 'Unable to select database');
php?>
My 'getDataUsers.php' file:
<?php
include 'dbconnect.php';
$query =mysql_query("SELECT
YEAR(created) AS Created_Year,
MONTH(created) AS Created_Month,
DAY(created) AS Created_Day,
count(id) AS NumUsers
FROM users
Group by
YEAR(created),
MONTH(created),
DAY(created)
ORDER BY
YEAR(created) ASC,
MONTH(created) ASC,
DAY(created) ASC");
$table = array();
$table['cols'] = array(
/* define your DataTable columns here
* each column gets its own array
* syntax of the arrays is:
* label => column label
* type => data type of column (string, number, date, datetime, boolean)
*/
array('label' => 'Date', 'type' => 'string'),
array('label' => '# Users', 'type' => 'number')
);
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$temp = array();
// each column needs to have data inserted via the $temp array
$temp[] = array('v' => $r['Created_Year'] . '-' . $r['Created_Month']. '-' . $r['Created_Day']);
$temp[] = array('v' => (int) $r['NumUsers']);
// insert the temp array into $rows
$rows[] = array('c' => $temp);
}
// populate the table with rows of data
$table['rows'] = $rows;
// encode the table as JSON
$jsonTable = json_encode($table);
// set up header; first two prevent IE from caching queries
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
// return the JSON data
echo $jsonTable;
?>
You aren't passing any data with the AJAX call. You need to set the data parameter of the AJAX call to include a site parameter:
var jsonDataUsers = $.ajax({
url: "getDataUsers.php",
dataType:"json",
async: false,
data: {
site: 'a' // set the site parameter here as appropriate
}
}).responseText;

Google charts are not displaying with new release

This is the my code i am using for column chart before the new release of Google Api and it is working fine. Now my chart is not displaying. i have checked the new release changes but i found noting relevant. the first problem appears with the data type in array, float data type is not legal and if i replaced it with some other data type then chart still not displayed. if i change the float to string then error will appear that string data type will not be used on X-axis. I have plotted time on X-axis and Distance on Y-axis. If any one knows how to change the code according to new release of Google Api please share your code or some information.
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="mysql"; // Database name
$tbl_name="gprs"; // Table name
// Connect to server and select database.
$con=mysql_connect("$host", "$username")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$data = mysql_query("select SUM(Distance) as Distance, CAST( Time AS date) as Time from gprs where DeviceId=25 and Time between '2013-08-08' and '2013-09-31' group by CAST(Time AS date) order by CAST( Time AS date)")
or die(mysql_error());
$table = array();
$table['cols'] = array(
array('label' => 'TIME', 'type' => 'string'),
array('label' => 'Distance', 'type' => 'float')
);
$rows = array();
while ($nt = mysql_fetch_assoc($data))
{
$temp = array();
$temp[] = array('v' => (string)$nt['TIME']);
$temp[] = array('v' =>(float) $nt['Distance']);
$rows[]['c'] = $temp;
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>
Google Visualization API Sample
</title>
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart']});
</script>
<script type="text/javascript">
function drawVisualization() {
// Create and populate the data table.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
// Create and draw the visualization.
new google.visualization.ColumnChart(document.getElementById('visualization')).
draw(data);
}
google.setOnLoadCallback(drawVisualization);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="visualization" style="width: 600px; height: 300px;"></div>
</body>
</html>
I have solved the above problem. Replace the above array with this
array('label' => 'TIME', 'type' => 'string'),
array('label' => 'fuel', 'type' => 'number')
and this $temp[] = array('v' => $nt['TIME']);
$temp[] = array('v' => $nt['fuel']);
and don't use the Packages: columnchart now it is replaced by corechart in new Api release

Json could not fetch table column in Google chart using php and mysql

I am trying to create google chart using google api which works fine for this:
<?php
echo "hi";
$mysqli =mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
$result = $mysqli->query('SELECT * FROM new_view');
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'ind_type', 'type' => 'string'),
array('label' => 'Index_val', 'type' => 'number')
);
/* Extract the information from $result */
foreach($result as $r) {
$temp = array();
// The following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['ind_type']);
// Values of the each slice
$temp[] = array('v' => (int) $r['Index_val']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
// convert data into JSON format
$jsonTable = json_encode($table);
//echo $jsonTable;
?>
<html>
<head>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
title: 'Index analysis',
is3D: 'true',
width: 800,
height: 600
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--this is the div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
But Now I tried with taking html part in another file and database part in another like this:
ajax_form_temp.php
<html>
<head>
<!--Load the Ajax API-->
<meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
<meta content="utf-8" http-equiv="encoding" />
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonTable = $.ajax({
url:"ajax_graph_temp.php",
dataType:"json",
async:true
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonTable);
var options = {
title: 'Index analysis',
is3D: 'true',
width: 800,
height: 600
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--this is the div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
and ajax_graph_temp.php
<?php
$mysqli =mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
$result = $mysqli->query('SELECT * FROM new_view');
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'ind_type', 'type' => 'string'),
array('label' => 'Index_val', 'type' => 'number')
);
/* Extract the information from $result */
foreach($result as $r) {
$temp = array();
// The following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['ind_type']);
// Values of the each slice
$temp[] = array('v' => (int) $r['Index_val']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
// convert data into JSON format
$jsonTable = json_encode($table);
echo $jsonTable;
?>
Code is same. Just in 2nd methods fetch table data using json.
But at line var data = new google.visualization.DataTable(jsonTable); jsonTable could not fetch column, though it exist.
And in browser: Table has no column error comes! Column are alread declared $table['cols'] = array(
array('label' => 'ind_type', 'type' => 'string'),
array('label' => 'Index_val', 'type' => 'number')
Where is the problem?
This does not answer your question, but here is a way how you can do it.
First of all restore the working version by checking it out again from version control.
Then do little edits to the wroking code where you check that - after each edit - the code still works.
In these little edits you move parts of the code first into function definitions and then - if still working - those function definitions into a new file that you include.
After each little edit do a commit so that you granulary can step back or diff to review in which lines of code you exactly introduced the error.
By creating function and moving them out in part you can easily do what you'd like to do. Doing all at once can introduce many errors and is not helpful to review quickly.
Hope this help.
See as well:
PHP file cannot enter some part of code

Categories