I want to save image inside mysql database. How I can do that using php and angular??
Im using add-style.component.ts to upload image
imageUploadEvent(event){
let imageFile = event.target;
if(imageFile.files.length > 0){
console.log(imageFile.files[0]);
let formData = new FormData();
formData.append('file',imageFile.files[0]);
this._databaseService.insertImageData(formData).subscribe((msg) => {
console.log(msg);
},(error) =>{
console.log("Get Some Error");
console.log(error);
});
}
}
I use add-style.html as following
<div class="container">
<div class="row">
<div class="col s8 offset-2">
<div class="card-panel teal lighten-2">
<h4>Image Uploading</h4>
</div>
<form #imageform ="ngForm">
<input type="file" class="form-file-control" (change)="imageUploadEvent($event)">
<button type="submit" class="btn-lg btn-submit form-control" (click)="saveFormData()" >submit</button>
</form>
</div>
</div>
</div>
I use database.service.ts to call php
insertImageData(value){
return this._http.get("http://localhost/jeleena-api/test-img.php",value).pipe(map(res => {
console.log(res);
}));
}
Following is my php code
<?php
//Create Database Connection
include "db-connection.php";
if(!empty($_FILES['file'])){
$ext = pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION);
$image = time().'.'.$ext;
if(move_uploaded_file($_FILES["file"]["tmp_name"],$image)){
$sql = "INSERT INTO test(img) VALUES('".$image."')";
$conn->query($sql);
echo "successfully uploaded";
}
else{
echo ' error ';
}
}
?>
Ok bear with me. You can use ngStyle for this. https://angular.io/api/common/NgStyle
You need to install the commonsmodule in your ngModule.
Now in your template you can do the following to show the image:
<div [ngStyle]="background-image: url('./assets/images/youImage.jpg');">
Now you are able to show your image based on a url. So what you can do is instead of saving the image to the sql just simple save the ./assets/images/youImage.jpg.
<div [ngStyle]="background-image: url(yourObject.image)>
And to show the image, you can make an object give it a property image and assign the string from the sql.
Related
I have this code for search in my database, I use a barcode scanner (work like a keyboard), when I scan a barcode the input text shown perfectly, but I need to press MATCH to do the enter function, I want to submit it automatically after the barcode scanner scan a code and not to press MATCH.
<html>
<body>
<div class="container pt-5">
<div class="row">
<form method="POST" action="match.php" autocomplete="off">
<div class="form-group">
<label>Scan:</label>
<input type="text" id="no" name="no" class="form-control" required>
</div>
<div ></div>
<button class="btn btn-info" name="sub" type="submit">MATCH</button>
</form>
</div>
</div>
</body>
</html>
<?php
include 'includes/conn.php';
if (isset($_POST['sub'])) {
$sca=trim($_POST['no'],"");
$flag=0;
$credentials="";
$password="";
$firstname="";
$lastname="";
$new2 ="SELECT * FROM `voters`";
$res2=mysqli_query($conn, $new2);
while($row=mysqli_fetch_array($res2)){
//echo $row['number'].'<br>';
// if($row['number']){
if($row['credentials'] == $sca){
$flag=1;
$credentials=$row['credentials'];
$password=$row['password'];
$firstname=$row['firstname'];
$lastname=$row['lastname'];
}
}if ($flag==1) {
echo "<div class='container'><div class='row'><div class='col-sm-3'></div><div class='col-sm-6'><div class='alert alert-success d-flex justify-content-center mt-3'>".
'<br><b>Votante:</b>'.' '.$id.
'<br><b>Registro:</b>'.' '.$credentials.
'<br><b>Contraseña:</b>'.' '.$password.
'<br><b>Nombre:</b>'.' '.$firstname.
'<br><b>Apellidos:</b>'.' '.$lastname.
"</div></div></div><div class='row'><div class='col-sm-3'></div><div class='col-sm-6'>" ;
return;
}
else{
echo "<div class='alert alert-danger d-flex justify-content-center mt-3'>Product Not Found</div></div>";
return;
}
}
mysqli_close($conn);
?>
We had to work with barcode scanners a while ago, where we had a similar request, so I hope I can help here. Most simple barcode scanners just enter the scanned code and append a new line.
As stated in the comments you need some JavaScript in order to do that. We used the jquery library. Like CBroe said, you need to find the correct event, to use. We tried different events and found the "change" event to be the best suitable one for us.
Our case was a little more complex, because we had multiple fields and had to make ajax requests, so I tried to reduce our script to something that may be a good starting point for you:
$(document).ready(function() {
$('#no').change(function () { //if content of field with id #no changes do stuff
let value = $(this).val();
const minlength = 5;
if (value.length >= minlength) {
$( "#scanform" ).submit(); //submit form with id scanform
}
});
});
Pleas note, that this script assumes you add the id "scanform" to your form tag.
please i don't know the right way to ask this,but am working on a media so what i want is to display a chat box in all of my webpage once the user open it in my home,like facebook when you are chatting with a friend and you load another page that chat box will still display in the new loaded page,please who can help me i don't know how to start dealing with that.
when friend name is click chat box display but once the page reload or another page is load it diappear but i want to still be active once the user has not log out.
index.php
<div id="frnd_chats">
<div id="frnd_chat">
<div class="u_c_p"><a href="profile.php?id=<?php echo $row["id"]?>">
<img src="hangout<?php echo $row['photo'];?>"></a></div><div class="u_c_n" id="332">
<a href="profile.php?id=<?php echo $row["id"]?>" id="<?php echo $row["id"]?>">
<?php echo $row["firstname"]." "." "." "." ".$row["surname"];?></a></div> </div>
</div>
chat.js
$(".u_c_n a").click(function(e){
e.preventDefault();
var chatid = this.id;
//alert(uid);
$.ajax({
type:'get',
url:"chat.php",
data:{chatid:chatid},
success: function(data){
$(".msge").html(data);
}
});
});
chat.php
<?php
session_start();
include 'myhangout.php';
if(isset($_SESSION["email"])){
$eml = $_SESSION["email"];
if(isset($_GET["chatid"])){
$id = $_GET["chatid"];
$sql = $con->prepare("select * from imt where id=?");
$sql->bind_param('i',$id);
$sql->execute();
$result = $sql->get_result();
$row = $result->fetch_assoc();
echo $user = $row["id"];
?>
<div class="chat_box">
<div class="chat_ibox">
<div class="chat_upic_o_e"><div><img id="upic" title="upload photo" src="hangout<?php echo $row["photo"];?>"></div><div><img id="chat_option" src="option.jpg"> <img id="chat_exit" src="exit.jpg"></div>
</div>
<div class="chat_display">
test this work
</div>
<div class="chat_typ_txt">
<form method="" action="">
<input type="text" name="message" placeholder="Type a message">
</form>
</div>
<div class="stic_files">
<div><img id="chat_stickers" src="option.jpg"> <img id="chat_files" src="exit.jpg"></div>
</div>
</div>
<?php
}
}
?>
There are multiple questions[duplicates] about this same error but I can't find a solution in any of them. I`m trying to save an image in my local directory but 'Undefined index' keeps showing up. I´m a noob in php and stack overflow. I would really appreciate any of your help.
HTML:
<form method="post" action="process.php" enctype="multipart/form-data">
<fieldset>
<div class="col-xs-12 col-sm-push-5 image-div form-control">
<div class="input-margin">
<input type="file" name="imagenIngreso" class="filestyle" onchange="readURL(this);" data-buttonText="Subir Imagen" data-buttonName="btn-primary" data-size="nr" data-buttonBefore="false">
</div>
<div>
<img class="image-preview" id="blah" src=""/>
</div>
</div>
<div class="col-xs-12 col-sm-12 submit-button">
<button type="submit" class="btn btn-primary btn-block" name="submit" value="ingreso">Ingresar</button>
</div>
</fieldset>
</form>
PHP:
// Previous Validations
else if($_POST['submit'] == 'ingreso') {
$fileName = $_FILES['imagenIngreso']['name']; // Line throwing error
$uploadDirectory = "images/uploadedImages/Ingresos/";
if($uploadedFileName!='') {
$targetPath=time().$uploadedFileName;
if(move_uploaded_file($_FILES['imagenIngreso']['tmp_name'], $uploadDirectory.$targetPath)) {
$queryIngresos = "INSERT INTO ingresos (fechaIngreso, responsable, proyecto, items, imagePath) VALUES (STR_TO_DATE('$fechaEgreso','%d/%m/%Y'), '$responsable', '$proyectoIngreso', '$itemsArray', '$targetPath')";
if(!mysqli_query($con, $queryEgresos)) {
echo "Error while uploading file";
die('Error :'.mysqli_error($con));
} else {
echo 'Upload done';
exit();
}
}
}
You can also find what error are you getting using the Error Codes available.
Put this and make a try.
<?php
if($_FILES['userfile']['error']) {
// handle the error
} else {
// process
}
?>
I have a first page of a form, and then I use jQuery to load the second part of the form. However, after I click submit on the form, nothing happens, the page is just stuck here. Any ideas?
jQuery:
$.ajax({
type: "POST",
url: "join_submit.php",
data: data,
success: function () {
$("#regform").load("submitTranscript.php");
}
});
submitTranscript.php:
<div id="regform>
<form id="uploadTranscript" action="uploadPDF.php" enctype="multipart/form-data" method="post">
<div class="separation">
<h3>Upload Transcripts</h3>
<div class = "row">
<div class="large-6 offset-2 columns">
<label for = "studid">Enter your student ID:</lable>
<input type="text" name="studid" id="studid"
</div>
<p>Please label your transcript with your user id (i.e. 123456.pdf).</p>
<div class="row">
<div class="large-6 offset-2 columns">
<input type="file" name="transcript" id="transcript">
</div>
</div>
<div class="buttonRow">
<div class="button" id="submit">Submit</div>
</div>
</div>
</form>
</div>
uploadPDF.php:
<?php
require_once("included.php"); //server info
$allowedExtensions = array("pdf");
$max_filesize = 20000;
$upload_path = "docs/transcripts/";
$filename = $_FILES["transcript"]["name"];
$filesize = $_FILES["transcript"]["size"];
$extension = $_FILES["transcript"]["type"];
if ($_FILES["transcript"]["error"] > 0) {
echo "Error: " . $_FILES["transcript"]["error"] . "<br />";
}
else if((in_array($extension, $allowedExtensions)) && ($filesize < $max_filesize)) {
move_uploaded_file($_FILES["transcript"]["tmp_name"], $upload_path . $filename);
}
else if($filesize > $max_filesize){
$fileSizeFail = true;
}
else {
$fileTypeFail = true;
}
?>
If I look into submitTranscript.php, You have coded following for submitting your form:
<div class="buttonRow">
<div class="button" id="submit">Submit</div>
</div>
But, you haven't inserted any submit button to submit the form. Div element cannot post or submit any form. So, I would suggest to put an input type submit button then try to submit your form via that button.
So the code will be:
<div class="buttonRow">
<div class="button" id="submit">
<input type="submit" name="form_submit" value="Submit" />
</div>
</div>
You are not giving any information about join_submit.php file. You have to check in firebug console present in Firefox browser what is the return value of your join_submit.php file. Whether it is going to success function or not. Then only you can track why it is not loading the second form. In chrome browser you can trace the ajax request by clicking F12 and then Network.
Hope it helps
I am using jQuery (version 1.8.1) with PHP (version 5.3) to submit a form adding an entry into a mySQL database, what is happening is on the first submit everything is fine but for each subsequent submission without a page refresh it adds an additional entry.
In addition I'm also using Bootstrap (version 2.1.1) and the upload widget from Jasny for Bootstrap (version j1a) in the UI. I have not yet connected the upload widget to the processing or submit as I detected the duplication problem when I was implementing it.
Please note that this is a proof of concept system so the code is rough as I'm not going to invest in cleaning it up until the project is confirmed. Due to this, you will notice some inline mySQL queries, I know that this isn't the best way to do it however it works for the purpose of demonstration and will be cleaned up later. Also as a POC system it is on an internal server currently, I can share the code but cannot show an example site at this time unfortunately.
Now back to the issue, as an example, the first post for "Company 1" has 1 record added for "Company 1", the second record for "Company 2" adds 2 records for "Company 2", the third record for "Company 3" adds 3 records for "Company 3" and so on. If I reload the form page in any way (refresh or a new request) the problem restarts from the first submission.
I am using jQuery serialize with ajax to post the data to the PHP processor. I have logged all of the posts being received by the processor and I see the processor is receiving multiple records from the form, I thought it may have been caused by a foreach loop in the PHP but this is not the case.
I have removed the jQuery functions and it works perfectly each time without any duplicates on normal PHP submit.
I have manually processed the entries via jQuery instead of serialize but as there is a dynamic array via PHP I still used serialize on that array, this produced the duplicates as described above.
I have searched the issue for a number of days but cannot find anything definitive to clear up the issue, all suggestions on blogs and forums that looked to be related did not work, I have tried around 10-15 different options.
The combination of all of this leads me to believe the issue is coming from the jQuery serialize and/or ajax functions but my eyes have become glazed each time I look at this code now.
I am also considering placing the form in an external file and reloading it fresh via ajax or cleaning the form setting it back to defaults via jQuery for each new entry required however I do not believe either of these approaches will solve the problem.
Any help is greatly appreciated, thanks in advance for the help!
jQUERY code
<script>
$(document).ready(function() {
$('.fileupload').fileupload('name:logo');
$('.help-inline').hide();
$("#btn_process").click(function() {
$('form').submit(function() {
$('.help-inline').hide();
var company_name = $("#company_name").val();
if (company_name === "") {
$("div#name_group").addClass("error");
$("span#name_error").show();
return false;
}
var dataString = $('form').serialize();
$.ajax({
type: "POST",
url: "inc/addcompany.php",
data: dataString,
success: function(html) {
if(html === 'success')
{
$('#message')
.addClass("label label-success")
.css("margin-bottom","20px")
.html("<h3>Login successful</h3><p>Company added</p>")
.slideDown(1500, function() {});
}
else
{
$('#message')
.addClass("label label-important")
.css("margin-bottom","20px")
.html("<h3>Error</h3><p>There was an error, please check the information and try again</p>")
.slideDown(1500, function() {});
$("div#name_error").addClass("error");
$("span#name_error").show();
$("div#type_error").addClass("error");
$("span#type_error").show();
return false;
}
}
});
return false;
});
});
});
</script>
HTML markup
<form class="form-horizontal" id="add_company" method="POST" action="">
<fieldset>
<div id="message"></div>
<div id="name_group" class="control-group">
<label class="control-label" for="company_name">Company name </label>
<div class="controls">
<input type="text" id="company_name" name="company_name" />
<span id="name_error" class="help-inline">This needs to be more than 3 characters</span>
</div>
</div>
<div id="type_group" class="control-group">
<label class="control-label">Company type </label>
<div class="controls">
<?
$sql = "SELECT description,id FROM types ORDER BY description";
$qry = mysql_query($sql) or die("ERROR: could not get company types => ".mysql_error());
while($company_type = mysql_fetch_array($qry)) {
echo '
<label class="checkbox inline"><input type="checkbox" name="type[]" value="'.$company_type['id'].'" /> '.$company_type['description'].' </label>';
}
?>
<span id="type_error" class="help-inline">Please select a minimum of 1 type</span>
</div>
</div>
<div id="website_group" class="control-group">
<label class="control-label" for="website">Website </label>
<div class="controls">
<input type="text" id="website" name="website" placeholder="www.something.com" />
</div>
</div>
<div id="logo_group" class="control-group">
<label class="control-label">Logo </label>
<div class="controls">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="fileupload-new thumbnail" style="width: 50px; height: 50px;"><img src="/img/50x50.png" /></div>
<div class="fileupload-preview fileupload-exists thumbnail" style="width: 50px; height: 50px;"></div>
<span class="btn btn-file"><span class="fileupload-new">Select image</span>
<span class="fileupload-exists">Change</span>
<input type="file" /></span>
Remove
</div>
</div>
</fieldset>
<input type="hidden" name="action" value="add_company" />
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary" name="btn_process" id="btn_process">Save changes</button>
</form>
The PHP processor
$error = false;
$error_company_name = false;
$error_type = false;
$error_website = false;
$company_name = $_REQUEST['company_name'];
$type = $_REQUEST['type'];
$website = $_REQUEST['website'];
$logo = $_REQUEST['logo'];
if(empty($company_name)) {
$error = true;
$error_company_name = true;
}
include_once('db.php');
$sql = "SELECT description,id FROM company_types";
$qry = mysql_query($sql) or die("ERROR: could not get company types => ".mysql_error());
$type_count = 0;
while($array = mysql_fetch_array($qry)) {
$type_count = $type_count+1;
}
if($type_count == 0) {
$error = true;
$error_type = true;
}
$ic = 0;
foreach($_REQUEST['type'] as $item) {
$ic = $ic+1;
}
if($ic == 0) {
$error = true;
$error_type = true;
}
if(isset($website) && $website != ' ') {
$url = 'http://'.$website;
if(!filter_var($url, FILTER_VALIDATE_URL)) {
$error = true;
$error_website = true;
}
}
if($error == false) {
$sql = "INSERT INTO company_list (name,website,logo) VALUES('$company_name','$website','$logo')";
$qry = mysql_query($sql) or die ("ERROR: could not add company => ".mysql_error());
$company_id = mysql_insert_id($link);
if($company_id == '' || $company_id == null || empty($company_id)) {
echo 'fail';
exit;
}
foreach($_REQUEST['type'] as $company_type) {
$sql = "INSERT INTO companies_types (companies_id,type_id) VALUES('$company_id','$company_type')";
$qry = mysql_query($sql) or die("ERROR: could not link company type: => ".mysql_error());
}
echo 'success';
}
Add $('form').unbind('submit'); immediately above this line: $('form').submit(function().
I found this solution here: https://stackoverflow.com/a/668354/300575
Note: I verified that this works by copying your code and testing it on my server.
It may be a patch and dont know if it will work but there is a jQuery ajaxStop which can be called at the success call back.