i searched all over the web and i couldn't find an answer, please help me!.
I have an HTML form, like this one:
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="text" name="folder_name" placeholder="Folder name">
<input type="submit" value="Submit">
</form>
Now, upload.php takes number of images and store a link to the folder in MySQL.
Then i call query.php through angularJS $http to retrieve the link to the folder + the images.
Here is query.php:
session_start();
include 'connection.php';
header("Content-Type: application/json; charset=UTF-8");
$folder = $_SESSION["target_folder"];
$query = "SELECT * FROM links WHERE link LIKE '%$folder%'";
$stmt = $db->prepare($query);
$stmt->execute();
$imagesArray = [];
$images = [];
$response = "";
$imageArray = "";
$first_response = "";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$images = unserialize($row["images"]);
$imagesArray = explode(",", $images);
foreach($imagesArray as $image) {
if ($response != "") {$response .= ",";}
$response .= '{"target_folder":"' . $row["link"] . '",';
//$response .= '"ext":"' . $row["ext"] . '",';
$response .= '"billboardNumber":"' . $image . '"}';
}
}
$response ='{"records":['.$response.']}';
echo $response;
Last is the slider in slider.html that retrieves the JSON data from query.php:
$http.get("php/query.php")
.success(function (response) {
$scope.slides = response.records;
});
Most important part, my question :-)
every time i run slider.html it overwrites the old slider.html link and outputs the images from the last JSON call.
how can i run slider.html for a month and still get to the same folder even if i generate another 1000 links to different folder.
i hope that someone will understand me :-)
thank you !!!
Related
I am getting a [$http:baddata] error when my Angular app calls my php file.
I'm not sure where the error is triggering exactly, but I believe it's a problem constructing the json object! I've attached all relevant code. Any help would be amazing. Thanks in advance :)
Angular documentation shows this
This is the PHP file which connects to my database and attempts to return a JSON formatting string back to the calling file
<?php
echo '<script>console.log("Inside php file!")</script>';
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once('mysqli_connect.php');
$query = "SELECT rideid, destination, price, capacity, userid, origin, departDate, vehicle FROM rides";
$result = #mysqli_query($dbc, $query);
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {$outp .= ",";}
$outp .= '{"Origin":"' . $rs["origin"] . '",';
$outp .= '"Destination":"' . $rs["destination"] . '",';
$outp .= '"Price":"'. $rs["price"] . '"}';
$outp .= '"Capacity":"'. $rs["capacity"] . '"}';
}
$outp ='{"records":['.$outp.']}';
//echo '<script>console.log(JSON.stringify('.$outp.'))</script>';
$conn->close();
echo($outp);
This is the Angular app making the request to the PHP file
<html>
<head>
<!-- Include Angular -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
</head>
<body>
<!-- Ride Table -->
<div ng-app = "rideAppTest" ng-controller= "rideCtrlTest">
<table>
<tr ng-repeat = "x in names">
<td>{{x.Origin}}</td>
<td>{{x.Destination}}</td>
<td>{{x.Price}}</td>
<td>{{x.Capacity}}</td>
</tr>
</table>
</div>
<!-- End Ride Table -->
<!--Ride Table Script-->
<script>
var app = angular.module('rideAppTest', []);
app.controller('rideCtrlTest', function($scope, $http) {
$http.get("angularFilter.php")
.then(
function (response) {
$scope.names = response.data.records;
},
function(data){
console.log("Error!" + data);
}
);
});
</script>
</body>
</html>
Don't construct the JSON the way you are doing, first collect everything inside an array or an object then do echo json_encode($result);
Something like this:
$outp = [];
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
$outp[] = $rs;
}
echo json_encode(["records" => $outp]);
Thank to #Madhav for the help. This is what ended up working for me :)
while($rs = mysqli_fetch_array($result)) {
$myArray[] = array(
'Origin' => $rs["origin"],
'Destination' => $rs["origin"],
'Price' => $rs["price"],
'Capacity' => $rs["capacity"]
);
}
echo json_encode(["records" => $myArray]);
I am having issues displaying image on the website i am developing. It a website that users can change their profile picture, as well as their basic profile information. bellow is my sample code.
profile.php
<?php
$studpix=$row_rsp['pix'];
$propix='<img class=
"profile-user-img img-responsive img-circle" src="...
/Student /imageupload/blank.png"
alt="profile picture">';
if($propix!=NULL)
{
$propix='<img class="profile-user-img
img-responsive img-circle" src="Student/imageupload/'.$studpix.'"
alt="profile picture">';
};
$profile_pic_btn =
' Profile pics';
$avatar_form = '<form id="avatar_form"
enctype="multipart/form-data" method="post" action="photoup.php">';
$avatar_form .= '<h4>Change your picture</h4>';
$avatar_form .= '<input type="file" name="avatar" required>';
$avatar_form .= '<p><input type="submit" value="Upload"></p>';
$avatar_form .= '</form>';
?>
<?php echo $propix?><?
php echo $avatar_form?><?php echo $profile_pic_btn;?>
//other codes goes here
imageupload.php
<?php
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]
["tmp_name"] != ""){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10){
echo "ERROR: That image has no dimensions";
exit();
}
$db_file_name = rand(100000000000,999999999999).".".$fileExt;
if($fileSize > 1048576) {
echo "ERROR: Your image file was larger than 1mb";
exit();
} else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) {
echo "ERROR: Your image file was not jpg, gif or png type";
exit();
} else if ($fileErrorMsg == 1) {
echo "ERROR: An unknown error occurred";
exit();
}
$sql = "SELECT pix FROM studentdetails WHERE email='%s'";
$query = mysqli_query($myconn, $sql);
$row = mysqli_fetch_row($query);
$avatar = $row[0];
if($avatar != ""){
$picurl = "../Student/imageupload/$avatar";
if (file_exists($picurl)) { unlink($picurl); }
}
$moveResult = move_uploaded_file(
$fileTmpLoc, "../Student /imageupload /$db_file_name");
if ($moveResult != true) {
echo "ERROR: File upload failed";
exit();
}
include_once("../image_resize.php");
$target_file = "../Student/imageupload/$db_file_name";
$resized_file = "../Student/imageupload/$db_file_name";
$wmax = 200;
$hmax = 300;
img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
$sql = "UPDATE studendetails SET pix='%s' WHERE email='%s' LIMIT 1";
$query = mysqli_query($myconn, $sql);
mysqli_close($myconn);
header("location: profile.php");
exit();
}
?>
Your help will be appreciated.
Try to debug your code step by step.
1. Check whether the file gets uploaded correctly and to the correct folder.
2. Check whether the data is updated correctly in the database.
3. Try to open the file by URL directly in the browser.
4. Check whether your HTML code is outputted correctly on the webpage and debug the outputted source code.
5. Make sure that your HTML code works properly.
There may be more steps to take, but this might give you some direction.
i've successfully uploaded my image into folder and successfully saved my path into database now as i tried to show pic into browser it's showing error:
Warning: mysql_query() expects parameter 2 to be resource, object given in C:\Users\Raj\PhpstormProjects\image\upload_file.php on line 6
Warning: mysql_num_rows() expects parameter 1 to be resource, null given in C:\Users\Raj\PhpstormProjects\image\upload_file.php on line 7
File name not found in database
here is my code for form:
<?php
// Assigning value about your server to variables for database connection
$hostname_connect= "localhost";
$database_connect= "photo";
$username_connect= "root";
$password_connect= "Bhawanku";
$connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR);
#mysql_select_db($database_connect) or die (mysql_error());
if($_POST)
{
// $_FILES["file"]["error"] is HTTP File Upload variables $_FILES["file"] "file" is the name of input field you have in form tag.
if ($_FILES["file"]["error"] > 0)
{
// if there is error in file uploading
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
// check if file already exit in "images" folder.
if (file_exists("images/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{ //move_uploaded_file function will upload your image. if you want to resize image before uploading see this link http://b2atutorials.blogspot.com/2013/06/how-to-upload-and-resize-image-for.html
if(move_uploaded_file($_FILES["file"]["tmp_name"],"images/" . $_FILES["file"]["name"]))
{
// If file has uploaded successfully, store its name in data base
$query_image = "insert into acc_images (image, status, acc_id) values ('".$_FILES['file']['name']."', 'display','')";
if(mysql_query($query_image))
{
echo "Stored in: " . "images/" . $_FILES["file"]["name"];
}
else
{
echo 'File name not stored in database';
}
}
}
}
}
?>
<html>
<body>
<form action="upload_file.php" method="post"enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
and here is my code for showing pics:
<?php
$con=mysqli_connect("localhost","root","Bhawanku","photo");
// Check connection
$query_image = "SELECT * FROM acc_images";
// This query will show you all images if you want to see only one image pass acc_id='$id' e.g. "SELECT * FROM acc_images acc_id='$id'".
$result = mysql_query($query_image, $con);
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result))
{
echo '<img alt="" src="images/'.$row["image"].'">';
}
}
else
{
echo 'File name not found in database';
}
?>
In the second script, you're connecting as mysqli but then using mysql_query, mysql_num_rows and mysql_fetch_array. MySQLi and MySQL aren't interchangeable.
$result = mysqli_query($query_image, $con);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
echo '<img alt="" src="images/'.$row["image"].'">';
}
}
else
{
echo 'File name not found in database';
}
You should consider changing the first script to MySQLi too, and use prepared statements instead of concatenating variables into the query.
In first row you use mysqli extension, but in all other - mysql.
Try to change:
<?php
$con=mysql_connect("localhost","root","Bhawanku");
mysql_select_db("photo", $con);
// Check connection
$query_image = "SELECT * FROM acc_images";
// This query will show you all images if you want to see only one image pass acc_id='$id' e.g. "SELECT * FROM acc_images acc_id='$id'".
$result = mysql_query($query_image, $con);
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result))
{
echo '<img alt="" src="images/'.$row["image"].'">';
}
}
else
{
echo 'File name not found in database';
}
?>
I have a list of products on my website a Catalogue. The following PHP Code uses javascript to create a div and insert all the product description links inside it.
$sql = "SELECT * from Products ORDER BY `Name` ASC";
$result = mysqli_query($con, $sql);
echo "<script>document.getElementById('products').innerHTML = '<div class=ks>';</script>";
while($row = mysqli_fetch_assoc($result))
{
$rowid = $row['Id'];
$xx = '<a href="Getdesc.php?hid='.$rowid . '" class=lnk>' . $row['Name'] . '</a><br>';
echo "<script>document.getElementById('products').innerHTML += '$xx';</script>";
}
echo "<script>document.getElementById('products').innerHTML += '</div>';</script>";
Ignore all the ks style sheet class and all the mysql stuff for now.
The problem is it displays the grey backgrounded div (grey from style sheet)
and THEN the links. I need the links to be inside the div.
For a little explanation for those of you who are confused by the pieces of code unrelated to the primary purpose of this question,
The Products table in MySQL is a table that hold all my product info including price, name, id, e.t.c.
the "Getdesc.php?hid=..." link is a link to a php web page that will display all the information about the product from it's Id.
"Products" is an Id of a different div that contains this internal div (With the products I mean) PLUS some other stuff ( I don't feel like telling you all about it).
Sorry for the messy code, thanks in advance.
Javascript:
//from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
function reqListener () {
document.getElementById('products').innerHTML = this.responseText;
}
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "yourFile.php", true);
oReq.send();
PHP
$sql = "SELECT <columns> from Products ORDER BY `Name` ASC";
$result = mysqli_query($con, $sql);
echo '<div class="ks">';
while($row = mysqli_fetch_assoc($result))
{
$rowid = $row['Id'];
echo '' . htmlspecialchars($row['Name']) . '<br>';
}
echo '</div>'
why not put everything in a variable :
$html = '<div class="ks">'; // btw you forgot those double-quotes. you html won't evaluate the class if not surrounded by double-quotes
while($row = mysqli_fetch_assoc($result))
{
$rowid = $row['Id'];
$xx = '<a href="Getdesc.php?hid='.$rowid . '" class=lnk>' . $row['Name'] . '</a><br>';
$html.= $xx;
}
$html.= '</div>';
then echo it? if you're using php, then there's no need to change the page with javascript after it's been loaded, you just sent all the remainder of the page to the client, why not directly put this code at the right place?
echo $html;
Any ideas on Exporting HTML5 Form data to CSV please?
I can only use HTML5 or Javascript or both.
Thanks
You could just display the form data in CSV format in the browser (maybe in a popup) and have the user do a File -> Save Page (assuming it doesn't have to be fully automated).
OK, this is what I'm going to have to do: 1. If there IS internet connection ... then save the data to MySQL Table. 2. Using PHP run a script on the MySQL DB to export the data to CSV.
I'll use something like this for example:
<?php
$host = 'localhost';
$user = 'mysqlUser';
$pass = 'myUserPass';
$db = 'myDatabase';
$table = 'products_info';
$file = 'export';
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field']."; ";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j]."; ";
}
$csv_output .= "\n";
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
?>