I have written a page that will scan a site and then extract certain code from the source. That part is working successfully, however I want to run this over multiple pages and dump the details into a database. I am stuggling to get the loop working, this is what I currently have:
date_default_timezone_set("australia/sydney");
$host = 'http://www.tabonline.com.au/';
$day = date(d);
$month = date(m);
$year = date(Y);
$slash = '/';
$mtgraces = '/mtgraces.html';
//Gallops Meetings on Todays racing page
$content = file_get_contents($host . $year . "/". $month . "/" . $day . $mtgraces);
preg_match_all('#<a[^<>]+href\s*=\s*[\'"](.R[0-9]+.html*)[\'"]#i', $content, $matches);
foreach ($matches[1] as $url) $links[] = "$host$year$slash$month$slash$day$slash$url";
//get the runners from each page
for($c=0; $c<count($links); $c++)
$racepage = file_get_contents($links[$i]);
preg_match_all('#<td align="right" height="18"><font color="\#ffffff">[0-9]{1,2}</font></td>#', $racepage, $number);
preg_match_all('#<font color="\#00ffff">[0-9]{1,3}</font>#', $racepage, $rating);
preg_match_all('#<B>[\w]+([\s][A-Z]+)?</B>#', $racepage, $location);
preg_match_all('#<B>[\w]+\s[0-9]+</B>#', $racepage, $locationcode);
//strip tags for storage in DB
$number_data = implode(",", $number[0]);
$dbnumber = strip_tags($number_data);
$final_number = explode(",", $dbnumber);
$rating_data = implode(",", $rating[0]);
$dbrating = strip_tags($rating_data);
$final_rating = explode(",", $dbrating);
$location_data = implode(",", $location[0]);
$dblocation = strip_tags($location_data);
$final_location = explode(",", $dblocation);
$locationcode_data = implode(",", $locationcode[0]);
$dblocationcode = strip_tags($locationcode_data);
$final_locationcode = explode(",", $dblocationcode);
//Insert into database
$data = array();
for($i=0; $i<count($final_number); $i++)
{
$data[] = "('" . $final_location[0] . "', '" . $final_locationcode[0] . "', '" . $final_number[$i] . "', '" . $final_rating[$i] . "')";
}
if(count($queries) == 0)
{
# Nothing passed
# exit
}
$query = "insert into ratings(location, location_code, tab_no, rating) values " . implode(", ", $data);
$hostname = "%hostname%"; // eg. mysql.yourdomain.com (unique)
$username = "%username%"; // the username specified when setting-up the database
$password = "%password"; // the password specified when setting-up the database
$database = "%database"; // the database name chosen when setting-up the database (unique)
mysql_connect($hostname,$username,$password);
mysql_select_db($database) or die("Unable to select database");
mysql_query($query) OR die(mysql_error())
At the moment the output for this is giving me the correct contents of the last page in the list of sites (the $links variable). Ultimately I want it to loop through the whole $links variable and then import that data, using the $query variable, into a database so I can do further analysis on it.
I hope this makes sense and you can see the error in my ways.
Hmm... There are a few issues in here...
for($c=0; $c<count($links); $c++)
This loop is executing just the next line:
$racepage = file_get_contents($links[$i]);
However, $i isn't defined, I suspect you want $c. Also, you need to place some braces around various parts... Now, this is untested, but I think you want something like:
date_default_timezone_set("australia/sydney");
$host = 'http://www.tabonline.com.au/';
$day = date(d);
$month = date(m);
$year = date(Y);
$slash = '/';
$mtgraces = '/mtgraces.html';
//Gallops Meetings on Todays racing page
$content = file_get_contents($host . $year . "/". $month . "/" . $day . $mtgraces);
preg_match_all('#<a[^<>]+href\s*=\s*[\'"](.R[0-9]+.html*)[\'"]#i', $content, $matches);
foreach ($matches[1] as $url) $links[] = "$host$year$slash$month$slash$day$slash$url";
//get the runners from each page
$final_number = array();
$final_rating = array();
$final_location = array();
$final_locationcode = array();
for($c=0; $c<count($links); $c++)
{
$racepage = file_get_contents($links[$c]);
preg_match_all('#<td align="right" height="18"><font color="\#ffffff">[0-9]{1,2}</font></td>#', $racepage, $number);
preg_match_all('#<font color="\#00ffff">[0-9]{1,3}</font>#', $racepage, $rating);
preg_match_all('#<B>[\w]+([\s][A-Z]+)?</B>#', $racepage, $location);
preg_match_all('#<B>[\w]+\s[0-9]+</B>#', $racepage, $locationcode);
//strip tags for storage in DB
$number_data = implode(",", $number[0]);
$dbnumber = strip_tags($number_data);
$final_number[] = explode(",", $dbnumber);
$rating_data = implode(",", $rating[0]);
$dbrating = strip_tags($rating_data);
$final_rating[] = explode(",", $dbrating);
$location_data = implode(",", $location[0]);
$dblocation = strip_tags($location_data);
$final_location[] = explode(",", $dblocation);
$locationcode_data = implode(",", $locationcode[0]);
$dblocationcode = strip_tags($locationcode_data);
$final_locationcode[] = explode(",", $dblocationcode);
}
//Insert into database
$data = array();
for($i=0; $i<count($final_number); $i++)
$data[] = "('" . $final_location[0] . "', '" . $final_locationcode[0] . "', '" . $final_number[$i] . "', '" . $final_rating[$i] . "')";
if(count($queries) != 0)
{
$query = "insert into ratings(location, location_code, tab_no, rating) values " . implode(", ", $data);
$hostname = "%hostname%"; // eg. mysql.yourdomain.com (unique)
$username = "%username%"; // the username specified when setting-up the database
$password = "%password"; // the password specified when setting-up the database
$database = "%database"; // the database name chosen when setting-up the database (unique)
mysql_connect($hostname,$username,$password);
mysql_select_db($database) or die("Unable to select database");
mysql_query($query) OR die(mysql_error())
}
$final_number is something you get from a racepage link right? You are using it to as $i<count($final_number). Instead i think you should use $i<count($links) there as what you want to insert is a row for each link. What you can do is move the:
$data[] = "('" . $final_location[0] . "', '" . $final_locationcode[0] . "', '" . $final_number[$i] . "', '" . $final_rating[$i] . "')";
...line to the bottom of for($c=0; $c<count($links); $c++) line which would make you code look like this starting from that point, (notice $data=array() is defined before the loop):
$data = array();
for($c=0; $c<count($links); $c++)
{
$racepage = file_get_contents($links[$c]);
preg_match_all('#<td align="right" height="18"><font color="\#ffffff">[0-9]{1,2}</font></td>#', $racepage, $number);
preg_match_all('#<font color="\#00ffff">[0-9]{1,3}</font>#', $racepage, $rating);
preg_match_all('#<B>[\w]+([\s][A-Z]+)?</B>#', $racepage, $location);
preg_match_all('#<B>[\w]+\s[0-9]+</B>#', $racepage, $locationcode);
//strip tags for storage in DB
$number_data = implode(",", $number[0]);
$dbnumber = strip_tags($number_data);
$final_number[] = explode(",", $dbnumber);
$rating_data = implode(",", $rating[0]);
$dbrating = strip_tags($rating_data);
$final_rating[] = explode(",", $dbrating);
$location_data = implode(",", $location[0]);
$dblocation = strip_tags($location_data);
$final_location[] = explode(",", $dblocation);
$locationcode_data = implode(",", $locationcode[0]);
$dblocationcode = strip_tags($locationcode_data);
$final_locationcode[] = explode(",", $dblocationcode);
$data[] = "('" . $final_location[0] . "', '" . $final_locationcode[0] . "', '" . $final_number[0] . "', '" . $final_rating[0] . "')";
}
if(count($queries) != 0)
{
$query = "insert into ratings(location, location_code, tab_no, rating) values " . implode(", ", $data);
$hostname = "%hostname%"; // eg. mysql.yourdomain.com (unique)
$username = "%username%"; // the username specified when setting-up the database
$password = "%password"; // the password specified when setting-up the database
$database = "%database"; // the database name chosen when setting-up the database (unique)
mysql_connect($hostname,$username,$password);
mysql_select_db($database) or die("Unable to select database");
mysql_query($query) OR die(mysql_error())
}
I think there are some problems with this code still.
Edit:I also noticed that on this line
$number_data = implode(",", $number[0]);
Wouldn't $number[0] be a string, it couldn't be an array because $number is an array of matched strings so $number[0] would be the whole matched string. This would apply to 'number_data', 'rating_data', 'location_data' and 'locationcode_data' so you can
$number_data = strip_tags($number[0]);
and then when creating the insert data:
$data[] = "('" . $final_location . "', '" . $final_locationcode . "', '" . $final_number . "', '" . $final_rating . "')";
I have managed to figure it out!
I needed to put the whole lot in the for loop, so it looks like this:
for($c=0; $c<count($links); $c++)
{
$racepage = file_get_contents($links[$c]);
preg_match_all('#<td align="right" height="18"><font color="\#ffffff">[0-9]{1,2}</font></td>#', $racepage, $number);
preg_match_all('#<font color="\#00ffff">[0-9]{1,3}</font>#', $racepage, $rating);
preg_match_all('#<B>[\w]+([\s][A-Z]+)?</B>#', $racepage, $location);
preg_match_all('#<B>[\w]+\s[0-9]+</B>#', $racepage, $locationcode);
//strip tags for storage in DB
$number_data = implode(",", $number[0]);
$dbnumber = strip_tags($number_data);
$final_number = explode(",", $dbnumber);
$rating_data = implode(",", $rating[0]);
$dbrating = strip_tags($rating_data);
$final_rating = explode(",", $dbrating);
$location_data = implode(",", $location[0]);
$dblocation = strip_tags($location_data);
$final_location = explode(",", $dblocation);
$locationcode_data = implode(",", $locationcode[0]);
$dblocationcode = strip_tags($locationcode_data);
$final_locationcode = explode(",", $dblocationcode);
//Insert into database
$data = array();
for($i=0; $i<count($final_number); $i++)
{
$data[] = "('" . $final_location[0] . "', '" . $final_locationcode[0] . "', '" . $final_number[$i] . "', '" . $final_rating[$i] . "')";
}
if(count($queries) == 0)
{
# Nothing passed
# exit
}
$query = "insert into ratings(location, location_code, tab_no, rating) values " . implode(", ", $data);
$hostname = "%HOSTNAME"; // eg. mysql.yourdomain.com (unique)
$username = "%username%"; // the username specified when setting-up the database
$password = "%password%"; // the password specified when setting-up the database
$database = "%database%"; // the database name chosen when setting-up the database (unique)
mysql_connect($hostname,$username,$password);
mysql_select_db($database) or die("Unable to select database");
mysql_query($query) OR die(mysql_error());
}
Thank you all for your help, it seems like a great community that is here. I am sure to keep an eye on it for more fixes.
Related
I have a Problem with PHP. I want to make an table update with PHP.
$name = pg_escape_string($_POST['NAME']);
$place = pg_escape_string($_POST['PLACE']);
$zip = pg_escape_string($_POST['ZIP']);
$nation = pg_escape_string($_POST['NATION']);
$name = "'" . $name . "'";
$place = "'" . $place . "'";
$zip = "'" . $zip . "'";
$nation = "'" . $nation . "'";
$club_id = "'" . $club_id . "'";
$result = pg_query($db_connect, "UPDATE club SET name_c = $name, place_c = $place, zip_c = $zip, nation_c = $nation WHERE id_c = $club_id;");
Why does it not work?
Thanks!
You do not have club_id defined in your code. And to avoid any problems and cleanup code I would do:
$club_id = 1;
$dbconn = pg_connect("connectionstring");
$sql = 'UPDATE club SET name_c = $1, place_c = $2, zip_c = $3, nation_c = $4 WHERE id_c = $5;';
$result = pg_query_params($dbconn, $sql, array(
$_POST['NAME'],
$_POST['PLACE'],
$_POST['ZIP'],
$_POST['NATION'],
$club_id
));
// Do what you need
It'll escape values for you so no need to handle strange cases.
http://php.net/manual/en/function.pg-query-params.php
$objetos = json_decode($_POST['objetos']);
$query1 = "DELETE FROM `usuarioObjeto` WHERE idusuario=" . $id . "";
$result1 = mysqli_query($conn, $query1) or die('Consulta fallida: ' . mysqli_error());
$size = count($objetos); //this works
//this do not insert into the BD
for ($k = 0; $k < $size; $k++) {
$ido = intval($objetos[$k]['id']);
$cantidad = intval($objetos[$k]['cantidad']);
$query2 = "INSERT INTO `usuarioObjeto`( `idUsuario`, `idObjeto`, `cantidad`) VALUES (" . $id . "," . $ido . "," . $cantidad . ")";
$result2 = mysqli_query($conn, $query2) or die('Consulta fallida: ' . mysqli_error());
}
thanks
and i have tried to access to one property like this but nothing
$ido = intval($objetos[0]['id']);
json_decode($_POST['objetos']); replece to json_decode($_POST['objetos'],true);
By adding true as a second parameter, it will convert your json to array
More information: json_decode
Use this code :
$objetos = json_decode($_POST['objetos'],true);
I have a csv upload plugin for wordpress. I can upload the files on a mac but on a windows pc it fails to upload. The csv files are created on the pc with utf-8 encoding.
if (isset($_POST) && !empty($_POST)) {
if (isset($_FILES) && $_FILES['csv_file']['size'] > 0 && $_FILES['csv_file']['type'] === 'text/csv') {
global $wpdb;
ini_set("auto_detect_line_endings", true);
$start_row = (int) $_POST['start_row'];
/*
* Get CSV data and put it into an array
*/
$fileData = file_get_contents($_FILES['csv_file']['tmp_name']);
$lines = explode(PHP_EOL, $fileData);
$csv = array();
foreach ($lines as $line) {
$csv[] = str_getcsv($line);
}
/*
* Put each row into the database
*/
$x = 1;
$insert_count = 0;
$insert_output = array();
$wpdb->query('TRUNCATE TABLE table');
foreach ($csv as $data) {
if ($x >= $start_row) {
$date = fix_date($data[0]);
$sql = "
INSERT INTO table ( date, column_1, column_2, column_3, column_4, column_5, column_6, column_7 )
VALUES ( '" . $date . "', '" . addslashes( $data[1] ) . "', '" . utf8_encode( $data[2] ) . "', '" . addslashes( $data[3]) . "', '" . $data[4] . "', '" . addslashes( $data[5] ) . "', '" . $data[6] . "', '" . $data[7] . "' )
";
$wpdb->query($sql)/* or die($sql)*/;
$insert_output[] = $insert_count . '. Added: ' . $data[1] . ' - ' . $data[3] . '<br />';
$insert_count++;
}
$x++;
}
echo '<div class="csv_success">Success. ' . number_format($insert_count) . ' rows uploaded.</div>';
} else {
echo '<div class="csv_failure">Please make sure the file you uploaded is a CSV.</div>';
}
}
Any ideas how I can get this to work on windows and mac?
Cheers
<?php
ini_set('max_execution_time', 0);
$con = mysql_connect("localhost", "", "") or die("not connect");
mysql_select_db("demo") or die("select db");
function readCSV($csvFile){
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) ) {
$line_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
return $line_of_text;
}
//Set path to CSV file
$csvFile = 'page.csv';
$csv = readCSV($csvFile);
//echo count($csv);
for ($i=1; $i <count($csv) ; $i++) {
$sql="insert into demo1 (name,bdate,phonenumber ) values('".$csv[$i][0]."','".$csv[$i][1]."' ,'".$csv[$i][2]."')";
mysql_query($sql);
}
echo 'done';
?>
I am inserting record from CSV file to MySQL table if any record already exists update that record and insert other records and if there is no match of the record insert all records.
Here is my code
<?php
$connect = mysql_connect('localhost', '', '');
if (!$connect) {
die('Could not connect to MySQL: ' . mysql_error());
}
$cid = mysql_select_db('test', $connect);
define('CSV_PATH', '/home/ubc/Documents/');
$csv_file = CSV_PATH . "test.csv";
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
$i = 0;
while (!feof($csvfile)) {
$csv_data[] = fgets($csvfile, 1024);
$csv_array = explode(",", $csv_data[$i]);
$insert_csv = array();
$insert_csv['name'] = $csv_array[0];
$insert_csv['email'] = $csv_array[1];
$query = mysql_query("select * from test");
$count = mysql_num_rows($query);
if ($count == 0) {
$query = "INSERT INTO test(name,email)VALUES('" . $insert_csv['name'] . "','" . $insert_csv['email'] . "')";
$n = mysql_query($query, $connect);
$i++;
} else {
$query = mysql_query("select name from test where name='" . $insert_csv['name'] . "'");
while ($row = mysql_fetch_array($query)) {
if ($count) {
$sql = "update test set email='" . $insert_csv['email'] . "'";
$qu = mysql_query($sql);
} else {
$query = "INSERT INTO test(name,email)VALUES('" . $insert_csv['name'] . "','" . $insert_csv['email'] . "')";
$n = mysql_query($query, $connect);
$i++;
}
}
}
}
fclose($csvfile);
echo "File data successfully imported to database!!";
mysql_close($connect);
?>
<?php
$connect = mysql_connect('localhost', '', '');
if (!$connect) {
die('Could not connect to MySQL: ' . mysql_error());
}
$cid = mysql_select_db('test', $connect);
define('CSV_PATH', '/home/ubc/Documents/');
$csv_file = CSV_PATH . "test.csv";
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
$i = 0;
while (!feof($csvfile)) {
$csv_data[] = fgets($csvfile, 1024);
$csv_array = explode(",", $csv_data[$i]);
$insert_csv = array();
$insert_csv['name'] = $csv_array[0];
$insert_csv['email'] = $csv_array[1];
$query = mysql_query("select name from test where name='" . $insert_csv['name'] . "'");
$count = mysql_num_rows($query);
if ($count == 0) {
$query = "INSERT INTO test(name,email)VALUES('" . $insert_csv['name'] . "','" . $insert_csv['email'] . "')";
$n = mysql_query($query, $connect);
} else {
$sql = "update test set email='" . $insert_csv['email'] . "'";
$qu = mysql_query($sql);
}
$i++;
}
}
fclose($csvfile);
echo "File data successfully imported to database!!";
mysql_close($connect);
?>
Use bellow query..
INSERT INTO table (primkey, col2, col3) VALUES(1, 2, 3) ON DUPLICATE KEY UPDATE
col1=VALUES(1), col2=VALUES(2)
Its example.
This may help you
http://dev.mysql.com/doc/refman/5.0/en/replace.html
I currently have this query that insert data into SQL server. But as the question can contain special characters that include ' which is single quote, it skips my query and did not insert into database.
Any idea what would work for me to be able to insert single quote data into SQL server database?
Example: Trainer's Performance.
Here's my code for inserting data into database:
$sql_array = array();
foreach ($_POST['question'] as $row => $name) {
$question = $name;
$qnsNo = $_POST['qnsNo'][$row];
$input = $_POST['input'][$row];
$options = $_POST['options'][$row];
$others = $_POST['others'][$row];
$compulsory = isset($_POST['compulsory'][$row]) ? $_POST['compulsory'][$row] : "";
$idQuery = "SELECT max(surveyID) FROM scSurveyForm WHERE createBy = '$createBy' AND writeUp = '$writeUp'";
$idResult = sqlsrv_query($conn, $idQuery);
$rows = sqlsrv_fetch_array($idResult);
$lastID = $rows[0];
$sql_array[] = "('" . $question . "'," . $lastID . ",'" . $qnsNo . "','" . $input . "','" . $options . "','" . $others . "','" . $compulsory . "')";
if (!empty($question)) {
$query_single = "INSERT INTO scFormLayout(question, surveyID, qnsNo, input, options, others, compulsory)
VALUES" . implode(', ', $sql_array);
//echo $query_single.'<br/>';
$status = sqlsrv_query($conn, $query_single);
$sql_array = array();