unable to insert xml string into mysql table - php

i want to insert below xml string into mysql database
<message to='". $groupMembersArray[$i] . "#crossmessenger.com' type='groupchat' from='$mFrom'><x xmlns='jabber:x:event'><offline/><delivered/><displayed/></x><body>$message</body></message>
so for that i have written below code
$connection = mysqli_connect("localhost","xyz","abc#123","mydb");
for($i = 0 ; $i < $totalMembers ; $i++){
$stanzaToInsert = "<message to='". $groupMembersArray[$i] ."#crossmessenger.com' type='groupchat' from='$mFrom'><x xmlns='jabber:x:event'><offline/><delivered/><displayed/></x><body>$message</body></message>";
$msgSize = strlen($stanzaToInsert);
$insertQuery = "INSERT INTO ofOffline VALUES ('$groupMembersArray[$i]', $messageID, $creationDate, $msgSize, '$stanzaToInsert')";
mysqli_query($connection, $insertQuery);
mysqli_commit($connection);
echo "record $message inserted in table and commited";
}
but nothing is inserting in database. if i replace xml string that means value of stanzaToInsert to some simple text, then it is inserting value into database.
$insertQuery = "INSERT INTO ofOffline VALUES (
$groupMembersArray[$i],
$messageID,
$creationDate,
$msgSize,
'hard coded string'
)";
so problem is with xml string.
so can i know "what's wrong with me"?

you should use mysqli_real_escape_string before inserting the value like this
$stanzaToInsert = mysqli_real_escape_string($connection, $stanzaToInsert);

Please use "N" befor the xml string for inert the xml message like this:--
(NULL,N'<?xml version="1.0" encoding="utf-16" standalone="yes"?><!--This is a test XML file--><filemeta filetype="Audio"><Comments /><AlbumTitle /><TrackNumber /><ArtistName /><Year /><Genre /><TrackTitle /></filemeta>')
Yourcode should be like this:-
$insertQuery = "INSERT INTO ofOffline VALUES (
$groupMembersArray[$i],
$messageID,
$creationDate,
$msgSize,
N'$xmlstring'
)";

Related

Foreach error when insert to mysql

I got some error when inserting my data. for data 1-20 , the data inserted well. But after that foreach not inserted all data. Here is the data :
<?php
include "../conn.php";
$source="https://source1.com/json";
$file=file_get_contents($source,true);
$char_parse=json_decode($file,true);
foreach($char_parse['data'] as $a_item){
$item_sold=$char_parse2['item_sold'];
$success=$char_parse2['success'];
$reject=$char_parse2['reject'];
$sqli="INSERT INTO `product` VALUES (NULL, '".$item_sold."', '".$success."', '".$reject."')";
mysqli_query($conn,$sqli);
$i++;
}
$?>
Please help me solve this issues
I don't know enough about your data structure. But based on your code, let's assume...
$char_parse['data'] = array(
array('item_sold'=>'item1', 'success'=>1, 'reject'=>2),
array('item_sold'=>'item2', 'success'=>1, 'reject'=>2)
);
Then,
foreach($char_parse['data'] as $a_item){
$item_sold = $a_item['item_sold'];
$success = $a_item['success'];
$reject = $a_item['reject'];
$sqli = "INSERT INTO `product` VALUES (NULL, '".$item_sold."', '".$success."', '".$reject."')";
mysqli_query($conn,$sqli);
}
If I'm wrong about the data structure, the proposed code won't work.

how to prevent duplicate entry in mysql while data are entered from array?

I am new in android development I am sending a json array through android application and insert that data into MySQL database. The problem is that whenever I insert userJSON it entered every time with duplicate entries. So, I want to prevent duplicate entry in mysql how can this possible with php. Please help me to solve this problem.
json string from android side
'[{"type":"Outgoing","duration":"0","number":"XXXXXXXX","date":"Tue Dec 13 15:26:29 GMT+05:30 2016"},
{"type":"Outgoing","duration":"0","number":"XXXXXXXX","date":"Tue Dec 13 13:49:50 GMT+05:30 2016"}]';
Here is my php file for post json:
<?php
require_once('conn.php');
if($_SERVER['REQUEST_METHOD']=='POST')
{
$json = $_POST["usersJSON"];
echo $json;
if (get_magic_quotes_gpc())
{
$json = stripslashes($json);
}
$data = json_decode($json,true);
$query=mysqli_query($con,"SELECT *
FROM users
where number = '$number'
and type = '$type'
and date = '$date'
and duration= '$duration'");
if(mysqli_num_rows($query)>0) {
echo "already exist";
}
elseif(is_array($data))
{
$sql = "INSERT IGNORE INTO users (type, duration, number,date) values ";
$valuesArr = array();
foreach($data as $row)
{
$type = mysqli_real_escape_string( $con,$row['type'] );
$duration = mysqli_real_escape_string($con, $row['duration'] );
$number = mysqli_real_escape_string( $con,$row['number'] );
$date = mysqli_real_escape_string( $con,$row['date'] );
$valuesArr[] = "('$type', '$duration', '$number', '$date')";
}
$sql .= implode(',', $valuesArr);
if(mysqli_query($con,$sql))
{
echo 'Entry Added Successfully';
}
else
{
echo 'Could Not Add Entry';
}
}
//Closing the database
mysqli_close($con);
}
?>
Create a UNIQUE INDEX
Regardless of whatever programming language that you use, all the constraints on the data have to be enforced with in the database and not in your application layer. And the easiest way to do that is to add a UNIQUE KEY on the columns in question.
ALTER TABLE users ADD UNIQUE KEY all_columns(number,type,date,duration)
I am adding all the four columns to the unique index because you seem to want any column to have duplicate values taken in isolation. Please confirm if this is correct or choose the columns appropriately when creating the index.
Simply your code
With a unique key in place, your don't need that SELECT
$data = json_decode($json,true);
if(is_array($data))
{
$sql = "INSERT IGNORE INTO users (type, duration, number,date) values ";
....
}
Use Prepared Statements
Instead of a huge string concatenation as is being currently done and multple calls to mysqli_real_escape, you would be better of using prepared statements. You might even get a tiny increase in performance. However more importantly there is a maximum size of a string that can be passed through to the server, if you get a large array you might go beyond that.

inserting directory address in mysql php

I'm trying something with file upload and sql lately, and I have this small problem. When I'm trying to insert this string to sql, the sql insert different value. Here is the text I'm trying to insert.
C:\xampp\tmp\phpCD2.tmp
and here is the text inserted in mysql
C:xampp mpphpCD2.tmp
so from what I see the php/mysql remove all the '\' and convert the '\t' to a tab or spaces. I know it will be fix if I change the directory but what if I have some file starting with 't' so it will be remove, so How can I fix this. Thanks.
Here is the code:
foreach ($files['name'] as $position => $file_name)
{
$name = $files['name'][$position];
$tempName = $files['tmp_name'][$position];
$type = $files['type'][$position];
$size = $files['size'][$position];
echo $tempName, '<br>';
$insert = "INSERT INTO " . $table . " (id, name, tempName, type, size)
VALUES ('', '$name', '$tempName', '$type', '$size') ";
mysql_query($insert);
}
You have to escape the string.
$tempName = mysql_escape_string($files['tmp_name'][$position]);

Unable to insert data in MySQL from PHP script

I am trying to inser json data in MySQL database using the code below but getting values like Array[0][0],0.000 etc. can someone please suggest a solution.
The values in the variables are correct as the echo in loop is displaying the correct values in browser.
Thanks.
[EDIT]
The datatype of 'add' is varchar, for 'SN','imm' its int and rest is all double.
[/EDIT]
for($x=0; $x<$totaladdress; $x++)
{
echo $x;
echo "<br>add=";
echo $json_a[report][$x][0];
$sql = "INSERT INTO `report`.`tempmain` (`SN`, `add`, `last`,`imm`, `lastH`, `pa`, `unex`, `meg`, `bi`, `re`) VALUES (NULL, '$json_a[report][$x][0]','$json_a[report][$x][1][last]', '$json_a[report][$x][1][imm]', '$json_a[report][$x][1][lastH]', '$json_a[report][$x][1][pa]', '$json_a[report][$x][1][unex]', '$json_a[report][$x][1][meg]', '$json_a[report][$x][1][bi]', '$json_a[report][$x][1][re]');";
$result=mysql_query($sql);
}
$sql = "INSERT INTO `report`.`tempmain` (`SN`, `add`, `last`,`imm`, `lastH`, `pa`, `unex`, `meg`, `bi`, `re`) VALUES (NULL, '$json_a[report][$x][0]','$json_a[report][$x][1][last]', '$json_a[report][$x][1][imm]', '$json_a[report][$x][1][lastH]', '$json_a[report][$x][1][pa]', '$json_a[report][$x][1][unex]', '$json_a[report][$x][1][meg]', '$json_a[report][$x][1][bi]', '$json_a[report][$x][1][re]');";
Is inserting $json_a as an array and is not interpreting the rest. Try:
$sql = "INSERT INTO `report`.`tempmain` (`SN`, `add`, `last`,`imm`, `lastH`, `pa`, `unex`, `meg`, `bi`, `re`) VALUES (NULL, '".$json_a['report'][$x][0]."','".$json_a['report'][$x][1]['last']."', '".$json_a['report'][$x][1]['imm']."', '".$json_a['report'][$x][1]['lastH']."', '".$json_a['report'][$x][1]['pa']."', '".$json_a['report'][$x][1]['unex']."', '".$json_a['report'][$x][1]['meg']."', '".$json_a['report'][$x][1]['bi']."', '".$json_a['report'][$x][1]['re']."');";
I.e. rather than doing:
$sql = "some sql $json_a[report][$x][1][pa] other sql"
do
$sql = "some sql ".$json_a['report'][$x][1]['pa'] ." other sql";

Wrong mysql query in php file?

I'm trying to insert some data into my mysql database. The connection is working fine but im having a problem with sending the query correctly to the database. Below you can find the code in my php file. I also post what for type of fields they are in the Database.
Fields in the mysql database:
Reservaties_id = int
Materialen_id = int
aantal = int
effectief_gebruikt = tinyint
opmerking = Varchar2
datum_van = date
datum_tot = date
$resID = $_REQUEST['resID'];
$materialen_id = $_REQUEST['materialen_id'];
$aantal = $_REQUEST['aantal'];
$effectief_gebruikt = $_REQUEST['effectief_gebruikt'];
$opmerking = $_REQUEST['opmerking'];
$datum_van = date('YYYY-MM-DD',$_REQUEST['datum_van']);
$datum_tot = date('YYYY-MM-DD',$_REQUEST['datum_tot']);
$string = "INSERT INTO `materialen_per_reservatie`(`reservaties_id`, `materialen_id`, `aantal`, `effectief_gebruikt`, `opmerking`, `datum_van`, `datum_tot`) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', $datum_van, $datum_tot)";
mysql_query($string);
you have to include single quotes for the date fields '$dataum_van'
$string = "INSERT INTO `materialen_per_reservatie`(reservaties_id, materialen_id, aantal, effectief_gebruikt, opmerking, datum_van, datum_tot) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', '$datum_van', '$datum_tot')";
and this is only a example query, while implementing don't forget to sanitize your inputs
Your code has some serious problems that you should fix. For one, it is not doing any error checking, so it's no surprise the query breaks silently when it fails. Check for errors and it will tell you what goes wrong - how to do it is outlined in the manual on mysql_query() or in this reference question.. Example:
$result = mysql_query($string);
// Bail out on error
if (!$result)
{
trigger_error("Database error: ".mysql_error(), E_USER_ERROR);
die();
}
In this specific case, I'm fairly sure it's because you are not putting your values into quotes after the VALUES keyword.
Also, the code you show is vulnerable to SQL injection. You need to escape every value you use like so:
$resID = mysql_real_escape_string($_REQUEST['resID']);
for this to work, you need to put every value in your query into quotes.
try this
$string = "INSERT INTO `materialen_per_reservatie`(`reservaties_id`) VALUES ('".$resID."')";

Categories