PHP - Dynamic Image And Data Upload Simultaneously
Ok so I have a form to submits to a .php file that creates an image. This works fine, but I also want the info from the form to be sent to MySQL database. The problem is that something in a script I "required" called core.inc.php is interfering and so no image is output. Here is core.inc.php: Code: [Select]
<?php ob_start(); session_start(); $current_file = $_SERVER['SCRIPT_NAME']; if(isset($_SERVER['HTTP_REFERER'])&&!empty($_SERVER['HTTP_REFERER'])) { $http_referer = $_SERVER['HTTP_REFERER']; } function loggedin() { if(isset($_SESSION['user_id'])&&!empty($_SESSION['user_id'])) { return true; } else { return false; } } function getuserfield($field) { $query="SELECT `$field` FROM `Users` WHERE `id`='".$_SESSION['user_id']."'"; if($query_run=mysql_query($query)) { if($query_result = mysql_result($query_run, 0, $field)) { return $query_result; } } } ?> Here is the code for the image creating .php file: Code: [Select] <?php require 'connect.inc.php'; require 'core.inc.php'; $title = $_REQUEST['title'] ; $user_id = getuserfield('id'); $query = "INSERT INTO `---` VALUES ('".mysql_real_escape_string($title)."','".mysql_real_escape_string($user_id)."')"; $query_run = mysql_query($query); //There is some more code in here obviously, but it's irrelevant header('Content-type: image/png'); imagepng($image_f); imagedestroy($image_f) Can anybody give me some idea of what is conflicting or what I can do to fix it? Similar TutorialsI wonder whether someone may be able to help me please. I've put together the following script which saves user defined images to server folders using the Aurigma Image Uploader software. Code: [Select] <?php require_once 'Includes/gallery_helper.php'; require_once 'ImageUploaderPHP/UploadHandler.class.php'; $galleryPath = 'UploadedFiles/'; function onFileUploaded($uploadedFile) { global $galleryPath; $packageFields = $uploadedFile->getPackage()->getPackageFields(); $username=$packageFields["username"]; $locationid=$packageFields["locationid"]; $usernamefolder = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $_POST['username']); $locationfolder = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $_POST['locationid']); $dirName = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $_POST['folder']); $absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR . $usernamefolder . DIRECTORY_SEPARATOR . $locationfolder . DIRECTORY_SEPARATOR; $absThumbnailsPath = $absGalleryPath . 'Thumbnails' . DIRECTORY_SEPARATOR; if (!is_dir($absGalleryPath)) mkdir($absGalleryPath, 0777, true); chmod($absGalleryPath, 0777); if (!is_dir($absGalleryPath . $dirName)) mkdir($absGalleryPath . $dirName, 0777, true); chmod($absGalleryPath . $dirName, 0777); if ($uploadedFile->getPackage()->getPackageIndex() == 0 && $uploadedFile->getIndex() == 0) initGallery($absGalleryPath, $absThumbnailsPath, FALSE); $originalFileName = $uploadedFile->getSourceName(); $files = $uploadedFile->getConvertedFiles(); $sourceFileName = getSafeFileName($absGalleryPath, $originalFileName); $sourceFile = $files[0]; if ($sourceFile) $sourceFile->moveTo($absGalleryPath . $sourceFileName); $thumbnailFileName = getSafeFileName($absThumbnailsPath, $originalFileName); $thumbnailFile = $files[1]; if ($thumbnailFile) $thumbnailFile->moveTo($absThumbnailsPath . $thumbnailFileName); $descriptions = new DOMDocument('1.0', 'utf-8'); $descriptions->load($absGalleryPath . 'files.xml'); $xmlFile = $descriptions->createElement('file'); // <-- please check the following line $xmlFile->setAttribute('name', $_POST['folder'] . '/' . $originalFileName); $xmlFile->setAttribute('source', $sourceFileName); $xmlFile->setAttribute('size', $uploadedFile->getSourceSize()); $xmlFile->setAttribute('originalname', $originalFileName); $xmlFile->setAttribute('thumbnail', $thumbnailFileName); $xmlFile->setAttribute('description', $uploadedFile->getDescription()); $xmlFile->setAttribute('username', $username); $xmlFile->setAttribute('locationid', $locationid); $xmlFile->setAttribute('folder', $dirName); $descriptions->documentElement->appendChild($xmlFile); $descriptions->save($absGalleryPath . 'files.xml'); } $uh = new UploadHandler(); $uh->setFileUploadedCallback('onFileUploaded'); $uh->processRequest(); ?> This code saves the files in the following structu UploadedFiles (Pre-existing folder) 'username' (Subfolder created dynamically on image upload if it doesn't already exist. This folder contains the 'location' folder) 'location' (Subfolder created dynamically on image upload if it doesn't already exist. This contains original image, 'files.xml' and 'Thumbnails' folder) 'Thumbnails' (Subfolder created dynamically on image upload if it doesn't already exist. This contains thumbnail of original image) I'm now trying to put together a script which creates an image gallery, with those images pertinent to the current user and location. The code below is the piece of my script which deals with the loading of the images. Code: [Select] <?php $galleryPath = 'UploadedFiles/'; $thumbnailsPath = $galleryPath . 'Thumbnails/'; $absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR; $descriptions = new DOMDocument('1.0'); $descriptions->load($absGalleryPath . 'files.xml'); ?> The initial problem I had, was resolved from guidance I received on this site, and that was to find the correct 'realpath' of the 'Thumbnails' folder and 'files.xml' These are as follows: Quote /homepages/2/d333603417/htdocs/development/UploadedFiles/IRHM73/1 and Quote /homepages/2/d333603417/htdocs/development/UploadedFiles/IRHM73/1/Thumbnails with 'IRHM73' being the 'username' value and '1' the 'location' value. The problem I now have lies within this line of code: `$absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR;` Because the 'username' and 'location' are dynamic and hence contain different values for each user and location, I've found it impossible to find a way of creating the correct file path to open the 'Thumbnails' folder and 'files.xml'. I had tried this: Code: [Select] <?php $galleryPath = 'UploadedFiles/'; $absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR . $usernamefolder . DIRECTORY_SEPARATOR . $locationfolder . DIRECTORY_SEPARATOR; $absThumbnailsPath = $absGalleryPath . 'Thumbnails' . DIRECTORY_SEPARATOR; $descriptions = new DOMDocument('1.0'); $descriptions->load($absGalleryPath . 'files.xml'); ?> But I receive the following error: DOMDocument::load() domdocument.load: I/O warning : failed to load external entity /homepages/2/d333603417/htdocs/development/UploadedFiles/'files.xml'; in /homepages/2/d333603417/htdocs/development/gallery.php on line 13 and line 13 is this: Code: [Select] $descriptions->load($absGalleryPath . 'files.xml'); I really am stumped with what to do next to get this to work. I appreciate that this is a fairly lengthy post, but thought it would be better to post all the information. I just wondered whether someone could perhaps take a look at this and let me know where I'm going wrong and how I can get it to work. Many thanks and regards so what i have going on is that i need help writing a basic script to upload original and copy with resize for thumbnail. then also need to rename both image files with content in the form. My server supports GD Library and that imagemagik or whatever it is lol. upload dirs orig: ../media/photos/ thumb: ../media/photos/thumb/ mySQL DB: name: m_photos fields: id(INT) m_cat(varchar) m_sub_cat(varchar) pic(varchar) description(varchar) p_group(varchar) I have the form written up for how it should look like: Code: [Select] <form action="upload.php" method="post" enctype="multipart/form-data"> Upload an image for processing<br /> <input type="file" name="Image"><br /> <select name="sub_group"> <option value="Photo Shoot">Photo Shoot</option> <option value="Live Performances">Live Performances</option> <option value="Randoms">Randoms</option> <option value="Fan Photos">Fan Photos</option> </select><br /> Location: <input type="text" name="p_group" /><br /> Date of Pic: <input type="text" name="date" /><br /> Description: <input type="text" name="description" /><br /> <input type="submit" value="Upload"> </form> so what needs to happen is for the file upload name. it needs to grab a count from "p_group" database to give it a starting number in a "00" pattern and then the date of pic needs to go in there next then the p_group name. so when the files gets uploaded it would look something like this after upload. "03 - Oct 21, 2011 - The Mex.jpg" NOTE: all pics must be converted to ".jpg" extension. both the orig and thumb will use that same file name cuz they just go into different dirs re-sizing for the thumbnail should be done by aspect ratio and needs to either be 300px width or 400px height. so if anyone would like to help me out please do. im not the greatest at writing in php yet Folks, I need help (Php code ) to generate a Dynamic Text on a Base Image. What i want to do is, to make this Image as header on my Site and to make this Header Specific to a Site, i want to Add the Domain Name on the Lower Left of the Image. Got the Idea? Here is the Image link: Quote http://img27.imageshack.us/i/shoppingheader1.jpg/ PHP Variable that holds the Domain name is: $domain All i need the Dynamic PHP Codes that i can put on all my sites to generate this Text on Image (Header) Dynamically... May Anyone Help me with this Please? Cheers Natasha T. How can i edit just one image at on time with a multiple image upload form? I have the images being stored in a folder and the path being stored in MySQL. I also have the files being uploaded with a unique id. My issue is that I want to be able to pass the values of what is already in $name2 $name3 $name4 if I only want to edit $name1. I don't want to have to manually update the 4 images. Here is the PHP: Code: [Select] <?php require_once('storescripts/connect.php'); mysql_select_db($database_phpimage,$phpimage); $uploadDir = 'upload/'; if(isset($_POST['upload'])) { foreach ($_FILES as $file) { $fileName = $file['name']; $tmpName = $file['tmp_name']; $fileSize = $file['size']; $fileType = $file['type']; if ($fileName != ""){ $filePath = $uploadDir; $fileName = str_replace(" ", "_", $fileName); //Split the name into the base name and extension $pathInfo = pathinfo($fileName); $fileName_base = $pathInfo['fileName']; $fileName_ext = $pathInfo['extension']; //now we re-assemble the file name, sticking the output of uniqid into it //and keep doing this in a loop until we generate a name that //does not already exist (most likely we will get that first try) do { $fileName = $fileName_base . uniqid() . '.' . $fileName_ext; } while (file_exists($filePath.$fileName)); $file_names [] = $fileName; $result = move_uploaded_file($tmpName, $filePath.$fileName); } if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); $filePath = addslashes($filePath); } $fileinsert[] = $filePath; } } $mid = mysql_real_escape_string(trim($_POST['mid'])); $cat = mysql_real_escape_string(trim($_POST['cat'])); $item = mysql_real_escape_string(trim($_POST['item'])); $price = mysql_real_escape_string(trim($_POST['price'])); $about = mysql_real_escape_string(trim($_POST['about'])); $fields = array(); $values = array(); $updateVals = array(); for($i = 0; $i < 4; $i++) { $values[$i] = isset($file_names[$i]) ? mysql_real_escape_string($file_names[$i]) : ''; if($values[$i] != '') { $updateVals[] = 'name' . ($i + 1) . " = '{$values[$i]}'"; } } $updateNames = ''; if(count($updateVals)) { $updateNames = ", " . implode(', ', $updateVals); } $update = "INSERT INTO image (mid, cid, item, price, about, name1, name2, name3, name4) VALUES ('$mid', '$cat', '$item', '$price', '$about', '$values[0]', '$values[1]', '$values[2]', '$values[3]') ON DUPLICATE KEY UPDATE cid = '$cat', item = '$item', price = '$price', about = '$about' $updateNames"; $result = mysql_query($update) or die (mysql_error()); Hello. If someone can help me, i'll be grateful So i have a foreach and an $output .= function that fills some infos in a table. Inside it i have a div for each line that when hovering your mouse should get some data .. Here i have a big problem, because for each line it should get some data and i don't know how to do it ... i'll post here some of my code for better understanding. Quote //some java here <?php require "class.php"; $server_list = query_group(); $misc = server_misc($server); foreach ($server_list as $server) { $misc = server_misc($server); $server = server_html($server); $idi = "{$server['o']['id']}"; $harta = "<a onmouseover=\"ShowContent('harta'); return true;\" onmouseout=\"HideContent('harta'); return true;\" href='".link($server['o']['id'])."' target=\"_self\">{$server['s']['map']}</a> <div style=\"position:absolute;\" id=\"harta\" class=\"FAQ\">file_get_contents('http://mysite/player.php?d={$idi}')</div> "; $output .= " <table> ........... some code..... <td> {$harta} </td> ....... so basicly when i hover my mouse over each row it should get data from the file for that id... The problem is that only one page can be loaded with file_get_contents. I read over the internet that some ajax functions can do it but i really don't know how. Please help me, i've been looking for 3 days already without any luck Hello, I had page that display results dynamically from the database, I need to export that html table to pdf. Any help? Thanks Hello I am having problems uploading an image through a HTML form. I want the image to be uploaded to the server and the image name to be written to the mysql database. Below is the code I am using: Code: [Select] <?php if (isset($_POST['add'])){ echo "<br /> add value is true"; $name = $_POST['name']; $description = $_POST['description']; $price = $_POST['price']; $category_id = $_POST['category_name']; $image = $_FILES['image']['name']; //file path of the image upload $filepath = "../images/"; //mew name for the image upload $newimagename = $name; //new width for the image $newwidth = 100; //new height for the image $newheight = 100; include('../includes/image-upload.php'); mysql_query("INSERT INTO item (item_name, item_description, item_price, item_image) VALUES ('$name','$description','$price','$image')"); ?> Here is the image-upload.php file code: Code: [Select] <?php //assigns the file to the image $image =$_FILES["image"]["name"]; $uploadedfile =$_FILES["image"]["tmp_name"]; if ($image) { //retrieves the extension type from image upload $extension = getextension($image); //converts extension to lowercase $extension = strtolower($extension); //create image from uploaded file type if($extension=="jpg" || $extension=="jpeg") { $uploadedfile = $_FILES['image']['tmp_name']; $src = imagecreatefromjpeg($uploadedfile); }else if($extension=="png") { $uploadedfile = $_FILES['image']['tmp_name']; $src = imagecreatefrompng($uploadedfile); }else{ $src = imagecreatefromgif($uploadedfile); } //creates a list of the width and height of the image list($width,$height)=getimagesize($uploadedfile); //adds color to the image $tmp = imagecreatetruecolor($newwidth,$newheight); //create image imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height); //set file name $filename = $filepath.$newimagename.".".$extension; $imagename = $newimagename.".".$extension; //uploads new file with name to the chosen directory imagejpeg($tmp,$filename,100); //empty variables imagedestroy($src); imagedestroy($tmp); } ?> Any help would be appreciated, fairly new to all this! Thanks!!! Hey guys, I got another one that i could use some help on. I have a input form that utilizes a javascript that adds additional rows to my table. here is a look at what i got. Code: [Select] <script type="text/javascript"> function insertRow() { var x = document.getElementById('results_table').insertRow(-1); var a = x.insertCell(0); var b = x.insertCell(1); var c = x.insertCell(2); var d = x.insertCell(3); var e = x.insertCell(4); a.innerHTML="<input type=\"text\" name=\"id\">"; b.innerHTML="<input type=\"text\" name=\"place\">"; c.innerHTML="<input type=\"text\" name=\"username\">"; d.innerHTML="<input type=\"text\" name=\"earnings\">"; e.innerHTML="<input type=\"button\" value=\"delete\" onClick=\"deleteRow(this)\">"; } function deleteRow(r) { var i=r.parentNode.parentNode.rowIndex; document.getElementById('results_table').deleteRow(i); } </script> this is my code stored in the header of my page. basically just a button to add a new row and a button in each row to delete rows if needed. here is a look at my html table, pretty basic... Code: [Select] <table id="results_table"> <th>Event ID</th><th>Place</th><th>Username</th><th>Earnings</th> <tr> <td><input type="text" name="id"></td><td><input type="text" name="place"></td><td><input type="text" name="username"></td><td><input type="text" name="earnings"></td><td><input type="button" value="delete" onClick="deleteRow(this)"</td> </tr> </table> Now what I am hoping to acheive is once i submit all of these rows to the database i will insert each of these rows into their own row in the database. is this doable? the structure of my database is: ResultID (Primary Key) Place Earnings UserID (Foreign Key) EventID (Foreign Key) now i think the biggest problem i'm having with submitting data to the database is that in the original HTML form I am typing in the actual username and not the userID. so when it comes to processing I need to do a switch of these two things before I run my query. Should something like this work? Code: [Select] $username = $_POST['username']; $userID = "SELECT userID FROM users WHERE username="$username"; $query = mysql_query($userID); also i've never tried to submit multiple entries at a time. maybe i have to create an array somehow in order to capture each rows data. any thoughts? as always thanks for the help. Hi, I have a dynamic form which uses javascript to add rows on the fly. The name of the element on my test page is txtRow1, txtRow2, etc; the number is added when I add a new row. I am trying to figure out how I will extract the data once the form had been POSTED. I have tried Code: [Select] $tags = $_POST['txtRow']; foreach ($tags as $t) { echo "$t<br />"; } but that shows nothing. I would be grateful for any assistance. Thanks Hi - I'm trying to speed up part of my business. I sell photos taken on site...I dump said photos in a directory and my little app pulls all images from a given directory and displays them on a page. I can get the filename etc displayed on screen, added to the image attributes, whatever. I'd like to have a checkbox next to each image, and the user checks a few and it'll send an email to me so I can fill their order. Looks like this: http://www.limitedwave.com/reflex/ I can use a sendmail like I've tried, but it can take like 10 minutes to actually send from the server which is lame. I'd be cool with just dropping the data in my database, then retrieving selections by user's name, but I don't know how to set up a form/insert page that will insert from a somewhat random set of checkboxes. Thoughts? Thanks. please help me the concept or code to retrive data from the database and display data according to the data from the dynamic list box option. After searching postings on multiple forums, I am officially now "Freaking OUT" trying to understand something that is probably very simple, but cannot seem to grasp. I simply want to read basic .csv data that is sent/uploaded directly to a PHP page, and to then append each record that shows up to a single .csv file on the server. The incoming data is supposed incoming via $_POST['csv'] ... at least that's what I was told. Each.csv record line being sent/uploaded is very simple (either single or multiple records in one small file): text1,text2,text3,text4,text5 For additional processing I know about 'explode', etc., but right now I am stuck even trying to do an 'echo' to display the simple incoming data "as is". One option I tried was: $postdata = file_get_contents("php://input"); echo $postdata; In the Java App monitoring I get the following after 3 records are sent/uploaded to the PHP URL: Server response status line: HTTP/1.1 200 OK I find this strange since I did not include... http_response_code(200); ... in the page code. Obviously, I do NOT know what I am doing here {SIGH}. Any assistance or guidance is appreciated. Thank you ! - FreakingOUT
im making a game and i need to show a users money but i dont know how help? Hi all new to php and this forum i have been looking around and im very impressed most questions get answered not like on some of the forums around.
Is there any one kind enough to help me out i have an api call via php and would like to output the results to owlcarousel where do i start with this.
Code i have is:
<?php error_reporting(E_ALL); // Turn on all errors, warnings and notices for easier debugging // API request variables $endpoint = 'http://svcs.ebay.com/services/search/FindingService/v1'; // URL to call $version = '1.0.0'; // API version supported by your application $appid = 'YourAppID'; // Replace with your own AppID $globalid = 'EBAY-GB'; // Global ID of the eBay site you want to search (e.g., EBAY-DE) $query = 'tools'; // You may want to supply your own query $safequery = urlencode($query); // Make the query URL-friendly // Construct the findItemsByKeywords HTTP GET call $apicall = "$endpoint?"; $apicall .= "OPERATION-NAME=findItemsIneBayStores"; $apicall .= "&SERVICE-VERSION=$version"; $apicall .= "&SECURITY-APPNAME=$appid"; $apicall .= "&GLOBAL-ID=$globalid"; $apicall .= "&keywords=$safequery"; $apicall .= "&storeName=yourstorename"; $apicall .= "&paginationInput.entriesPerPage=6"; $apicall .= "&paginationInput.pageNumber=1"; // Load the call and capture the document returned by eBay API $resp = simplexml_load_file($apicall); // Check to see if the request was successful, else print an error if ($resp->ack == "Success") { $results = ''; // If the response was loaded, parse it and build links foreach ($resp->searchResult->item as $item) { $pic = $item->galleryURL; $link = $item->viewItemURL; $title = $item->title; $price = $item->currentPrice; // For each SearchResultItem node, build a link and append it to $results $results .= "<div id='item'><div class='img-wrap' align='center'><img src=\"$pic\" class='itemimg'></div> <div class='itemtxt' align='center'><a href=\"$link\">$title</a>$price</div></div>"; } } // If the response does not indicate 'Success,' print an error else { $results = "<h3>Oops! The request was not successful. Make sure you are using a valid "; $results .= "AppID for the Production environment.</h3>"; } ?> <html> <head> <body> <table> <tr> <td> <div id="result"> <?php echo $results;?> </div> </td> </tr> </table> </body> </html>Im sure is pretty basic but being new to this i have no idea where to start, any advice would be much appreciated. thanks Edited by didz666, 25 January 2015 - 02:22 PM. i've to populate google charts with dynamic data. the data looks llike. +----+-------+---------+-------+-----------+---------+------+ | id | name | physics | maths | chemistry | biology | sst | +----+-------+---------+-------+-----------+---------+------+ | 1 | Name1 | 10 | 25 | 35 | 42 | 62 | | 2 | Name2 | 80 | 45 | 45 | 45 | 25 | | 3 | Name3 | 63 | 25 | 63 | 36 | 36 | | 4 | Name4 | 82 | 36 | 75 | 48 | 42 | | 5 | Name5 | 45 | 45 | 78 | 25 | 24 | | 6 | Name6 | 36 | 36 | 15 | 75 | 36 | | 7 | Name7 | 99 | 45 | 24 | 24 | 45 | | 8 | Name8 | 45 | 85 | 85 | 85 | 96 | +----+-------+---------+-------+-----------+---------+------+ i have to create google charts based on this such that # namewise - such that when i select a name it displays all subject marks of that particular name in a column chart #markswise - when i select a subject, it displays all the names with marks in that particular subject. conisdiering that data may be added and i've to accumulate that also, for namewise i did // chart.php <?php include("connection.php"); $query = "SELECT name FROM csv GROUP BY name DESC"; $statement = $connect->prepare($query); $statement->execute(); $result = $statement->fetchAll(); ?> <!DOCTYPE html> <html> <head> <title>Google charts</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> </head> <body> <br /><br /> <div class="container"> <div class="panel panel-default"> <div class="panel-heading"> <div class="row"> <div class="col-md-9"> <h3 class="panel-title">Student Wise Marks Data</h3> </div> <div class="col-md-3"> <select name="name" class="form-control" id="name"> <option value="">Select Student</option> <?php foreach($result as $row) { echo '<option value="'.$row["name"].'">'.$row["name"].'</option>'; } ?> </select> </div> </div> </div> <div class="panel-body"> <div id="chart_area" style="width: 1000px; height: 620px;"></div> </div> </div> </div> </body> </html> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {packages: ['corechart', 'bar']}); google.charts.setOnLoadCallback(); function load_student_data(name, title) { var temp_title = title + ' '+name+''; $.ajax({ url:"fetch.php", method:"POST", data:{name:name}, dataType:"JSON", success:function(data) { drawStudentwiseChart(data, temp_title); } }); } function drawStudentwiseChart(chart_data, chart_main_title) { var jsonData = chart_data; var data = new google.visualization.DataTable(); data.addColumn('number', 'Physics'); data.addColumn('number', 'Maths'); data.addColumn('number', 'Chemistry'); data.addColumn('number', 'Biology'); data.addColumn('number', 'SST'); $.each(jsonData, function(i, jsonData){ var Physics = jsonData.Physics; var Maths = jsonData.Maths; var Chemistry = jsonData.Chemistry; var Biology = jsonData.Biology; var SST = jsonData.SST; data.addRows([[Physics,Maths,Chemistry,Biology,SST]]); }); var options = { title:chart_main_title, hAxis: { title: "Subjects" }, vAxis: { title: 'Percentage' } }; var chart = new google.visualization.ColumnChart(document.getElementById('chart_area')); chart.draw(data, options); } </script> <script> $(document).ready(function(){ $('#name').change(function(){ var name = $(this).val(); if(name != '') { load_student_data(name, 'Student wise marks data'); } }); }); </script> and in order to fetch data // fetch.php <?php //fetch.php include('connection.php'); if(isset($_POST["name"])) { $query = " SELECT * FROM csv WHERE name = '".$_POST["name"]."' ORDER BY id ASC "; $statement = $connect->prepare($query); $statement->execute(); $result = $statement->fetchAll(); foreach($result as $row) { $output[] = array( 'Physics' => $row["Physics"], 'Maths' => $row["Maths"], 'Chemistry' => $row["Chemistry"], 'Biology' => $row["Biology"], 'SST' => $row["SST"], ); } echo json_encode($output); } ?> it diplays a blank page. however when i play with singular values i.e one subject at a time it displays fine Edited March 19, 2019 by zetastreakHi, I am hoping someone can help me out with a slight issue I have with php and mySQL. I have an ajax-powered form with a select (dropdown) field populated through a php function. Based on the user-selected values in this field, data is displayed on the webpage; i.e. selected value 1 returns values x and y on the page. I am now trying to call additional data (value z) from a different table in the same database, and as before, use the selected values from the dropdown to display the data. For some reason, value z is not changing according to the user-selected value. This is my code: [The function to populate the select field] Code: [Select] function kfl_get_funds_names() { $result = array(); $result['CDF'] = 'Crosby Dragon Fund'; $result['CPF'] = 'Crosby Phoenix Fund'; $result['AMZPIF'] = 'AMZ Plus Income Fund'; $result['KASBIIF'] = 'KASB Islamic Income Opportunity'; $result['KASBCPGF'] = 'KASB Capital Protected Gold Fund'; $result['KASBLF'] = 'KASB Income Opportunity Fund'; $result['KASBCF'] = 'KASB Cash Fund'; $result['KASBBF'] = 'KASB Asset Allocation Fund'; $result['KASBSMF'] = 'KASB Stock Market Fund'; return $result; } [the code calling and using the function to interact with the database] Code: [Select] $funds_to_display = kfl_get_funds_names(); $current_symbol = key( $funds_to_display ); $current_nav_rates = kfl_get_latest_rates( $current_symbol ); [the code calling additional data, value z, from the database, and using the info in the select field to filter it] Code: [Select] $cutoff = kfl_cutoff( $current_symbol ); The display of each of these items is as follows: Code: [Select] <?php echo $current_nav_rates['nav_date']; ?> <?php echo $funds_to_display[$current_symbol]; ?> <?php echo $cutoff['cutoff']; ?> I can't get the $cutoff code to display the correct values. It picks up the first symbol to display and doesn't change with user selection. The code for the selection box, by the way: Code: [Select] <select id="dailynav-funds" autocomplete="off" name="dnf"> <?php foreach ($funds_to_display as $fund_symbol => $fund_name) { echo '<option'; if( $fund_symbol == $current_symbol ) { echo ' selected="selected"'; } echo ' value="' . $fund_symbol . '">'; echo $fund_name; echo '</option>'; } ?> </select> I've tried to get data using $_GET['dnf'] into the cutoff code, but that throws up parse errors. What am I doing wrong, and how can I resolve this issue? Thanks in advance! I have a working image upload script that uploads, renames the file and adds filename to the database. is it possible to include some sort of image resize code? if so can anyone point me in the right direction or better still show some example code and explain how it works etc. below is my working code: Code: [Select] <?php $rand = mt_rand(1,9999999); $member_id = $_SESSION['SESS_MEMBER_ID']; $caption = $_POST["caption"]; if(isset($_FILES['uploaded']['name'])) { $allowed_filetypes = array('.jpg','.gif','.bmp','.png','.jpeg'); $max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB) $fileName = basename($_FILES['uploaded']['name']); $errors = array(); $target = "gallery/"; $fileBaseName = substr($fileName, 0, strripos($fileName, '.')); // Get the extension from the filename. $ext = substr($fileName, strpos($fileName,'.'), strlen($fileName)-1); //$newFileName = md5($fileBaseName) . $ext; $newFileName = $target . $rand . "_" . $member_id.$ext; // Check if filename already exists if(file_exists("gallery/" . $newFileName)) { $errors[] = "The file you attempted to upload already exists, please try again."; } // Check if the filetype is allowed. if(!in_array($ext,$allowed_filetypes)) { $errors[] = "The file you attempted to upload is not allowed."; } // Now check the filesize. if(!filesize($_FILES['uploaded']['tmp_name']) > $max_filesize) { $errors[] = "The file you attempted to upload is too large."; } // Check if we can upload to the specified path. if(!is_writable($target)) { $errors[] = "You cannot upload to the specified directory, please CHMOD it to 777."; } //Here we check that no validation errors have occured. if(count($errors)==0) { //Try to upload it. if(!move_uploaded_file($_FILES['uploaded']['tmp_name'], $newFileName)) { $errors[] = "Sorry, there was a problem uploading your file."; } } //Lets INSERT database information here if(count($errors)==0) { $result = mysql_query("INSERT INTO `gallery` (`image`, `memberid`, `caption`) VALUES ('$newFileName', '$member_id', '$caption')") or die (mysql_error()); } //If no errors show confirmation message if(count($errors)==0) { echo "<div class='notification success png_bg'> <a href='#' class='close'><img src='img/cross_grey_small.png' title='Close this notification' alt='close' /></a> <div> Image has been uploaded.<br>\n </div> </div>"; //echo "The file {$fileName} has been uploaded"; echo "<br>\n"; echo "<a href='gallery.php'>Go Back</a>\n"; } else { //show error message echo "<div class='notification attention png_bg'> <a href='#' class='close'><img src='img/cross_grey_small.png' title='Close this notification' alt='close' /></a> <div> Sorry your file was not uploaded due to the following errors:<br>\n </div> </div>"; //echo "Sorry your file was not uploaded due to the following errors:<br>\n"; echo "<ul>\n"; foreach($errors as $error) { echo "<li>{$error}</li>\n"; } echo "</ul>\n"; echo "<br>\n"; echo "<a href='gallery.php'>Go Back</a>\n"; } } else { //Show the form echo "Use the following form below to add a new image to your gallery;<br /><br />\n"; echo "<form enctype='multipart/form-data' action='' method='POST'>\n"; echo "Please choose a file:<br /><input class='text' name='uploaded' type='file' /><br />\n"; echo "Image Caption:<br /><input class='text' name='caption' type='text' value='' /><br /><br />\n"; echo "<input class='Button' type='submit' value='Upload' />\n"; echo "</form>\n"; } ?> Many thanks to phpfreaks again. |