При сохранении данных из XML-файла в базу данных MSSQL база данных использует информацию из XML-файла и пытается ее обработать. Это приводит к ошибкам при выполнении запроса. В данных действительно есть некоторые странные токены и последовательности, поэтому я считаю, что проблема.
Есть ли способ поместить данные в базу данных в виде открытого текста?
Ниже вы можете найти файл XML.
<?xml version = "1.0"?><OWASPZAPReport version = "2.7.0" generated = "Then">
<site name = "xnxx" host = "xnxx" port = "80" ssl = "false">
<alerts>
<alertitem>
<pluginid>10020</pluginid>
<alert>X-Frame-Options Header Not Set</alert>
<name>X-Frame-Options Header Not Set</name>
<riskcode>2</riskcode>
<confidence>2</confidence>
<riskdesc>Medium (Medium)</riskdesc>
<desc><p>X-Frame-Options header is not included in the HTTP response to protect against 'ClickJacking' attacks.</p></desc>
<instances>
<instance>
<uri>xnxx/uri>
<method>GET</method>
<param>X-Frame-Options</param>
</instance>
<instance>
<uri>xnxx</uri>
<method>GET</method>
<param>X-Frame-Options</param>
</instance>
</instances>
<count>97</count>
<solution><p>Most modern Web browsers support the X-Frame-Options HTTP header. Ensure it's set on all web pages returned by your site (if you expect the page to be framed only by pages on your server (e.g. it's part of a FRAMESET) then you'll want to use SAMEORIGIN, otherwise if you never expect the page to be framed, you should use DENY. ALLOW-FROM allows specific websites to frame the web page in supported web browsers).</p></solution>
<reference><p>http://blogs.msdn.com/b/ieinternals/archive/2010/03/30/combating-clickjacking-with-x-frame-options.aspx</p></reference>
<cweid>16</cweid>
<wascid>15</wascid>
<sourceid>3</sourceid>
</alertitem>
</alerts>
</site>
А это php-файл. Если вы обнаружите какие-либо другие ошибки или плохие методы, не стесняйтесь указать на них, я новичок в PHP и SQL-сервере.
Первый цикл foreach перебирает теги alertitem (их больше, но я сократил файл). Второй цикл перебирает экземпляры.
<?php
$xml=simplexml_load_file("XML-FILE");
$serverName = "";
$connectionInfo = array( "Database"=>"DB");
$conn = sqlsrv_connect($serverName,$connectionInfo) or die('Error connecting to the SQL Server database.');
if ( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$query = "INSERT INTO Scan(ScanType, start_date, end_date, TargetTargetID) VALUES
('$ScanType', '$start_date', '$end_date', '$TargetTargetID');";
$query_id = "SELECT SCOPE_IDENTITY() as id;";
$result = sqlsrv_query($conn,$query);
$result_id = sqlsrv_query($conn,$query_id);
if ( $result === false ) {
die( print_r( sqlsrv_errors(), true));
}
if ( sqlsrv_fetch( $result_id ) === false) {
die( print_r( sqlsrv_errors(), true));
}
$ScanID = sqlsrv_get_field( $result_id, 0);
//iterating the alertitems
foreach ($xml ->site->alerts->alertitem as $row) {
$issueName = $row->name;
$issueDescription = $row->desc;
$issueSeverity = $row->riskdesc;
$issueConfidence = $row->confidence;
$count = $row->count;
$issueRemedy_guidance = $row->solution;
$cweid = $row->cweid;
$wascid = $row->wascid;
//SQL query
$query = "INSERT INTO issueZAP(issueName, issueDescription, issueSeverity, issueConfidence, count, issueRemedy_guidance, cweid, wascid, ScanID) VALUES
('$issueName', '$issueDescription', '$issueSeverity', '$issueConfidence', '$count', '$issueRemedy_guidance', '$cweid', '$wascid', '$ScanID');";
$query_issue_id = "SELECT SCOPE_IDENTITY() as id;";
$result = sqlsrv_query($conn,$query);
if ( $result === false ) {
die( print_r( sqlsrv_errors(), true));
}
//get ID of newly made issue
$result_issue_id = sqlsrv_query($conn,$query_issue_id);
if ( sqlsrv_fetch( $result_issue_id ) === false) {
die( print_r( sqlsrv_errors(), true));
}
$issueID = sqlsrv_get_field( $result_issue_id, 0);
echo $issueID."\n";
//iterating instances
foreach ($row ->instances->instance as $insta) {
$uri=$insta->uri;
$method=$insta->method;
$evidence=$insta->evidence;
$attack=$insta->attack;
$param=$insta->param;
//SQL query
$query = "INSERT INTO instances(uri, method, evidence, attack, param, issueID) VALUES
('$uri', '$method', '$evidence', '$attack', '$param', '$issueID');";
$result = sqlsrv_query($conn,$query);
if ( $result === false ) {
die( print_r( sqlsrv_errors(), true));
}
}
}
?>
Это ошибки, которые я получаю при запуске PHP-файла. Когда я не помещаю оператор die () -, он помещает некоторые элементы предупреждения в базу данных без каких-либо проблем.
'
Эта последовательность токенов - единственное сходство, которое я могу найти между неудавшимися запросами.
Array
(
[0] => Array
(
[0] => 08004
[SQLSTATE] => 08004
[1] => 911
[code] => 911
[2] => [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Database 'SAMEORIGIN' does not exist. Make sure that the name is entered correctly.
[message] => [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Database 'SAMEORIGIN' does not exist. Make sure that the name is entered correctly.
)
[1] => Array
(
[0] => 42000
[SQLSTATE] => 42000
[1] => 102
[code] => 102
[2] => [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Incorrect syntax near 'ClickJacking'.
[message] => [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Incorrect syntax near 'ClickJacking'.
)
[2] => Array
(
[0] => 42000
[SQLSTATE] => 42000
[1] => 4145
[code] => 4145
[2] => [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]An expression of non-boolean type specified in a context where a condition is expected, near 'expect'.
[message] => [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]An expression of non-boolean type specified in a context where a condition is expected, near 'expect'.
)
)






Когда php читал XML-файл, он уже преобразовал "& apos;" в одинарные кавычки, а MSSQL не принимает одинарные кавычки.
Поэтому я заменил одинарные кавычки двойными одинарными кавычками, и теперь он работает.