Upload file path from array to database - javascript

I currently am able to save multiple individual files to folder using an array. Now I would like to add the individual file paths from the folder into a database.
How would I be able to get the individual paths of each file uploaded to folder?
From there how would I insert those individual paths into my database into separate fields?
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<p><input type="file" name="file_array[]"></p>
<p><input type="file" name="file_array[]"></p>
<p><input type="file" name="file_array[]"></p>
<input type="submit" value="Upload all files">
</form>
</body>
</html>
PHP:
<?php
if(isset($_FILES['file_array'])){
$name_array = $_FILES['file_array']['name'];
$tmp_name_array = $_FILES['file_array']['tmp_name'];
$type_array = $_FILES['file_array']['type'];
$size_array = $_FILES['file_array']['size'];
$error_array = $_FILES['file_array']['error'];
$imageFileType = pathinfo($path,PATHINFO_EXTENSION);
$path = 'uploads/' . $_FILES['my-file']['name'];
for($i = 0; $i < count($tmp_name_array); $i++){
if(move_uploaded_file($tmp_name_array[$i], "uploads/".$name_array[$i])){
echo $name_array[$i]." upload is complete<br>";
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
}
$conn_info = "host=d port= dbname= user= password=";
$dbconn = pg_connect($conn_info)
or die('could not connect:' . pg_last_error());
echo"<br/>sucessful connection";
$query = "INSERT INTO photo2 (path) VALUES ('".$path."') ;";
$result = pg_query($dbconn, $query);
if (!$result) {
$errormessage = pg_last_error();
echo "<br/> error with query: " . $errormessage;
exit();
}
echo "<br/> file uploaded to PostgreSQL";
pg_close();
?>

Get the path in for loop. And also write insert query in loop.
Database connection code has to be before for loop.
for($i = 0; $i < count($tmp_name_array); $i++){
if(move_uploaded_file($tmp_name_array[$i], "uploads/".$name_array[$i])){
// get path
$path = "uploads/".$name_array[$i];
echo $name_array[$i]." upload is complete<br>";
// Insert query comes here
$query = "INSERT INTO photo2 (path) VALUES ('".$path."') ;";
pg_query($dbconn, $query);
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}

There is the full code you need. I think it's may help you sir.
<?php
$conn_info = "host=d port= dbname= user= password=";
$dbconn = pg_connect($conn_info) or die('could not connect:' . pg_last_error());
echo "<br/>sucessful connection";
if(isset($_FILES['file_array'])){
$name_array = $_FILES['file_array']['name'];
$tmp_name_array = $_FILES['file_array']['tmp_name'];
$type_array = $_FILES['file_array']['type'];
$size_array = $_FILES['file_array']['size'];
$error_array = $_FILES['file_array']['error'];
// you don't need this lines of code
// $imageFileType = pathinfo($path, PATHINFO_EXTENSION);
// $path = 'uploads/' . $_FILES['my-file']['name'] . '.' . $imageFileType;
for($i=0;$i<count($tmp_name_array);$i++) {
$path = "uploads/" . $name_array[$i];
if(move_uploaded_file($tmp_name_array[$i], $path)){
$query = "INSERT INTO photo2 (path) VALUES ('".$path."');";
$result = pg_query($dbconn, $query);
if (!$result) {
$errormessage = pg_last_error();
echo "<br/> error with query: " . $errormessage;
exit();
} else {
echo $name_array[$i]." upload is complete<br>";
}
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
}
echo "<br/> file uploaded to PostgreSQL";
pg_close();
?>

Related

How to continue code to allow me to click on image and display a separate page with more info

As of right now, I am able to display my images in a single column, with an image, a title, and a small description. All of this is derived from the same database. I am not very good at coding and need some guidance, how would you add onto this existing code to 1) allow the pictures to be displayed in more than one column...and 2)allow the thumbnails to be clicked on, which will load a separate page that I can then style and list the full recipe on.
I have been messing with the code in general, and I am confused by what I created. I am not sure how to proceed.
<h2>index.php:</h2>
<section class="gallery-links">
<div class="wrapper">
<div class="gallery-container">
<?php
include_once 'includes/dbh.inc.php';
$sql = "SELECT * FROM gallery ORDER BY orderGallery DESC"
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statment failed!";
} else {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
echo '<a href="#">
<div style="background-image: url(img/gallery/'.$row["imgFullNameGallery"].');"></div>
<h3>'.$row["titleGallery"].'</h3>
<p>'.$row["descGallery"].'</p>
</a>';
}
}
?>
</div>
<?php
echo '<div class="gallery-upload">
<form action="includes/gallery-upload.inc.php" method="post" enctype="multipart/form-data">
<input type="text" name="filename" placeholder="File name...">
<input type="text" name="filetitle" placeholder="Image title...">
<input type="text" name="filedesc" placeholder="Image description...">
<input type="file" name="file">
<button type="submit" name="submit">Upload</button>
</form>
</div>'
?>
</div>
</section>
<h2>gallery-upload.inc.php:</h2>
<?php
if (isset($_POST['submit'])) {
$newFileName = $_POST['filename'];
if (empty($newFileName)) {
$newFileName = "gallery";
} else {
$newFileName = strtolower(str_replace(" ", "-", $newFileName));
}
$imageTitle = $_POST['filetitle'];
$imageDesc = $_POST['filedesc'];
$file = $_FILES["file"];
$fileName = $file["name"];
$fileType = $file["type"];
$fileTempName = $file["tmp_name"];
$fileError = $file["error"];
$fileSize = $file["size"];
$fileExt = explode(".", $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array("jpg", "jpeg", "png");
if (in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if($fileSize < 2000000) {
$imageFullName = $newFileName . "." . uniqid("", true) . "." . $fileActualExt;
$fileDestination = "../images/gallery/" . $imageFullName;
include_once "dbh.inc.php";
if (empty($imageTitle) || empty($imageDesc)) {
header("Location: ../index.php?upload=empty");
exit();
} else {
$sql = "SELECT * FROM gallery;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed!";
} else {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$rowCount = mysqli_num_rows($result);
$setImageOrder = $rowCount + 1;
$sql = "INSERT INTO gallery (titleGallery, descGallery, imgFullNameGallery, orderGallery) VALUES (?, ?, ?, ?);";
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed!";
} else {
mysqli_stmt_bind_param($stmt, "ssss", $imageTitle, $imageDesc, $imageFullName, $setImageOrder);
mysqli_stmt_execute($stmt);
move_uploaded_file($fileTempName, $fileDestination);
header("Location: ../index.php?upload=success");
}
}
}
} else {
echo "File size is too big!";
exit();
}
} else {
echo "You had an error!";
exit();
}
} else {
echo "You need to upload a proper file type!";
exit();
}
<h2>dbh.inc.php:</h2>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "gallery";
$conn = mysqli_connect($servername, $username, $password, $dbname);
Basically, you need to make a link on anchor tag which will have url of image detailed page with image id as below:
while ($row = mysqli_fetch_assoc($result)) {
// assuming that imgId is your primary key
echo '<a href="detail.php?imageId="'.$row["imgId"].' target="_blank">
<div style="background-image: url(img/gallery/'.$row["imgFullNameGallery"].');"></div>
<h3>'.$row["titleGallery"].'</h3>
<p>'.$row["descGallery"].'</p>
</a>';
}
After, you need to create a new file detail.php where you can get image id by $_GET['imgId'] and then can query on that and will be able to get complete image details. You will also need to create a HTML for view and can show details.
Hope it helps you!!

unable to display images in a list after uploading using the user id

im trying to display images in a list after uploading, i want php to fetch the images using the 'user_id' from the database.
here's my php code
<div class="container-two">
<?php
$image = "";
$caption = "";
if ("POST" == $_SERVER['REQUEST_METHOD']){
$caption = $_POST['Caption'];
$con = mysqli_connect("localhost","root","Y1qSYlz1iTNBMCfY","schedios");
$query = "SELECT Img_dir FROM images WHERE user_id = '".$_SESSION['user_id']."' ";
$result = mysqli_query($con,$query);
$row = $result->mysqli_fetch_assoc();
$image = $row['Img_dir'];
}
?>
<div>
<?php
$array = array();
while ($row = mysqli_fetch_assoc($query) ) {
$array['user_id'] = $row['user_id'];
echo "<ul><li ><img src='$image' ></li></ul>";}
?>
</div>
i have a table of designers, so this is the dashboard, where the user can upload images and display , thanks in advance to help.
Why are you trying to fetch $query ?
$row = mysqli_fetch_assoc($query)
You should to do the same with $result if i'm getting you right
while ($row = mysqli_fetch_assoc($query) ) {
$image = $row['Img_dir']; // maybe add $row['Img_name'] if exist in your database
// $array['user_id'] = $row['user_id'];// you already know userid from $_SESSION, right ?
echo "<ul><li ><img src='$image' ></li></ul>";}
It seems that, you are trying to echo image dir in li only, so try to save full image path in database while uploading, let me give you, sample code to give an idea.
Receive image uploaded by user from form:
// image file directory
$target = "images/".basename($image);
$sql = "INSERT INTO images (user_id,image)
VALUES
('".$_SESSION['user_id']."','$image')";
// execute query
mysqli_query($con, $sql);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
}
$result = mysqli_query($db, "SELECT * FROM images WHERE user_id =
'".$_SESSION['user_id']."' ");
?>
2.Display images back to user on unordered list:
<div id="content">
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
echo "<ul><li>img src='images/".$row['image']."' /><li></ul>";
echo "</div>";
}
?>

Can't run <Script> after redirection from php

I have two files named index.php and uploadcover.inc.php. Everything is working fine, except the script tags being executed if the upload fails for any of the if-else conditions. Here is the code:
index.php =>
<form action="include/uploadcover.inc.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="cover-upload" style="display:none" onchange="this.form.submit();">
<label for="cover-upload" class="fa fa-camera fa-2x" aria-hidden="true"></label>
</form>
uploadcover.inc.php =>
<?php
session_start();
include_once 'dbh.inc.php';
$sessionid = $_SESSION['u_id'];
$filename = "../profile/cover".$sessionid.".*";
$fileinfo = glob($filename);
$fileExt= explode('.',$fileinfo[0]);
$fileActualExt= $fileExt[3];
$file = "../profile/cover".$sessionid.".".$fileActualExt;
if(!unlink($file)){
echo "File not deleted";
} else {
"File deleted";
}
$sql = "UPDATE coverimg SET status=1 WHERE user_id='$sessionid';";
mysqli_query($conn,$sql);
$file= $_FILES['file'];
$fileName= $file['name'];
$fileTmpName= $file['tmp_name'];
$fileSize= $file['size'];
$fileError= $file['error'];
$fileType= $file['type'];
$fileExt = explode('.',$fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg','jpeg','png','gif');
if(in_array($fileActualExt,$allowed)){
if($fileError=== 0){
if($fileSize<3145728){
$fileNameNew = "cover".$sessionid.".".$fileActualExt;
$fileDestination = '../profile/'.$fileNameNew;
move_uploaded_file($fileTmpName,$fileDestination);
$sql = "UPDATE coverimg SET status=0 WHERE user_id='$sessionid'";
mysqli_query($conn,$sql);
header("Location: ../index.php?upload=success");
} else {
header("Location: ../index.php?upload=size_exceeded_3MB");
exit();
echo "<script>alert('File should be less than 3MB!')</script>";
}
} else {
header("Location: ../index.php?upload=error");
exit();
echo "<script>alert('Error uploading the file!')</script>";
}
} else{
header("Location: ../index.php?upload=typeerror");
exit();
echo "<script>alert('Filetype not supported!')</sc
ript>";
}
Note: I tried die(), exit() and also removing them in case it executes the script after being redirected to index.php but it doesn't work.
A redirect tells the client that why they are looking for can be found at a different URL. The client then requests that other URL and displays that document instead.
You can't simultaneously say "Here is the document you should show" and "The document you should show can be found over here". It is one or the other.

Connect, Insert and retrieve information from Postgresql in Javascript or JS

I have connected and pull retrieve some data using PHP but I would like to know:
It is PHP or Javascrip , JS better to interacts with Postgresql
It is an easy way to do the same as my PHP code in Javascrip or JS? if so, how?
In my example: I'm inserting the name, last name and email and retrieving the country.
Thank you very much
<!DOCTYPE HTML>
<html>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $surnameErr = $AddressErr = "";
$name = $email = $surname = $address = "";
<select name="countryselect" id="countryselect">
<?php
$db = pg_connect('host=localhost dbname=test user=myuser password=mypass');
$query = "SELECT country FROM countries";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
printf ("<option value=Select>Select a Country</option>");
while($myrow = pg_fetch_assoc($result)) {
printf ("<option value=$myrow[country]>$myrow[country]</option>");
}
?>
</select>
<input type="submit" name="submit" value="SAVE">
</form>
<?php
if ($nameErr == '' && $emailErr == '' && $surnameErr == '')
{
$db = pg_connect('host=localhost dbname=test user=myuser password=mypass');
$firstname = pg_escape_string($_POST['name']);
$surname = pg_escape_string($_POST['surname']);
$emailaddress = pg_escape_string($_POST['email']);
$query = "INSERT INTO host(firstname, surname, emailaddress) VALUES('" . $firstname . "', '" . $surname . "', '" . $emailaddress . "')";
$result = pg_query($db, $query);
if (!$result) {
$errormessage = pg_last_error();
echo "Error with query: " . $errormessage;
exit();
}
//printf ("These values were inserted into the database - %s %s %s", $firstname, $surname, $emailaddress);
pg_close();
}
?>
</body>
</html>

how to fetch data from sql using form $_Post id in where clause

I am using a form with javascript which is used to add n numbers of rows dynamical and post data to mysql.
now i want to post more information to mysql using where clause (form data) in sql statement.
This is my code to submit and post data.
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var addDiv = $('#addinput');
var i = $('#addinput p').size() + 1;
$('#addNew').live('click', function() {
$('<p><select name="stockid[]' + i +'" onchange="showUser(this.value)"> <?php echo $item; ?></select> <select name="desc[]' + i +'" id="txtHint"> <?php echo $description; ?></ </select>Remove </p>').appendTo(addDiv);
i++;
return false;
});
$('#remNew').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
</script>
<body>
<?php if (!isset($_POST['submit_val'])) { ?>
<h1>Add your Hobbies</h1>
<form method="post" action="">
<div id="container">
<p id="addNew"><span>Add New</span></p>
<div id="addinput">
<input type="submit" name="submit_val" value="Submit" />
</form>
<?php } ?>
<?php
?>
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
foreach($stockid as $a => $B)
{
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description) VALUES ('$stockid[$a]','$desc[$a]')", $connection );
}
echo "<i><h2><strong>" . count($_POST['stockid']) . "</strong> Hobbies Added</h2></i>";
}
?>
its working fine now when am trying to use a select statement and post data to mysql its not working
here is code
<?php
$con=mysqli_connect("localhost","root","","inventory");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
{
echo $row['price'];
}
mysqli_close($con);
?>
then i modify the post code of above file like this
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
$price = $row['price'];
foreach($stockid as $a => $B)
{
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection);
}
echo "<i><h2><strong>" . count($_POST['stockid']) . "</strong> Hobbies Added</h2></i>";
}
?>
but nothing is inserted in to database in price column
Change your code to store the price value in a new variable:-
<?php
$con=mysqli_connect("localhost","root","","inventory");
$price = array(); //declare
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
{
echo $row['price'];
$price = $row['price']; //initiate
}
mysqli_close($con);
?>
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid','$desc','$price')", $connection);
}
?>
Your $row['price'] variable will only exist within the while loop so you have to store it in something that is present beforehand and use that variable instead.
Assuming that both code snippets are in the same file, that is. Take a look over the code and see the changes on line 3 and line 27.
Also, as the other guys have said remove the double $$ and just use one on this line:-
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
Hope this is of some help to you :)
As said by aconrad in comments, replacing $$_POST by $_POST would probably solve your problem.
But I suggest you to change mysqli_query() to mysqli_prepare (and to change all mysql_* by the equivalent mysqli_* function)
I suggest you to transform all into mysqli_ and use prepared statements instead of direct query like this :
Change this:
<?php
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
to this:
<?php
$stmt = mysqli_prepare($con,"SELECT price FROM 0_stock_master where id = ?");
mysqli_stmt_bind_param($stmt, 'i', $_POST['stockid']);
$result = mysqli_stmt_execute($stmt);
if (!$result)
echo 'Mysql error : '.mysqli_stmt_error($stmt);
mysqli_stmt_bind_result($stmt, $price); // values will
mysqli_stmt_fetch($stmt); // this call send the result in $price
mysqli_stmt_close($stmt);
Change this:
<?php
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection );
to this :
<?php
$stmt = mysqli_prepare($connection, "INSERT INTO 0_stock_master (stock_id,description,price) VALUES (?, ?, ?)");
// I assume stock_id must be int, desc must be string, and price must be float
mysqli_stmt_bind_param($stmt, 'isf', $stockid[$a],$desc[$a],$price[$a]);
$query = mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
EDIT :
Some documentation:
MySQLi
mysqli_prepare (sql queries more protected from sql injection)
mysqli_stmt_bind_param
mysqli_stmt_execute
mysqli_stmt_bind_result
mysqli_stmt_fetch

Categories

Resources