mysqli to postgres database - php

I create a script to insert data from a mysqli database to a postgres database
<?php
$conn = new mysqli(...........);
if ($conn->connect_error) {
die("Connection fialed: " . $conn->connect_error);
}
else
{
echo "MySQL connection successfull\n";
}
$db = pg_connect(.................);
if(!$db){
echo "Error : Unable to open database\n";
} else {
echo "PostgreSQL connection successfull\n";
}
$sql = "SELECT * FROM crm_subscriptions";
echo $sql . "\n";
$result = $conn->query($sql);
echo $conn->error . "\n";
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$psql = "
INSERT INTO subscriptions_sub (id,cust_id,tarrif_id,des,datetime_created,datetime_modified,credit,credit_limit,status,date_start,date_end,backoffice_userref,backoffice_deleted,backoffice_createdon,backoffice_createdby, backoffice_updatedon,backoffice_updatedby,backoffice_administration,backoffice_readonly,backoffice_order,backoffice_dummy)
VALUES('" .(int) $row["subscription_id"] . "','" . (int) $row["customer_id"] . "','" . (int) $row["tariffplan_id"] . "','" . $row["description"] . "',NULLIF('" . $row["datetime_created"] . "','0000-00-00 00:00:00')::timestamp,NULLIF('" . $row["datetime_modified"] . "','0000-00-00 00:00:00')::timestamp,'" . (int) $row["credit"] . "','" . (int) $row["credit_limit"] . "','" . $row["status"] . "',NULLIF('" . $row["date_start"] . "','')::timestamp,NULLIF('" . $row["date_end"] . "','')::timestamp,'" . (int) $row["backoffice_userref"] . "','" . (int) $row["backoffice_deleted"] . "',NULLIF('" . $row["backoffice_createdon"] . "','0000-00-00 00:00:00')::timestamp,'" . (int) $row["backoffice_createdby"] . "',NULLIF('" . $row["backoffice_updatedon"] . "','0000-00-00 00:00:00')::timestamp,'" . (int) $row["backoffice_updatedby"] . "','" . (int) $row["backoffice_administration"] . "','" . (int) $row["backoffice_readonly"] . "','" . (int) $row["backoffice_order"] . "','" . (int) $row["backoffice_dummy"] . "');
";
print_r($row);
$ret = pg_query($db, $psql);
if(!$ret){
echo pg_last_error($db);
} else {
echo "Records created succesfully\n";
}
}
} else {
echo "0 results \n";
}
?>
When I run it I get this error:
invalid input syntax for type timestamp: "" in
/home/ruud/Database2.php on line 38 ERROR: invalid input syntax
for type timestamp: ""root#149-210-204-94:/home/ruud# ERROR:
invalid input syntax for type timestamp: ""Array
datetime_created and datetime_modified are from type TIMESTAMP date_start and date_end are from type DATE backoffice_createon and backoffice_update on are from type DATETIME

You need to install a postgres driver/module, as mysqli is the driver for mysql.
sudo apt-get install php5-pgsql
Or if the package is installed, you need to enable de module in php.ini
extension=php_pgsql.dll (windows)
extension=php_pgsql.so (linux)
you may already have it installed. check your phpinfo();

Related

I am unable to increament id

I searched many stackoverflow questions it didn't help
I want to increment id by fetching last id from MySQL table.
I don't want to do auto increment in MySQL table because already one column is auto incremented.
<?php
include 'db.php';
$created = date('Y-m-d H:i:s');
//$json_data = array();
$message = array();
$error = array();
if ($_GET['vendor_id'] == "") {
$message[] = array("message" => "Values Empty");
} else {
$result = mysqli_query("SELECT loo_id FROM loo_list ORDER BY loo_id DESC LIMIT 1");
if ($result) {
$order_array = mysqli_fetch_assoc($result) or die(mysqli_error());
//echo $order_array['loo_id'];
}
$loo_id = $order_array['loo_id'] + 1;
$sql = "insert into loo_list(loo_id,name,address,geolocation,price,facility_category,facilities,count,accessbility,image,type,category,created_vendor,days,timings,terms_conditions,vendor_approval,created,warning,url,user_ids,overall,admin_approval,updated)values('" . $loo_id . "','" . $_GET['loo_name'] . "','" . $_GET['address'] . "','" . $_GET['loo_location'] . "','" . $_GET['price'] . "','" . $_GET['facility_category'] . "','" . $_GET['facilities'] . "','" . $_GET['count'] . "','" . $_GET['accessbility'] . "','" . $_GET['image'] . "','Offerers','" . $_GET['category'] . "','" . $_GET['vendor_id'] . "','" . $_GET['days'] . "','" . $_GET['timings'] . "','" . $_GET['terms_conditions'] . "','1','" . $created . "','0','','" . $_GET['user_ids'] . "','" . $_GET['overall'] . "','1','" . $created . "')";
$res1 = mysqli_query($db, $sql) or die(mysqli_error());
$message[] = array("message" => "success");
}
$json_data = array("result" => $message);
echo json_encode($json_data);
?>
Try this code.
if(trim($order_array['loo_id']) === ''){
$loo_id = 1;
}else{
$loo_id = intval($order_array['loo_id']) + 1;
}

mysql to postgresql database error

I create a script to convert my mysql database to a postgres database
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$psql = "
INSERT INTO subscriptions_sub (id,cust_id,tarrif_id,des,datetime_created,datetime_modified,credit,credit_limit,status,date_start,date_end,backoffice_userref,backoffice_deleted,backoffice_createdon,backoffice_createdby, backoffice_updatedon,backoffice_updatedby,backoffice_administration,backoffice_readonly,backoffice_order,backoffice_dummy)
VALUES('" .(int) $row["subscription_id"] . "','" . (int) $row["customer_id"] . "','" . (int) $row["tariffplan_id"] . "','" . $row["description"] . "',NULLIF('" . $row["datetime_created"] . "','0000-00-00 00:00:00')::timestamp,NULLIF('" . $row["datetime_modified"] . "','0000-00-00 00:00:00')::timestamp,'" . (int) $row["credit"] . "','" . (int) $row["credit_limit"] . "','" . $row["status"] . "',NULLIF('" . $row["date_start"] . "','')::timestamp,NULLIF('" . $row["date_end"] . "','')::timestamp,'" . (int) $row["backoffice_userref"] . "','" . (int) $row["backoffice_deleted"] . "',NULLIF('" . $row["backoffice_createdon"] . "','0000-00-00 00:00:00')::timestamp,'" . (int) $row["backoffice_createdby"] . "',NULLIF('" . $row["backoffice_updatedon"] . "','0000-00-00 00:00:00')::timestamp,'" . (int) $row["backoffice_updatedby"] . "','" . (int) $row["backoffice_administration"] . "','" . (int) $row["backoffice_readonly"] . "','" . (int) $row["backoffice_order"] . "','" . (int) $row["backoffice_dummy"] . "');
";
print_r($row);
$ret = pg_query($db, $psql);
if(!$ret){
echo pg_last_error($db);
} else {
echo "Records created succesfully\n";
}
When I run it I get this error:
invalid input syntax for type timestamp: "" in /home/ruud/Database2.php on line 38
ERROR: invalid input syntax for type timestamp: ""root#149-210-204-94:/home/ruud#
datetime_created and datetime_modified are from type TIMESTAMP
date_start and date_end are from type DATE
backoffice_createon and backoffice_update on are from type DATETIME
I cant seem to find out where I'm making a error.

mysqli::query(): Couldn't fetch mysqli after first line of foreach loop

I have created a foreach loop to add data to a MySQL database and I am receiving the error "mysqli::query(): Couldn't fetch mysqli" after the first line has been added to the database.
PHP DB CONNECTION
$db = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
I then have another chunk of script which collects the data I require. The data is then added to the foreach insert loop
PHP FOREACH
foreach($RSS_DOC->channel->item as $RSSitem)
{
$item_id = md5($RSSitem->title);
$fetch_date = date("Y-m-j G:i:s");
$item_title = $RSSitem->title;
$item_date = date("Y-m-j G:i:s", strtotime($RSSitem->pubDate));
$item_url = $RSSitem->link;
echo "Processing item '" , $item_id , "' on " , $fetch_date , "<br/>";
echo $item_title, " - ";
echo $item_date, "<br/>";
echo $item_url, "<br/>";
$sql = "INSERT INTO rssingest (item_id, feed_url, item_title, item_date, item_url, fetch_date)
VALUES ('" . $item_id . "', '" . $feed_url . "', '" . $item_title . "', '" . $item_date . "', '" . $item_url . "', '" . $fetch_date . "')";
if ($db->query($sql) === TRUE) { // <- THIS IS LINE 170
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
}
The first line is added to the database without a problem. The second line and every line after that one returns "mysqli::query(): Couldn't fetch mysqli on line 170".
Any ideas where I may be going wrong?
The problem may be the $db->close() inside the loop. Try closing the database after the loop.
foreach($RSS_DOC->channel->item as $RSSitem)
{
$item_id = md5($RSSitem->title);
$fetch_date = date("Y-m-j G:i:s");
$item_title = $RSSitem->title;
$item_date = date("Y-m-j G:i:s", strtotime($RSSitem->pubDate));
$item_url = $RSSitem->link;
echo "Processing item '" , $item_id , "' on " , $fetch_date , "<br/>";
echo $item_title, " - ";
echo $item_date, "<br/>";
echo $item_url, "<br/>";
$sql = "INSERT INTO rssingest (item_id, feed_url, item_title, item_date, item_url, fetch_date)
VALUES ('" . $item_id . "', '" . $feed_url . "', '" . $item_title . "', '" . $item_date . "', '" . $item_url . "', '" . $fetch_date . "')";
if ($db->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
}
$db->close();

MySQLi / PHP - Pulling data from one database. Inserting into another database

Trying to pull data out of a basic phpmyadmin database.
The code below pulls the data correctly (Commented out section verify).
I can write it to the screen and display it. (Not needed just testing)
Trying to insert it into another database however and it fails.
I've discovered that the while loops for inserting do not run. Although I can not find out why.
It's a basic localhost database (Testing right now) So the connect data is just temporary.
Any assistance is greatly appreciated
Thanks.
<?php
/*
Connect to database
*/
$webhost = 'localhost';
$webusername = 'root';
$webpassword = '';
$webdbname = 'transfertest';
$webcon = mysqli_connect($webhost, $webusername, $webpassword, $webdbname);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
/*
*
*/
$questions = mysqli_query($webcon, "SELECT * FROM questions");
$scenarios = mysqli_query($webcon, "SELECT * FROM scenarios");
$results = mysqli_query($webcon, "SELECT * FROM results");
$employees = mysqli_query($webcon, "SELECT * FROM employees");
/*
* These while loops display the content being pulled from the database correctly.
while ($row = mysqli_fetch_array($questions)) {
echo $row['questionID'] . " : " . $row['question'] . " : " . $row['answers'];
echo "</br>";
}
while ($row = mysqli_fetch_array($scenarios)) {
echo $row['scenarioID'] . " : " . $row['scenarioTitle'] . " : " . $row['scenarioInformation'];
echo "</br>";
}
while ($row = mysqli_fetch_array($results)) {
echo $row['employeeID'] . " : " . $row['scenarioID'] . " : " . $row['questionID'] . " : " . $row['answers'] . " : " . $row['correct'];
echo "</br>";
}
while ($row = mysqli_fetch_array($employees)) {
echo $row['employeeID'] . " : " . $row['firstName'] . " : " . $row['lastName'] . " : " . $row['email'] . " : " . $row['password'];
echo "</br>";
}
*/
/* //////////////////////////////////////////////////////////////////////////
Connect to database
*/
$mobhost = 'localhost';
$mobusername = 'root';
$mobpassword = '';
$mobdbname = 'exampletransfer';
$mobcon = mysqli_connect($mobhost, $mobusername, $mobpassword, $mobdbname);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
/*
*
*/
while ($row = mysqli_fetch_array($questions)) {
mysqli_query($mobcon, "INSERT INTO questions (questionID, question, answers) VALUES (" . $row['questionID'] . ", " . $row['question'] . ", " . $row['answers'] . ")");
}
while ($row = mysqli_fetch_array($scenarios)) {
mysqli_query($mobcon, "INSERT INTO scenarios (scenarioID, scenarioTitle, scenarioInformation) VALUES (" . $row['scenariosID'] . ", " . $row['scenarioTitle'] . ", " . $row['scenarioInformation'] . ")");
}
while ($row = mysqli_fetch_array($results)) {
mysqli_query($mobcon, "INSERT INTO results (employeeID, scenarioID, questionID, answers, correct) VALUES (" . $row['employeesID'] . ", " . $row['scenariosID'] . ", " . $row['questionID'] . ", " . $row['answers'] . ", " . $row['correct'] . ")");
}
while ($row = mysqli_fetch_array($employees)) {
mysqli_query($mobcon, "INSERT INTO employees (employeeID, firstName, lastName, email, password) VALUES (" . $row['employeesID'] . ", " . $row['firstName'] . ", " . $row['lastName'] . ", " . $row['email'] . ", " . $row['password'] . ")");
}
/*
Close Connections
*/
mysqli_close($webcon);
mysqli_close($mobcon);
/*
* Error code:
Notice: Undefined index: scenariosID on line 75
Notice: Undefined index: employeesID on line 78
Notice: Undefined index: scenariosID on line 78
Notice: Undefined index: employeesID on line 81
*/
?>
The problem is that you close your $webcon connection and then you try to read from it ^^
You try to do this... Thats not possible ;)
Prepare query mysqli_query($webcon, "SELECT * FROM questions");
Close connection <<< after that i cant read data
Read data
Try this please.
<?php
/**
* Connect to database
*/
$webhost = 'localhost';
$webusername = 'root';
$webpassword = '';
$webdbname = 'transfertest';
$webcon = mysqli_connect($webhost, $webusername, $webpassword, $webdbname);
if (mysqli_connect_errno())
{
echo 'Failed to connect to MySQL: ' . mysqli_connect_error();
}
/**
* Queries for reading
*/
$questions = mysqli_query($webcon, 'SELECT * FROM `questions`');
$scenarios = mysqli_query($webcon, 'SELECT * FROM `scenarios`');
$results = mysqli_query($webcon, 'SELECT * FROM `results`');
$employees = mysqli_query($webcon, 'SELECT * FROM `employees`');
/**
* Connect to database
*/
$mobhost = 'localhost';
$mobusername = 'root';
$mobpassword = '';
$mobdbname = 'exampletransfer';
$mobcon = mysqli_connect($mobhost, $mobusername, $mobpassword, $mobdbname);
if (mysqli_connect_errno())
{
echo 'Failed to connect to MySQL: ' . mysqli_connect_error();
}
/**
* Insert data from old database
*/
// questions
while ($row = mysqli_fetch_array($questions))
{
// escape your strings
foreach($row as $key => $val)
{
$row[$key] = mysqli_real_escape_string($mobcon, $row[$key]);
}
mysqli_query($mobcon, "INSERT INTO `questions` (`questionID`, `question`, `answers`) VALUES ('" . $row['questionID'] . "', '" . $row['question'] . "', '" . $row['answers'] . "');");
}
// scenarios
while ($row = mysqli_fetch_array($scenarios))
{
// escape your strings
foreach($row as $key => $val)
{
$row[$key] = mysqli_real_escape_string($mobcon, $row[$key]);
}
mysqli_query($mobcon, "INSERT INTO `scenarios` (`scenarioID`, `scenarioTitle`, `scenarioInformation`) VALUES ('" . $row['scenariosID'] . "', '" . $row['scenarioTitle'] . "', '" . $row['scenarioInformation'] . "');");
}
// results
while ($row = mysqli_fetch_array($results))
{
// escape your strings
foreach($row as $key => $val)
{
$row[$key] = mysqli_real_escape_string($mobcon, $row[$key]);
}
mysqli_query($mobcon, "INSERT INTO `results` (`employeeID`, `scenarioID`, `questionID`, `answers`, `correct`) VALUES ('" . $row['employeesID'] . "', '" . $row['scenariosID'] . "', '" . $row['questionID'] . "', '" . $row['answers'] . "', '" . $row['correct'] . "');");
}
// employees
while ($row = mysqli_fetch_array($employees))
{
// escape your strings
foreach($row as $key => $val)
{
$row[$key] = mysqli_real_escape_string($mobcon, $row[$key]);
}
mysqli_query($mobcon, "INSERT INTO `employees` (`employeeID`, `firstName`, `lastName`, `email`, `password`) VALUES ('" . $row['employeesID'] . "', '" . $row['firstName'] . "', '" . $row['lastName'] . "', '" . $row['email'] . "', '" . $row['password'] . "');");
}
/*
Close Connections
*/
mysqli_close($mobcon);
mysqli_close($webcon);
Pending it's on the same server and using the same username and password:
// Create a new MySQL database connection
if (!$con = mysql_connect('localhost', $username, $password)) {
die('An error occurred while connecting to the MySQL server!<br/>' . mysql_error());
}
if (!mysql_select_db($database)) {
die('An error occurred while connecting to the database!<br/>' . mysql_error());
}
// Create an array of MySQL queries to run
$sql = array(
'DROP TABLE IF EXISTS `exampletransfer.questions`;',
'CREATE TABLE `exampletransfer.questions` SELECT * FROM `transfertest.questions`'
);
// Run the MySQL queries
if (sizeof($sql) > 0) {
foreach ($sql as $query) {
if (!mysql_query($query)) {
die('A MySQL error has occurred!<br/>' . mysql_error());
}
}
}
If using MySQLi instead of MySQL:
// Create a new MySQL database connection
if (!$con = new mysqli('localhost', $username, $password, $database)) {
die('An error occurred while connecting to the MySQL server!<br/>' . $con->connect_error);
}
// Create an array of MySQL queries to run
$sql = array(
'DROP TABLE IF EXISTS `exampletransfer.questions`;',
'CREATE TABLE `exampletransfer.questions` SELECT * FROM `transfertest.questions`'
);
// Run the MySQL queries
if (sizeof($sql) > 0) {
foreach ($sql as $query) {
if (!$con->query($query)) {
die('A MySQL error has occurred!<br/>' . $con->error);
}
}
}
$con->close();

Preventing SQL Injections [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Best way to stop SQL Injection in PHP
In PHP when submitting strings to the database should I take care of illegal characters using htmlspecialchars() or use a regular expression?
Yesterday I asked a question with regards to a script not working, whilst I in the end solved the issue myself. There was talk of SQL Injections risks.
So what I'm asking today is, with the code I have inserted below, how would one prevent SQL Injections?
So any advice of guidence. I know I can read the internet about SQL injections but there is so many conflicting articles on it, I don't know which is correct or not.
Here is the code, this is all put in a page of it's own lets say 'form-process.php' which the form then submits the data to e.g
<?
session_start();
$_SESSION['Title'] = stripslashes($_REQUEST['Title']);
$_SESSION['ShortTitle'] = stripslashes($_REQUEST['Title']);
$_SESSION['Category'] = stripslashes($_REQUEST['Category']);
$_SESSION['Story'] = stripslashes($_REQUEST['Story']);
$_SESSION['FrontPage'] = stripslashes($_REQUEST['FrontPage']);
$_SESSION['imagefilename'] = ($_FILES['image']['name']);
if (empty($_REQUEST['Title'])) {
header("Location: ". $_SERVER['HTTP_REFERER'] ."?message=0");
exit;
} elseif (empty($_REQUEST['ShortTitle'])) {
header("Location: ". $_SERVER['HTTP_REFERER'] ."?message=1");
exit;
} elseif (strlen($_REQUEST['Category']) < 1) {
header("Location: ". $_SERVER['HTTP_REFERER'] ."?message=2");
exit;
} elseif (empty($_REQUEST['Story'])) {
header("Location: ". $_SERVER['HTTP_REFERER'] ."?message=3");
exit;
} else {
include("settings.php");
include("dbconnect.php");
if($_POST['btnSubmit'] == 'Publish'){
$target = "../../../images/matchreports/uploaded/";
$target = $target . time() . '-' . basename( $_FILES['image']['name']);
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)){
$image=time() . '-' . basename( $_FILES['image']['name']);
$newdate = $_POST['date_y'].''.$_POST['date_m'].''.$_POST['date_d'];
$SQL = "INSERT INTO " . $match_reports_table . " (Title,ShortTitle,Story,FrontPage,active,image,date,user_ip) VALUES('" . addslashes($_REQUEST['Title']) . "','" . addslashes($_REQUEST['ShortTitle']) . "','" . addslashes($_REQUEST['Story']) . "','" . addslashes($_REQUEST['FrontPage']) . "','" . addslashes(y) . "','$image','$newdate','" . addslashes($_SERVER['REMOTE_ADDR']) . "')";
$result = #mysql_query($SQL) or die("Error Publishing 1");
header("Location: /cms/matchreports/index.php?message=4");
exit;
} else {
$newdate = $_POST['date_y'].''.$_POST['date_m'].''.$_POST['date_d'];
$SQL = "INSERT INTO " . $match_reports_table . " (Title,ShortTitle,Story,FrontPage,active,date,user_ip) VALUES('" . addslashes($_REQUEST['Title']) . "','" . addslashes($_REQUEST['ShortTitle']) . "','" . addslashes($_REQUEST['Story']) . "','" . addslashes($_REQUEST['FrontPage']) . "','" . addslashes(n) . "','$newdate','" . addslashes($_SERVER['REMOTE_ADDR']) . "')";
$result = #mysql_query($SQL) or die("Error Publishing 2");
header("Location: /cms/matchreports/index.php?message=5");
exit;}}
if($_POST['btnSubmit'] == 'Save draft'){
$target = "../../../images/matchreports/uploaded/";
$target = $target . time() . '-' . basename( $_FILES['image']['name']);
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)){
$image=time() . '-' . basename( $_FILES['image']['name']);
$newdate = $_POST['date_y'].''.$_POST['date_m'].''.$_POST['date_d'];
$SQL = "INSERT INTO " . $match_reports_table . " (Title,ShortTitle,Story,FrontPage,active,image,date,user_ip) VALUES('" . addslashes($_REQUEST['Title']) . "','" . addslashes($_REQUEST['ShortTitle']) . "','" . addslashes($_REQUEST['Story']) . "','" . addslashes($_REQUEST['FrontPage']) . "','" . addslashes(n) . "','$image','$newdate','" . addslashes($_SERVER['REMOTE_ADDR']) . "')";
$result = #mysql_query($SQL) or die("Error Saving Draft 1");
header("Location: /cms/matchreports/index.php?message=6");
exit;
} else {
$newdate = $_POST['date_y'].''.$_POST['date_m'].''.$_POST['date_d'];
$SQL = "INSERT INTO " . $match_reports_table . " (Title,ShortTitle,Story,FrontPage,active,date,user_ip) VALUES('" . addslashes($_REQUEST['Title']) . "','" . addslashes($_REQUEST['ShortTitle']) . "','" . addslashes($_REQUEST['Story']) . "','" . addslashes($_REQUEST['FrontPage']) . "','" . addslashes(n) . "','$newdate','" . addslashes($_SERVER['REMOTE_ADDR']) . "')";
$result = #mysql_query($SQL) or die("Error Saving Draft 2");
header("Location: /cms/matchreports/index.php?message=7");
exit;}}
if($_POST['btnSubmit'] == 'Publish changes'){
//This gets all the other information from the form
$newdate = $_POST['date_y'].''.$_POST['date_m'].''.$_POST['date_d'];
$SQL = "UPDATE " . $match_reports_table . " SET Title='" . addslashes($_REQUEST['Title']) . "',ShortTitle='" . addslashes($_REQUEST['ShortTitle']) . "',Story='" . addslashes($_REQUEST['Story']) . "',Category='" . addslashes($_REQUEST['Category']) . "',FrontPage='" . addslashes($_REQUEST['FrontPage']) . "',active = '" . y . "',date='$newdate' WHERE ID=" . $_REQUEST['ID'] . "";
$result = #mysql_query($SQL) or die("Error Updating News");
header("Location: /cms/matchreports/index.php?message=8");
exit;}
if($_POST['btnSubmit'] == 'Publish draft to website'){
//This gets all the other information from the form
$newdate = $_POST['date_y'].''.$_POST['date_m'].''.$_POST['date_d'];
$SQL = "UPDATE " . $match_reports_table . " SET Title='" . addslashes($_REQUEST['Title']) . "',ShortTitle='" . addslashes($_REQUEST['ShortTitle']) . "',Story='" . addslashes($_REQUEST['Story']) . "',Category='" . addslashes($_REQUEST['Category']) . "',FrontPage='" . addslashes($_REQUEST['FrontPage']) . "',active = '" . y . "',date='$newdate' WHERE ID=" . $_REQUEST['ID'] . "";
$result = #mysql_query($SQL) or die("Error Updating News");
header("Location: /cms/matchreports/index.php?message=9");
exit;}
if($_POST['btnSubmit'] == 'Save changes to draft'){
//This gets all the other information from the form
$newdate = $_POST['date_y'].''.$_POST['date_m'].''.$_POST['date_d'];
$SQL = "UPDATE " . $match_reports_table . " SET Title='" . addslashes($_REQUEST ['Title']) . "',ShortTitle='" . addslashes($_REQUEST['ShortTitle']) . "',Story='" . addslashes($_REQUEST['Story']) . "',Category='" . addslashes($_REQUEST['Category']) . "',FrontPage='" . addslashes($_REQUEST['FrontPage']) . "',active = '" . n . "',date='$newdate' WHERE ID=" . $_REQUEST['ID'] . "";
$result = #mysql_query($SQL) or die("Error Updating News");
header("Location: /cms/matchreports/index.php?message=10");
exit;}
}?>
Use PDO and prepared statements.
A simple, universal rule I like to apply is this:
Always store data raw, and escape it for the appropriate application when needed.
This means, get rid of nebulous stripslashes(), and:
for string values in SQL statements, use the database's appropriate escape function, e.g. mysqli_real_escape_string(),
for system()-type command names, use escapeshellcmd(), for arguments use escapeshellarg(),
for manually assembling GET request URLs, use urlencode(), and finally
for printing content in an HTML structure, use htmlentities().
There's no point in blindly using some sort of mangling and hoping it'll filter out bad things. Be conscious of what you're doing, and do the appropriate thing at every step.
Example: To print a link with a user-provided GET parameter, you'd do
print("<a href='" . htmlentities($BASEURL . "?data=" . urlencode($untrusted)) . "'>click</a>");
Important note: For SQL queries, it is generally preferable to use prepared statements rather than building queries by hand. This is a different technology from what you're used to, so it's not the straight "how do I fix this" answer, but it is by far the better solution.
I strongly suggest this article generally on escaping (google-translated from czech language)

Categories