The Data i am trying to insert is a blob or a file
This is for a school project and the lecturer said to insert it into the database for now.
This is what i have right now
function stop() {
cancelAnimationFrame(rafId);
endTime = Date.now();
$('#stop-me').disabled = true;
document.title = ORIGINAL_DOC_TITLE;
toggleActivateRecordButton();
console.log('frames captured: ' + frames.length + ' => ' +
((endTime - startTime) / 1000) + 's video');
embedVideoPreview();
};
function embedVideoPreview(opt_url) {
var url = opt_url || null;
var video = $('#video-preview video') || null;
var downloadLink = $('#video-preview a[download]') || null;
if (!video) {
video = document.createElement('video');
video.autoplay = true;
video.controls = true;
video.loop = true;
//video.style.position = 'absolute';
//video.style.top = '70px';
//video.style.left = '10px';
video.style.width = canvas.width + 'px';
video.style.height = canvas.height + 'px';
$('#video-preview').appendChild(video);
downloadLink = document.createElement('a');
downloadLink.download = 'capture.webm';
downloadLink.textContent = '[ download video ]';
downloadLink.title = 'Download your .webm video';
var p = document.createElement('p');
p.appendChild(downloadLink);
$('#video-preview').appendChild(p);
} else {
window.URL.revokeObjectURL(video.src);
}
if (!url) {
var webmBlob = Whammy.fromImageArray(frames, 1000 / 60);
url = window.URL.createObjectURL(webmBlob);
}
video.src = url;
downloadLink.href = url;
And this is how i am inserting it into the database from the same page i am also not to sure on where the video blob is also created.
<?php
require("connect.php");
$namey = video;
$up = mysql_query("INSERT INTO video VALUES ($namey)");
?>
Ok, so say you have an input for a user to upload a video...
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="VideoToUpload" />
<input type="submit" value="Upload Video" />
</form>
Then in your new upload.php you will want to process and save the file
$allowedExts = array("mp4", "mov");
$extension = end(explode(".", $_FILES["VideoToUpload"]["name"]));
if (($_FILES["VideoToUpload"]["type"] == "video/mp4") || ($_FILES["VideoToUpload"]["type"] == "video/quicktime")):
if($_FILES["VideoToUpload"]["error"] > 0):
echo "Error: " . $_Files["VideoToUpload"]["error"];
else:
move_uploaded_file($_FILES["VideoToUpload"]["tmp_name"], dirname(__FILE__) . "/FolderWhereIWantMyVideoSaved/" . $_FILES["VideoToUpload"]["name"]);
endif;
endif;
$VideoURL = "http://domain/and/path/to/FolderWhereIWantMyVideoSaved/" . $_FILES["VideoToUpload"];
$mysqli = new mysqli('ip.of.data.base', 'DatabaseName', 'Password', 'Username');
$stmt = $mysqli->prepare("INSERT INTO Videos (Name, Type, URL) VALUES (?,?,?)") or die ($mysqli->error);
$stmt->bind_param('sss', $_FILES["VideoToUpload"]["name"],$_FILES["VideoToUpload"]["type"], $VideoURL);
$stmt->execute() or die ($mysqli->error);
$stmt->close();
$mysqli->close();
Now the file is saved on the server, and the URL to that is in the database. So to display the video all you would then do is.
$mysqli = new mysqli('ip.of.data.base', 'DatabaseName', 'Password', 'Username');
$stmt = $mysqli->prepare("SELECT Name, Type, URL FROM Videos WHERE ID=?") or die ($mysqli->error);
$stmt->execute() or die($mysqli->error);
$stmt->bind_result($Name, $Type, $URL);
$stmt->store_result();
$stmt->fetch();
...
<video width="320" height="240" controls>
<source src="<?= $URL ?>" type="<?= $Type ?>">
Your browser does not support the video tag.
</video>
...
$stmt->close();
$mysqli->close();
Related
I want to upload User images via AJAX to PHP Database. I tried multiple tutorials and other examples but nothing worked for my code. The codes work when used without AJAX but since I don't wish my users to see the upload page and stay on the same page that's why the thought of adding AJAX to the code. So have been trying this code for the past few hours but nothing worked in my favor. The files are not getting uploaded nor the data in the database is getting updated.
file: test.php
<script>
function triggerClick(e) { document.querySelector('#profileImage').click(); }
function displayImage(e) { if (e.files[0]) {
var reader = new FileReader();
reader.onload = function(e){
document.querySelector('#profileDisplay').setAttribute('src', e.target.result);
}
reader.readAsDataURL(e.files[0]); } }
$(document).on('click',"#UploadImage", function(){
var fd = new FormData();
var profileImage = $('#profileImage')[0].files[0];
//fd.append('profileImage',profileImage);
var bio = document.getElementById( "bio" ).value;
$.ajax({
url:"include/Upload.php",
method:"POST",
data: fd,
contentType: false,
processData: false,
success:function(data){
alert(data);
if(data == "Login Successful") {
}
else {
alert(data);
}
}
})
});
</script>
File : Upload .php
<?php
session_start();
include('connection.php');
$msg = "";
$msg_class = "";
$Username = $_SESSION['Username'];
//echo var_dump($Username);
$conn = mysqli_connect("localhost", "root", "1234567890", "test");
$Status = stripslashes($_POST['bio']);
echo var_dump($Status);
$profileImageName = $Username. '-' . time() . '-' . $_FILES['profileImage']['name'];
echo var_dump($profileImageName);
$target_dir = "../UserImages/";
$target_file = $target_dir . basename($profileImageName);
if($_FILES['profileImage']['size'] > 200000) {
$msg = "Image size should not be greated than 200Kb";
$msg_class = "alert-danger";
}
// check if file exists
if(file_exists($target_file)) {
$msg = "File already exists";
$msg_class = "alert-danger";
}
// Upload image only if no errors
if (empty($error)) {
if(move_uploaded_file($_FILES["profileImage"]["tmp_name"], $target_file)) {
$sql = "UPDATE users_login SET Image='$profileImageName', Status='$Status' WHERE Username='$Username'";
echo var_dump($sql);
//header("location: profiles.php")
if(mysqli_query($conn, $sql)){
session_start();
$query="select * from $dbtable WHERE Username = '".$Username."' ";
echo $query;
$result2=#mysqli_query($connection,$query);
$row=mysqli_fetch_assoc($result2);
$_SESSION['ProfileImage']= $row['Image'];
print_r($_SESSION['ProfileImage']);
$_SESSION['Status']= $row['Status'];
$msg = "Image uploaded and saved in the Database";
$msg_class = "alert-success";
} else {
$msg = "There was an error in the database";
$msg_class = "alert-danger";
}
} else {
$error = "There was an error uploading the file";
$msg = "alert-danger";
}
}
?>
Removing those comments // worked and had to add another append line for bio and it worked. It wasn't working yesterday that's why I commented // on it. It's working properly now! Here's my new code that made it work...
var fd = new FormData();
var profileImage = $('#profileImage')[0].files[0];
fd.append('profileImage',profileImage);
var bio = document.getElementById( "bio" ).value;
fd.append('bio', bio);
Credits to: Ken Lee & charlietfl for their comments.
I am calling selected images from mysql and then using the jquery resizable script below. Problem is the resized object/image coordinates are not saving unique to its id but rather the last objects id. If I specifically hard code the id it works. Can anyone shed some light on what, where, how I am doing it wrong. Thank you.
<?php
$get_coords = mysqli_query($link, "SELECT * FROM images WHERE appear = 'Yes' AND publication_id = '2'");
while($row = mysqli_fetch_array($get_coords)) {
$id = $row['image_id'];
$x = $row['x_pos'];
$y = $row['y_pos'];
$h = $row['h_pos'];
$w = $row['w_pos'];
$z_depth = $row['z_depth'];
$name = $row['image_name'];
echo "<div id='resizable' class='resizable' style='left:".$x."px; top:".$y."px; height:".$h."px; max-width: 1280px; width:".$w."px; z-index:".$z_depth.";'><img src='../article_images/$name'/></div>";
}
?>
<script type="text/javascript">
var id = '<?php echo $id; ?>';
$('.resizable').resizable({
start : function(event,ui) {
startW = $(this).outerWidth();
startH = $(this).outerHeight();
},
stop : function(event,ui) {
endW = $(this).outerWidth();
endH = $(this).outerHeight();
$.post('updatedimensions.php', { endW: endW, endH: endH, id: id }); //If I hard code the id here it works fine
}
});
</script>
updatedimensions.php
<?php
$link = mysqli_connect($db_host, $db_usr, $db_pass) or die("MySQL Error: " . mysqli_error());
mysqli_select_db($link, $db_name) or die("MySQL Error: " . mysqli_error());
$w_coord=$_POST['endW'];
$h_coord=$_POST['endH'];
$id=$_POST['id'];
$sql = "UPDATE images SET h_pos = '$w_coord', w_pos = '$h_coord' WHERE image_id = '$id'";
mysqli_query($link, $sql) or die("Error updating Coords :".mysqli_error());
?>
I am using below scripts to build an image gallery
1) scriptphoto.js
2) acceptcomment.php
3) edit_album.php
Edit_album.php contains a mysql query which run when an Image get click (to print comments if image is shared)
html:
<div id="photo_preview" style="display:none">
<div class="photo_wrp">
<img class="close" src="uploads/close.gif" />
<div style="clear:both"></div>
<div class="pleft">test1</div>
<div class="pright">test2</div>
<div style="clear:both"></div>
</div>
</div>
and Javascript on scriptphoto.js
function getPhotoPreviewAjx(id,name) {
$.post('edit_album.php',{action:'get_info',Id:id},
function(data){
if (name == 'YES'){
$('#photo_preview .pleft').html(data.data1);
$('#photo_preview .pright').html(data.data2);
$('#photo_preview').show();
}
else{
$('#photo_preview .pleft').html(data.data1);
$('#photo_preview .pright').html(data.data3);
$('#photo_preview').show();
}
}, "json"
);
};
php code on edit_album.php for that is
if ($_POST['action'] == 'get_info' && (int)$_POST['Id'] > 0) {
$iPid = (int)$_POST['Id'];
$shared = $_POST['shared'];
$sComments = '';
$sq= "SELECT * FROM comment_table WHERE ImageSN = '".$iPid."' ORDER BY C_when ASC LIMIT 10";
$sql = mysql_query($sq);
while($query = mysql_fetch_array($sql))
{
$sWhen = date('F j,Y' , $query['C_when']);
$sComments .= "<div class=\"comment\" id='".$query['C_id']."'>
<p>Comment from '".$query['c_name']."' <span>(".$sWhen.")</span>:</p>
<p>".$query['c_text']."</p>
</div>" ;
}
$sharewarning .="<div id='sharewarning'>Share Images To Enable Comments</div>";
$sCommentsBlock .="<div class=\"comments\" id=\"comments\">
<h2>Comments</h2>
<div id=\"comments_warning1\" style=\"display:none\">Don`t forget to fill both fields (Name and Comment)</div>
<div id=\"comment_warning2\" >You can't post more than one comment per 10 minutes (spam protection)</div>
<form onsubmit=\"return false;\">
<table>
<tr><td class=\"label\"><label>Your name: </label></td><td class=\"field\"><input type=\"text\" value=\"\" title=\"Please enter your name\" id=\"name\" /></td></tr>
<tr><td class=\"label\"><label>Comment: <input type=\"hidden\" name=\"action\" value=\"accept_comment\"></label></td><td class=\"field\"><textarea name=\"text\" id=\"text\"></textarea></td></tr>
<tr><td class=\"label\"> </td><td class=\"field\"><button onclick=\"submitComment(".$iPid."); return false;\">Post comment</button></td></tr>
</table>
</form>
<div><span id=\"commentspsn\"></span>
<div id=\"comments_list\">".$sComments."</div>
</div>";
$imageInfo = '';
$selecT = "SELECT imagesrc FROM imagerate WHERE ImageSN ='".$iPid."'";
$table = mysql_query($selecT);
while($query = mysql_fetch_array($table))
{
$imageInfo.=$query['imagesrc'];
}
require_once('classes/Services_JSON.php');
$oJson = new Services_JSON();
header('Content-Type:text/javascript');
echo $oJson->encode(array(
'data1' => '<img class="fileUnitSpacer" src="uploads/'. $imageInfo.'">' . $sPrevBtn . $sNextBtn ,
'data2' => $sCommentsBlock,
'data3' => $sharewarning,
));
exit;
}
when a image get clicked to view it shows like this
Till this it works fine but when I Insert a comment successfully, I want to refresh comments to show new comment thats where I got struck
jquery code for handling comments and inserting them is below
function submitComment(id) {
var sName = $('#name').val();
var sText = $('#text').val();
if (sName && sText) {
$.post('acceptcomment.php', { action: 'accept_comment', name: sName, text: sText, id: id },
function(data){
if (data != '1') {
$('#comments_list').fadeOut(2000, function () {
$(this).html(data);
$(this).fadeIn(1000);
});
$("#commentspsn").html('<span id="commentspan"> <b>comment Submitted</b></span>');
}
}
);
} else {
$('#comments_warning1').fadeIn(1000, function () {
$(this).fadeOut(1000);
});
}
};
acceptcomment.php code is
$iItemId =(int)$_POST['id']; // prepare necessary information
$sIp = getVisitorIP();
$sName = $_POST['name'];
$sText = $_POST['text'];
if ($sName && $sText) {
$sql = "SELECT ImageSN FROM comment_table WHERE ImageSN = '".$iItemId."' AND commentip = '".$sIp."' AND C_when >= 'UNIX_TIMESTAMP()-600' LIMIT 1";
$query = mysql_query($sql);
$array = mysql_num_rows($query);
if ($array == 0 ) {
$insert = "INSERT INTO comment_table SET ImageSN = '".$iItemId."' , commentip = '".$sIp."' , C_when = UNIX_TIMESTAMP(), c_name = '".$sName."', c_text ='".$sText."'";
$sql = mysql_query($insert);
$update= 'UPDATE imagerate SET comment_counts = comment_counts + 1 WHERE ImageSN = "'.$iItemId.'"';
$query = mysql_query($update);
}
}
return 1;
need guideness
Modify your accept comment.php to return a json response as below code.
// prepare necessary information
$iItemId =(int)$_POST['id'];
$sIp = getVisitorIP();
$sName = $_POST['name'];
$sText = $_POST['text'];
$oJson = new Services_JSON();
if ($sName && $sText) {
$sql = "SELECT ImageSN FROM comment_table WHERE ImageSN = '".$iItemId."' AND commentip = '".$sIp."' AND C_when >= 'UNIX_TIMESTAMP()-600' LIMIT 1";
$query = mysql_query($sql);
$array = mysql_num_rows($query);
if ($array == 0 ) {
$insert = "INSERT INTO comment_table SET ImageSN = '".$iItemId."' , commentip = '".$sIp."' , C_when = UNIX_TIMESTAMP(), c_name = '".$sName."', c_text ='".$sText."'";
$sql = mysql_query($insert);
$update= 'UPDATE imagerate SET comment_counts = comment_counts + 1 WHERE ImageSN = "'.$iItemId.'"';
$query = mysql_query($update);
$data = array("item_id"=>$iItemId,"name"=>$sName,"text"=>$sText);
return $oJson->encode($data);
}
}
return $oJson->encode(array("error"=>"Error while updating the comment"));
In your Javascript code update the comment section with the received text
function submitComment(id) {
var sName = $('#name').val();
var sText = $('#text').val();
if (sName && sText) {
$.post('acceptcomment.php', { action: 'accept_comment', name: sName, text: sText, id: id },
function(data){
if (!data.error) {
$('#comments_list').fadeOut(2000, function () {
$(this).html(data.text);
$(this).fadeIn(1000);
});
$("#commentspsn").html('<span id="commentspan"> <b>comment Submitted</b></span>');
}
}
);
} else {
$('#comments_warning1').fadeIn(1000, function () {
$(this).fadeOut(1000);
});
}
};
I have problem.
That code should change image on site after success or error:
pastebin
if(isset($func) and $func == 'claim_bonus'){
global $ado;
$user = escape($_GET['user']);
$type = escape($_GET['type']);
$now = date("Y-m-d H:i:s");
$points = rand(1,20);
$query = $ado->exec("INSERT INTO `claimed_bonuses` SET `user` = '$user', `date` = '$now', `type` = '$type'");
$query1 = $ado->exec("INSERT INTO `history` SET `user` = '$user', `date` = '$now', `type` = 'bonus', `amount` = '$points', `title` = 'Bonus Claimed', `description` = '$user claimed bonus $points points'");
$query2 = $ado->exec("update `balances` SET `actual` = actual+$points, `total` = total+$points");
if ($query && $query1 && $query2) {
echo "<img src=\"/img/bonus/add_used.png\" width=\"30%\" height=\"30%\" alt=\"Bonus claimed\" />";
} else {
echo "<img src=\"/img/bonus/error.png\" width=\"30%\" height=\"30%\" alt=\"Error\" />";
}
}
Im calling ajax using ajax.js file
// JavaScript Document
var xmlhttp=false;
function claimbonus(user, type, id){
xmlhttp = new XMLHttpRequest();
xmlhttp.abort();
xmlhttp.open("GET", "/functions/ajax.php?func=claim_bonus&user="+user+"&type="+type, true);
xmlhttp.onreadystatechange=function() {
if(xmlhttp.status == 200) {
document.getElementById(id).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
And code is loaded on page.
Script is returning image but it doesnt replace old image.
Image code:
<img src="img/bonus/add.png" width="30%" height="30%" alt="Claim bonus" id="add_img" onclick="claimbonus(<?php echo $_SESSION['userid']; ?>, '<?php echo $type; ?>', 'add_img'); return false"/>
I hope someone can help me
You are replacing the innerHTML of the image tag. Wrap in a div or span and replace that instead and quote the userid too
<span id="add_img"><img
src="img/bonus/add.png" width="30%" height="30%"
alt="Claim bonus"
onclick="claimbonus('<?php echo $_SESSION['userid']; ?>',
'<?php echo $type; ?>', 'add_img')/></span>
I am having an issue with my AJAX and MySQL/PHP script.
The first file below, is my javascript file I use to test accessing my server. This file works as far as I know and have tested.
Game = function() {};
var timer;
Game.EncodeURI = function (text) {
return encodeURIComponent(text);
}
Game.DecodeURI = function (text) {
return decodeURIComponent(text);
}
Game.AlterDiv = function(div,data) {
if (Game.ID(div)) {
Game.ID(div).innerHTML = data;
}
}
Game.ID = function(value) {
return document.getElementById(value);
}
Game.ServerRequest = function (url, data) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
data = xmlhttp.responseText.split("|");
for (i = 0; i < data.length; i++){
var one = Game.DecodeURI(data[parseInt(i)]);
var two = Game.DecodeURI(data[parseInt(i) + 1]);
var three = Game.DecodeURI(data[parseInt(i) + 2]);
var four = Game.DecodeURI(data[parseInt(i) + 3]);
var five = Game.DecodeURI(data[parseInt(i) + 4]);
}
} else {
return false;
}
}
if (!data) {
data = "";
}
data = data.replace(/: /gi, "=");
data = data.replace(/:/gi, "=");
data = data.replace(/, /gi, "&");
data = data.replace(/,/gi, "&");
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data);
}
Game.Action = function (id, seconds) {
clearTimeout(timer);
if (id) {
if (!seconds) {
Game.AlterDiv('message', 'You begin working.');
Game.ServerRequest("action.php", "id: " + id);
} else {
Game.AlterDiv('message', 'You begin working.');
Game.ID('timer').innerHTML = seconds;
if (seconds >= 2) {
seconds -= 1;
Game.ID('timer').innerHTML = seconds;
timer = setTimeout(function(){
Game.Action(id, seconds);
},1000);
} else {
Game.ID('timer').innerHTML = "Finished";
Game.ServerRequest("action.php", "id: " + id + ", x: x"); // Request it, then POST "x" to say timer has counted down.
}
}
} else {
alert("There was an error with your request.\n Please try again.");
}
}
This second file is a basic PHP web page that I use to test the said function.
<html>
<head>
<title>Test</title>
</head>
<body>
<span onClick="Game.Action('1','5');">Start Work</span><br /><br />
<div id="message"></div>
<div id="timer"></div>
</body>
</html>
<script type="text/javascript" src="game.js?<?php echo time(); ?>"></script><!-- the time() stops it cache-ing -->
This third file is my PHP/MYSQL file that I use to connect to the database.
<?php
$mysqli = new mysqli_connect("127.0.0.1", "root", "", "gurstang");
$id = $_POST['id'];
if(isset($_POST['x'])) {
$x = true;
}else{
$x = false;
}
$userid = 1;
$query = "SELECT * FROM `action_info` WHERE `actionid` = '$id'";
if($result = $mysqli->query($query)){
while ($row = $result->fetch_assoc()) {
$action_name = $row['name'];
$basetimer = $row['time'];
$gaineditem = $row['itemid'];
}
$result->free();
}
$query = "SELECT `item`,`plural` FROM `items` WHERE `itemid` = '$gaineditem' LIMIT 0,1";
if($result = $mysqli->query($query)){
while($row = $result->fetch_assoc()){
$gained_item = $row['item'];
$gained_plural = $row['plural'];
}
$result->free();
}
if($x == false){
echo "Action|$id|"5"";
$message = "You have begun working.";
echo "AlterDiv|message|$message";
}
if($x == true){
echo "Action|$id|"5"";
$itemnumber = mt_rand(1,2);
$gainedmessage = "You have gained $itemnumner $gained_item.";
echo "AlterDiv|message|$gainedmessage";
$query = "SELECT `count` FROM inventory WHERE userid = '$userid' AND itemid = '$gaineditem' LIMIT 0,1";
if($result = $mysqli->query($query)){
while($row = $result->fetch_assoc()){
$count = $row['count'];
$add = $count + $itemnumber;
$updatequery = "UPDATE `inventory` SET `count` = '$add' WHERE `userid` = '$userid' AND `itemid` = '$gaineditem'";
$mysqli->query($updatequery);
}
}
else{
$insertquery = "INSERT INTO `inventory` (`userid`, `itemid` ,`count`) VALUES ('$userid', '$gaineditem', '1')";
$mysqli->query($insertquery);
}
}
?>
Those are all 3 of the file currently to run my script. I have an onclick event in the php webpage, and it sends the values to my Javascript function of Game.Action. After testing I have concluded or at least assume that my Javascript function for Game.Action works. After testing my Game.ServerRequest function, I have concluded that there is a change somewhere happening. Although, when I check my server to see if the updates actually happened, nothing happens. It doesn't update the timer div or the message div properly.
So basically my question is, is my issue with PHP/MYSQL or AJAX?
Thanks for your help.