javascript - Saving (with JS Request) and reading (with PHP) XML in MySQL -
i'm trying save xml content (that receive plain text) site's database. read saving xml content , suggested not idea save xml in text field (database), decided in blob. thing i'm doing via cors, through javascript way:
var formdata = new formdata(); formdata.append("name", 'mynewfile'); // xml content var content = '<a id="a"><b id="b">hey!</b></a>'; var blob = new blob([content], { type: "text/xml"}); formdata.append("file", blob); var request = new xmlhttprequest(); request.open("post", url); request.onreadystatechange = function() { if(request.readystate == 4 && request.status == 200) { resultscontainer.innerhtml = (request.responsetext ); } } request.send(formdata);
on server, store with:
$name = $_post['name']; $file = $_post['file']; $sql = "insert profilefiles (name, file) values ('$name', '$file')";
it seemed work, entry created in database can't see what's inside blob field. so, tried read server, using php, i'm retrieving "0" in file field.
$sql = "select datetime, name, file profilefiles"; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo "timestamp: " . $row["datetime"]."<br>"; echo "name: " . $row["name"]. "<br>"; echo "content: " + $row["file"]; echo "<br>----------<br>"; } } else { echo "nothing"; }
what missing? in advance! never worked php.
the reason why don't in $_post['file']
, sending file. files posted in superglobal variable $_files
not $_post
. $_files['file']
contain array
array('name' => '...', 'tmp_name' => '...', 'type' => '...', 'size' => '...');
the content saved temporary file name stored in $_files['file']['tmp_name']
you see, go astray here... have send xml data post variable , not file. when doing this, can save data database tried it, prepared statements, (assuming using mysqli
$name = $_post['name']; $file = $_post['file']; $sql = "insert profilefiles (name, file) values (?, ?)"; $stmt = $mysqli->stmt_init(); $stmt->prepare($sql); $stmt->bind_param("ss", $name, $file); $stmt->execute(); $stmt->bind_result($result); $stmt->fetch();
the point of using prepared statement :
if file contains '
, error in query. code vulnerable sql injection. need escape strings in query.
i never used mysqli myself, , code gave looks bit clumsy, here's alternative :
$sql = "insert profilefiles (name, file) values ('". mysqli_real_escape_string($name)."', '".mysqli_real_escape_string($file) ."')";
Comments
Post a Comment