PHP - Php -> Mysql - Inserting Of Pdf Into Blob
Hi guys,
This is my first time to insert PDF into MySQL BLOB. Below is my form that i used Code: [Select] <?php <form enctype="multipart/form-data" name="frmUploadFile" action="ulf-exec.php" method="post"> <select name="title" id="title"> <option>xxx</option> <option>yyy</option> <option>zzz</option> </select> </label> <input name="des" type="text" class="dropdownlists1" id="des"></td> <input name="fileUpload" type="file" class="dropdownlists1" id="fileUpload" size="20" border=""></td> <input type="submit" name="button" id="button" value="Submit"> </form> ?> I have prepared my database based on the required but decided to test with echo just to confirm there's no issue with the code The action="ulf-exec.php" : Code: [Select] <?php function clean($str) { $str = @trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } return mysql_real_escape_string($str); } //Sanitize the POST values $title = clean($_POST['title']); $des = clean($_POST['des']); $fileUpload = $_POST['fileUpload']; if(empty($des) || $fileUpload == "none") die("You must enter both a description and file"); $fileHandle = fopen($fileUpload, "r"); $fileContent = fread($fileHandle, $fileUpload_size); $fileContent = addslashes($fileContent); $date = date('d').'-'.date('m').'-'.date('y'); $time = date('h').':'.date('i').':'.date('s'); echo "<h1>File Uploaded</h1>"; echo "The details of the uploaded file are shown below:<br><br>"; echo "<b>File name:</b> $fileUpload_name <br>"; echo "<b>File type:</b> $fileUpload_type <br>"; echo "<b>File size:</b> $fileUpload_size <br>"; echo "<b>Uploaded to:</b> $fileUpload <br><br>"; echo "<a href='uploadfile.php'>Add Another File</a>"; ?> This is the error: Code: [Select] Warning: fopen() [function.fopen]: Filename cannot be empty in /ulf-exec.php on line 30 Warning: fread(): supplied argument is not a valid stream resource in ulf-exec.php on line 31 Similar TutorialsHello, I am storing files that my users upload to the website as a blob in mysql database. Here is the code that does uploading: $fileName = $_FILES['userfile']['name']; $tmpName = $_FILES['userfile']['tmp_name']; $fileSize = $_FILES['userfile']['size']; $fileType = $_FILES['userfile']['type']; $fp = fopen($tmpName, 'r'); $content = fread($fp, filesize($tmpName)); $content = mysql_real_escape_string($content); fclose($fp); if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); } $query = mysql_query("INSERT INTO documents (idapplicant, fileType, fileSize, fileData, fileName) VALUES ('$idapplicant','$fileType','$fileSize', '$content','$fileName')",$db); Here is the code for download: echo "File found:".@mysql_result($result, 0, "fileID"); //always correct $data = @mysql_result($result, 0, "fileData"); $name = @mysql_result($result, 0, "fileName"); $size = @mysql_result($result, 0, "fileSize"); $type = @mysql_result($result, 0, "fileType"); header("Content-length: $size"); header("Content-type: $type"); header("Content-Disposition: attachment; filename=$name"); echo $data; I can upload/download files no problem. However, I noticed problem with GIF files. All GIF files are just dark screen after downloading. All other files (PDF, JPEG) looked just fine. I compared files (before upload and after download) in HEX editor and found that the first byte on all files is set to A0 (it is added in front of all the data) and the last byte is deleted! I have tried: $content = addslashes($content); instead of: $content = mysql_real_escape_string($content); with the same results I also tried removing this line of code and in that case no file would be uploaded at all! Any idea? Thank you I have created a image using imagepng() and then right-click'd and saved it. I then added it to the database by using phpMyAdmin to upload it directly into a field called 'avatar' which is a BLOB. The code the view the image back is the following: header("Content-type: image/png"); echo mysql_result(mysql_query("SELECT `avatar` FROM `rscd_players` WHERE `username` = 'Kryptix'"), 0); Now when I try and add the imagepng() directly to the database it doesn't work. I've tried multiple things. Here's the code: ob_start(); imagepng($char_image); $pngimagedata = ob_get_contents(); ob_end_clean(); mysql_query("UPDATE `rscd_players` SET `avatar` = " . $pngimagedata . " WHERE `username` = 'Kryptix'"); Here's the full code: http://pastebin.com/jqsKc9Qd This is the query that phpMyAdmin produces: http://pastebin.com/nuypNuwJ This is the query that the above code produces: http://pastebin.com/NPWmi5eb phpMyAdmin is 2.2kB, my code is 4.4kB Any idea? I've been trying all night... Hi! I am building a little PHP/MySQL application where pictures are uploaded and stored in MySQL in a longblob. These are special circumstances and storing images in the database in an absolute must. Uploading is working fine. The upload script inserts the following into the field `image_data`: base64_encode(file_get_contents($_FILES['image']['tmp_name'])) The problem is displaying the images. I cannot for the life of me make it work. I've tried the code on multiple systems with various versions of PHP and MySQL. I have two files: one called view.php and one called show.php. # view.php # It gets $info['id'] from a query getting the ID of the recent-most image uploaded. echo '<img src="show.php?id='.$info['id'].'" alt="" />'; # show.php # $id is determined by $_GET['id'] and passes through security checks I've omitted here. # There is zero (not even a whitespace) output before the header()s are sent. $query = "SELECT `image_data`,`image_mime`,`image_size` FROM `upload`.`files` WHERE `id` = '$id';"; $sql = mysql_query($query) or die(mysql_error()); $image = mysql_fetch_assoc($sql); header('Content-Type: ' . $image['image_mime']); header('Content-Length: ' . $image['image_size']); echo base64_decode($image['image_data']); The problem is that no image is displayed either in view.php or when I call show.php directly with a valid ID. I have verified that $image['image_mime'] and $image['image_size'] contain the right data. However, if I download show.php and change extension to for example .jpg, the image is there. So the image is stored correctly in the database and $image['image_data'] is outputting the right data. I even compared checksums for the image before and after and they're identical, so I would conclude that the error is in the outputting of the image - but I can't figure out what. Error_report is set to E_ALL but there's nothing useful coming out. Any ideas? Code: [Select] $thephoto = $row['thePHOTO']; in mysql thephoto is BLOB file type and stores an image i want to display the image as an avatar, in a while loop. Code: [Select] while($row = mysql_fetch_assoc($query4)) { $id = $row['ID']; $thename = $row['theNAME']; $thephoto = $row['thePHOTO']; } how do i make blob readable and then display as an image? Hi guys, I have a problem. I need to create a page that has a web form to upload an image to a mySQL database and place it in a blob field. Then I need to be able to query the database later to display the image on the site. I've looked around but I just haven't found any examples that can help me. Does anyone know of any good example or can anyone please give me an example? I have nothing so far, just the html web form and database. Hi All, This is my first post on here. I'd really appreciate any help with this, it's driving me mad. I'm trying to create a form to save a image into a mySQL database. I have a website hosted by UK2.net which has a mysql db with a table called gallery(name (varchar 30), size (int), type varchar(30), thePic(mediumBlob)). I have a form with this: Code: [Select] <td><p><label>Pic: </label></td><td><input name="userfile" type="file" id="userfile" /></td></p> Which when submitted actions addImage.php. The code for this looks like this: Code: [Select] <?php $fileName = $_FILES['userfile']['name']; $tmpName = $_FILES['userfile']['tmp_name']; $fileSize = $_FILES['userfile']['size']; $fileType = $_FILES['userfile']['type']; $fp = fopen($tmpName, 'r'); $content = fread($fp, filesize($tmpName)); $content = addslashes($content); fclose($fp); if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); } $con = mysql_connect("localhost", "userName", "password") or die(mysql_error()); mysql_select_db("dbName", $con) or die(mysql_error()); $query = "INSERT INTO gallery (name, size, type, thePic) ". "VALUES ('$fileName', '$fileSize', '$fileType', '$content')"; if (!mysql_query($query,$con)) { die('Error: ' . mysql_error()); } echo "<br>File $fileName uploaded<br>"; ?> I get the following error message: Quote Warning: fopen() [function.fopen]: Filename cannot be empty in /home/hiddenje/public_html/addImage.php on line 13 Does anyone know what this is about? I've been on out friend google and a lot of people seem to be pointing to permissions but I can't seem to apply it to my scenario and just can't get it to work. Im a developer by trade, but this is my first step into the...interesting world of PHP and mySQL. Again, I'd appreciate any help with this. I'd love someone to talk me through exactly what I'm missing or doing wrong. Thanks in advance. this is my 3 files which is i am using to show data of customer but i am not able to see them their logo image please see them & help me guys i dont know whats wrong in this. these files i uploaded please find attachment to see them. thnx in advanced [attachment deleted by admin] Okay, so here is the deal. Have a table which stores image as blob files. Now i want to read the image width and height directly from the blob field. Is this possible and if yes, how? Things i tried so far; list($size[0],$size[1],$type, $attr) = getimagesize('image.php?i=26ddd45b02859e836d13d4b9fde34281'); print_r($size); $img = 'image.php?i=26ddd45b02859e836d13d4b9fde34281'; echo imagesy($img); image.php grabs the image from DB and show's it with header("Content-type: image/jpg"); It works for just showing the images with the <img> tag. Any ideas of help would be great! Hi guys I am using the code found here http://www.elated.com/articles/cms-in-an-afternoon-php-mysql/ with some alterations to try and insert data in a database via a php form, i have completed the example shown on that site and it works perfect, but I am now trying to adjust the code so that i have a user and admin section, but the form will not submit to the database. Here is the for my form, page know as editArticles: Code: [Select] <?php include "templates/include/header.php" ?> <div id="userHeader"> <h2><spanH1>Advertise!</spanH1> Place an advert for your book</h2> <p>You are logged in as <b><?php echo htmlspecialchars( $_SESSION['username']) ?></b>. <a href="user.php?action=logout"?>Log out</a></p> </div> <h1><?php echo $results['pageTitle']?></h1> <form action="user.php?action=newArticle" method="post"> <input type="hidden" name="articleId" value="<?php echo $results['article']->id ?>"/> <?php if ( isset( $results['errorMessage'] ) ) { ?> <div class="errorMessage"><?php echo $results['errorMessage'] ?></div> <?php } ?> <ul> <li> <label for="booktitle">Book Title</label> <input type="text" name="booktitle" id="booktitle" placeholder="Title of the book" required autofocus maxlength="100" value="<?php echo htmlspecialchars( $results['article']->booktitle )?>" /> </li> <li> <label for="author">Book Author</label> <input type="text" name="author" id="author" placeholder="Author of the book" required autofocus maxlength="50" value="<?php echo htmlspecialchars( $results['article']->author )?>" /> </li> <li> <label for="edition">Edition</label> <input type="text" name="edition" id="edition" placeholder="Edition" required autofocus maxlength="2" value="<?php echo ( $results['article']->edition )?>" /> </li> <li> <label for="category">Category</label> <input type="text" name="category" id="category" placeholder="Book Category E.G Buisness" required autofocus maxlength="30" value="<?php echo htmlspecialchars( $results['article']->category )?>" /> </li> <li> <label for="module">Module</label> <input type="text" name="module" id="module" placeholder="Module" required autofocus maxlength="30" value="<?php echo ( $results['article']->module )?>" /> </li> <li> <label for="price">Price</label> <input type="text" name="price" id="price" placeholder="Price" required autofocus maxlength="30" value="<?php echo ( $results['article']->price )?>" /> </li> <li> <label for="condition">Condition</label> <input type="text" name="condition" id="condition" placeholder="condition" required autofocus maxlength="30" value="<?php echo ( $results['article']->condition )?>" /> </li> <li> <label for="description">Description</label> <textarea name="description" id="description" placeholder="Description of the book including condition and associated modules" required maxlength="500" style="height: 15em;"> <?php echo htmlspecialchars( $results['article']->description )?></textarea> </li> <li> <label for="Image">Image</label> <input type="file" name="Image" id="Image" /> </li> <li> <label for="pdate">Sale Date</label> <input type="date" name="pdate" id="pdate" placeholder="YYYY-MM-DD" required maxlength="10" value="<?php echo $results['article']->pdate ? date( "Y-m-d", $results['article']->pdate ) : "" ?>" /> </li> </ul> <div class="buttons"> <input type="submit" name="saveChanges" value="Save Changes" /> <input type="submit" formnovalidate name="cancel" value="Cancel" /> </div> </form> <?php if ( $results['article']->id ) { ?> <p><a href="admin.php?action=deleteArticle&articleId=<?php echo $results['article']->id ?>" onclick="return confirm('Delete This Article?')">Delete This Article</a></p> <?php } ?> <?php include "templates/include/footer.php" ?> This is the form for the php, as you can see the form action is "new article" This is the code for the action new article Code: [Select] function newArticle() { $results = array(); $results['pageTitle'] = "New Article"; $results['formAction'] = "newArticle"; if ( isset( $_POST['saveChanges'] ) ) { // User has posted the article edit form: save the new article $article = new Article; $article->storeFormValues( $_POST ); $article->insert(); header( "Location: admin.php?status=changesSaved" ); } elseif ( isset( $_POST['cancel'] ) ) { // User has cancelled their edits: return to the article list header( "Location: admin.php" ); } else { // User has not posted the article edit form yet: display the form $results['article'] = new Article; require( TEMPLATE_PATH . "/admin/editArticle.php" ); } } As you can see the template is set to the above form page editArticle Below is the code for the class "article" which contains the insert function and other functions such as construct, the storeFormValues which can is used in the "newArticle" function, and of course the insert function Code: [Select] class Article { public $id = null; public $booktitle = null; public $author = null; public $edition = null; public $category = null; public $module = null; public $price = null; public $condition = null; public $description = null; public $image = null; public $pdate = null; public function __construct( $data=array() ) { if ( isset( $data['id'] ) ) $this->id = (int) $data['id']; if ( isset( $data['booktitle'] ) ) $this->booktitle = preg_replace ( "/[^\.\,\-\_\'\"\@\?\!\:\$ a-zA-Z0-9()]/", "", $data['booktitle'] ); if ( isset( $data['author'] ) ) $this->author = preg_replace ( "/[^\.\,\-\_\'\"\@\?\!\:\$ a-zA-Z0-9()]/", "", $data['author'] ); if ( isset( $data['edition'] ) ) $this->edition = $data['edition']; if ( isset( $data['category'] ) ) $this->category = $data['category']; if ( isset( $data['module'] ) ) $this->module = $data['module']; if ( isset( $data['price'] ) ) $this->price =(int) $data['price']; if ( isset( $data['condition'] ) ) $this->condition = $data['condition']; if ( isset( $data['description'] ) ) $this->description = $data['description']; if ( isset( $data['image'] ) ) $this->image = $data['image']; if ( isset( $data['pdate'] ) ) $this->pdate = (int) $data['pdate']; } public function storeFormValues ( $params ) { // Store all the parameters $this->__construct( $params ); // Parse and store the publication date if ( isset($params['pdate']) ) { $sdate = explode ( '-', $params['pdate'] ); if ( count($pdate) == 3 ) { list ( $y, $m, $d ) = $pdate; $this->pdate = mktime ( 0, 0, 0, $m, $d, $y ); } } } public function insert() { // Does the Article object already have an ID? if ( !is_null( $this->id ) ) trigger_error ( "Article::insert(): Attempt to insert an Article object that already has its ID property set (to $this->id).", E_USER_ERROR ); // Insert the Article $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD ); $sql = "INSERT INTO books ( booktitle, author, edition, category, module, price, condition, description, image, pdate ) VALUES ( :booktitle, :author, :edition, :category, :module, :price, :condition, :description, :image, FROM_UNIXTIME(:pdate) )"; $st = $conn->prepare ( $sql ); $st->bindValue( ":booktitle", $this->booktitle, PDO::PARAM_STR ); $st->bindValue( ":author", $this->author, PDO::PARAM_STR ); $st->bindValue( ":edition", $this->edition, PDO::PARAM_STR ); $st->bindValue( ":category", $this->category, PDO::PARAM_STR ); $st->bindValue( ":module", $this->module, PDO::PARAM_STR ); $st->bindValue( ":price", $this->price, PDO::PARAM_INT ); $st->bindValue( ":condition", $this->condition, PDO::PARAM_STR ); $st->bindValue( ":description", $this->description, PDO::PARAM_STR ); $st->bindValue( ":image", $this->image, PDO::PARAM_STR ); $st->bindValue( ":pdate", $this->pdate, PDO::PARAM_INT ); $st->execute(); $this->id = $conn->lastInsertId(); $conn = null; } I would truly appreciate if someone is able to figure out what is going wrong, btw i dont get any errors when i click the save it takes mw to the next page and show a message i have set saying the changes have been saved but it doesnt actually save to me database. If you have any questions or i need to explain more please let me know Thanks in advance Hi, Does anyone have any idea how to insert an entire php or html pages into mysql once the page has being created with php? E.g. np1.php <form action="np2.php" method="post"> Name of New Page: <input type="text" name="newpage_name" /> <input type="submit" /> </form> np2.php <?php $newpage_name = $_POST[ 'newpage_name' ]; $newpage_initial = "Input Contents Here."; //echo $editor_data; $newpage_file = "test/" . $newpage_name . ".php"; $newpage_save = fopen($newpage_file, 'w'); fwrite($newpage_save, $newpage_initial); fclose($newpage_save); ?> I have managed to create a new file with php but I also want it when I click on the submit button, it will also auto save that new php file or html file into mysql. Regards Jas Thanks for reading my post, Can someone point me to the right direction here; Am trying to insert a record in a text area field into PHP/MYSQl. This time around, I am reading what the user entered into the textarea before inserting. Take a look at this: TEXTAREA -> row 1: BOY row 2: GIRL Can I make it two rows in my database as opposed to one? I don't have a problem inserting, just how to insert as multiple if there are two rows. Thanks in advance hey, here is the code I am using. Code: [Select] mysql_connect("localhost","XXXXXX","XXXXXX") or die("Could not connect."); mysql_select_db("XXXXXX"); $query="SELECT * FROM VIDEO_SESSIONS"; $result=mysql_query($query); while ($db_field = mysql_fetch_assoc($result)) { $timeslider = $db_field['timeslider']; } $message=$_POST['message']; $name=$me['first_name']; if(isset($_POST['submit'])){ if(strlen($message)<1) { print "You did not input a message"; } else if(strlen($name)<1) { print "Please login with Facebook to post a message"; } else { $insertmessage="INSERT INTO CHAT_SESSIONS (user_id,user_message,current_time) VALUES ('$name', '$message', '$timeslider')"; mysql_query($insertmessage); echo mysql_error(); } } ?> I am getting this error everytime I try and INSERT into the database " You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'current_time) VALUES ('Luke', 'Hello?', '00:23:00')' at line 2 " it works fine without the '$timeslider' which is a time stored on the database in the format 00:00:00 why does it not want to store the time back in a different table.. same format!? Hello I have a text list that looks like this: Code: [Select] ACACIA-Acacia spp.-Australia AMANITAS-Amanita muscaria-Siberia AYAHUASCA-Yage-Amazon Basin ... continues... i am trying to create a script that if i placed that text like that in a textarea and submitted the form it would explode each line one at a time by the "-" and add it into a mysql database (COMMON_NAME, GENUS_SPECIES, NATIVE_TO) I dont want to have to submit these one at a time and im sure this is very simple to do just im not understanding how to explode each line. maybe a code like; 1. counts the total number of lines and places it in a variable called lines 2. do while $lines > 0 3. for each $line explode by "-" 4. insert each piece of the exploded line into the database as (COMMON_NAME, GENUS_SPECIES, NATIVE_TO) as piece 0,1, & 2 5. after inserted subtract 1 from $lines or something similar to that effect. any help is greatly appreciated1 Hey Guys, I have to insert some data in MySQL but it wont work . Please have a look. <?php // to values are set to empty $vatsim=""; $ivao=""; // values from form in other page are set if(isset($_POST["pilotid"])) $pilotid=$_POST["pilotid"]; if(isset($_POST["network"])) $network=$_POST["network"]; if(isset($_POST["vid"])) $vid=$_POST["vid"]; if(isset($_POST["pilot"])) $pilot=$_POST["pilot"]; // if value is that copy data in this value, otherways in that value if ($network == "IVAO") { $ivao="$vid";} if ($network == "VATSIM") { $vatsim="$ivao";} // connect db include(dbconnect.inc.php); // first sql to update some data in one table $sql = "UPDATE `360283`.`jos_users` SET `IPS` = \'1\' WHERE `jos_users`.`id` = \'$pilotid\'"; $result1 = mysql_query($sql); // 2nd sql to insert some data in other table $sql2 = "INSERT INTO `360283`.`IPS_Pilots` (`ID`, `Name`, `Hours`, `Flights`, `LastFlight`, `IVAO`, `VATSIM`, `Enabled`, `Rating`) VALUES ('$pilotid', '$pilot', NULL, NULL, NULL, '$ivao', '$vatsim', '1', '0');"; $result2 = mysql_query($sql2); // sql to check if it was succesful $sql3 = "SELECT * FROM `IPS_Pilots` WHERE `ID` = '$pilotid' LIMIT 0, 30 "; $result3 = mysql_query($sql3); $num3 = mysql_numrows($result3); // echo succesfull or not if (!$num3) { echo "Sorry, but I failed to apply this pilot."; } else { echo "Pilot succesfully applied."; } ?> Thanks Hi All, I'm trying to insert a HTML code into one of the fileds so when you load the page it reads that code and shows you the picture that code is pointing you as you can see below but the problem is I have too many " and ' s so PHP wont pass it. $name = $_POST['name']; $title = $_POST['title']; $ext = $_POST['ext']; $cell = $_POST['cell']; $sec = $_POST['sec']; $emp = $_POST['emp']; $con = mysql_connect("localhost","root","PA55ss"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("movedb", $con); $sql="INSERT INTO sheet1sa (ext, F2, cell, name, dep, F6, empno) VALUES ('$ext', '$sec', '$cell', '$name', '$dep', '<img src='./pics/$empno.jpg' width="80" height='90' />", '$empno')"; BTW i need to make this code so it takes the "empno" value and insert it into that code before .JPG so when browser reads my database it will read it as "./pics/777788.JPG" Thanks for your help I'm sorry to be back so soon, but I'm up against another mystery. I'm using the code below to enter a bunch of css data from a spreadsheet into a mysql table. I think the data file is OK. The array created by the script checks out with print_r. (There are many more records than shown. I truncated it to save space.) The problem is that I get this error regarding my sql statement, not the data or anything else: Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'check, name, phone, email, entry_fee, print_fee, image_name, description, med...' at line 1 in /Users/studio/Sites/BannerProject/b-as/_test_site/csv_to_array.php:242 Stack trace: #0 /Users/studio/Sites/BannerProject/b-as/_test_site/csv_to_array.php(242): PDO->prepare('INSERT INTO tbl...') #1 {main} thrown in /Users/studio/Sites/BannerProject/b-as/_test_site/csv_to_array.php on line 242 I've typed it in a dozen times to make sure there are no errors and keep getting the same error. I tried running a test file and gradually increasing the number of placeholders and at some point I always end up getting the same error, I can delete the most recent addition and it works again. Then I can add another placeholder exactly as before and it works the second time. It feels like a ghost in the machine. Any idea what I am doing wrong? An I typing something I don't see? <?php require '__classes/Db.php'; $csvData = '1,FALSE,Carol Lettko,,,TRUE,FALSE,Carol_Lettko-DSC_3022.jpg,Baby Herons/Brickyard,photo,,, ,,,925-285-0320,cjl164@aol.com,,,Carol_Lettko-DSC_0164.JPG,Heron/Brickyard,photo,,, ,,,,,,,Carol_Lettko-IMG_5723.jpg,Kayaker/Brickyard,photo,,, ,,,,,,,,,,,, 2,FALSE,Louise Williams,,,TRUE,FALSE,Louise_Williams-BirdsOfAFeatherAOPR.jpg,Alligator with Words,Book Excerpt,,, ,,,510-232-9547,lkw@louisekwilliams.com,,,Louise_Williams-Hope-TheFairyChickenAOPR.jpg,Hope The Fairy Chicken,,,, ,,,The d exatrfrfvct/.*tygrvurr,,,,,,,,, ,,,,,,,,,,,, 3,TRUE,Dorothy Leeland,,lelanddorothy@gmail.com,TRUE,FALSE,DJ_Lee-bridge at dusk 700px width.jpg,Bridge,photo,,, ,,,,,,,DJ_Lee-friends 700px width.jpg,Friends,photo,,, ,,,,,,,DJ_Lee-hybiscus 700 px wide.jpg,Hibiscus,photo,,, ,,,,,,,,,,,, 4,FALSE,Rita Gardner,,,TRUE,FALSE,Rita_Gardner-Explosion - Gardner photo.JPG,Explosion,photo,,, ,,,,tropicrita@msn.com,,,Rita_Gardner-Ferry Point tables and chair - Gardner.JPG,Ferry Point Tables,photo,, , ,,,,,,,Rita_Gardner-Forks - Gardner photo.JPG,Forks,photo,,, ,,,,,,,,,,,, '; $lines = explode(PHP_EOL, $csvData); $array1 = array(); foreach ($lines as $line) { $array1[] = str_getcsv($line); } $stmt = $pdo->prepare("INSERT INTO tbl_person_data (number, check, name, phone, email, entry_fee, print_fee, image_name, description, medium, select, orient, site) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"); foreach ($array1 as $row) { $stmt->execute('$row'); } echo '<pre>'; print_r($array1); echo '</pre>'; ?>
Hi all I am trying to write a script that takes the filename and username from a form and adds it into a mySQL database. At the moment only the username is added? Here's my code: <?php include('includes/connection.php'); $username = $_POST['username']; date_default_timezone_set('Europe/London'); // Change time zone to GMT $date = date ('D M j G:i:s'); // Set date format $path= "/home/cndvizp/public_html/prints2impress.co.uk/images/uploads/".$HTTP_POST_FILES['ufile']['name']; if($ufile !=none) { if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path)) { //insert new query $filename = $_FILES['ufile']['name']; $pfw_strQuery = "INSERT INTO `uploads`(`username`,`url`,`date_entered`)VALUES (\"$username\",\"$filename\",\"$date\")" ; $pfw_result = mysql_query($pfw_strQuery); if (!$pfw_result) { die('Invalid query: ' . mysql_error()); } //include ('payment.php'); echo 'done'; } else { //include ('error.php'); echo 'error!'; exit; } } ?> Can anyone help me get the filename and the date to be added? Cheers Pete. Hello, me again. I have created a little forum - very very basic. main_forum.php : Code: [Select] <?php $host="localhost"; // Host name $username="yvonnedp"; // Mysql username $password="yvonne"; // Mysql password $db_name="forum"; // Database name $tbl_name="forum_question"; // Table name // Connect to server and select databse. mysql_connect('localhost', 'yvonnedp', 'yvonne')or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $sql="SELECT * FROM $tbl_name ORDER BY id"; // OREDER BY id DESC is order result by descending $result=mysql_query($sql); ?> <table width="90%" border="0" align="center" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC"> <tr> <td width="6%" align="center" bgcolor="#E6E6E6"><strong>#</strong></td> <td width="53%" align="center" bgcolor="#E6E6E6"><strong>Topic</strong></td> <td width="15%" align="center" bgcolor="#E6E6E6"><strong>Views</strong></td> <td width="13%" align="center" bgcolor="#E6E6E6"><strong>Replies</strong></td> <td width="13%" align="center" bgcolor="#E6E6E6"><strong>Date/Time</strong></td> </tr> <?php while($rows=mysql_fetch_array($result)){ // Start looping table row ?> <tr> <td bgcolor="#FFFFFF"><? echo $rows['id']; ?></td> <td bgcolor="#FFFFFF"><a href="view_topic.php?id=<? echo $rows['id']; ?>"><? echo $rows['topic']; ?></a><BR></td> <td align="center" bgcolor="#FFFFFF"><? echo $rows['view']; ?></td> <td align="center" bgcolor="#FFFFFF"><? echo $rows['reply']; ?></td> <td align="center" bgcolor="#FFFFFF"><? echo $rows['datetime']; ?></td> </tr> <?php // Exit looping and close connection } mysql_close(); ?> create_topic.php : Code: [Select] <table width="400" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC"> <tr> <form id="form1" name="form1" method="post" action="add_topic.php"> <td> <table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF"> <tr> <td colspan="3" bgcolor="#E6E6E6"><strong>Create New Topic</strong> </td> </tr> <tr> <td width="14%"><strong>Topic</strong></td> <td width="2%">:</td> <td width="84%"><input name="topic" type="text" id="topic" size="50" /></td> </tr> <tr> <td valign="top"><strong>Detail</strong></td> <td valign="top">:</td> <td><textarea name="detail" cols="50" rows="3" id="detail"></textarea></td> </tr> <tr> <td><strong>Name</strong></td> <td>:</td> <td><input name="name" type="text" id="name" size="50" /></td> </tr> <tr> <td> </td> <td> </td> <td><input type="submit" name="Submit" value="Submit" /> <input type="reset" name="Submit2" value="Reset" /></td> </tr> </table> </td> </form> </tr> </table> add_topic.php : Code: [Select] <?php $host="localhost"; // Host name $username="yvonnedp"; // Mysql username $password="yvonne"; // Mysql password $db_name="forum"; // Database name $tbl_name="forum_question"; // Table name // Connect to server and select database. mysql_connect('localhost', 'yvonnedp', 'yvonne')or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // get data that sent from form $topic=$_POST['topic']; $detail=$_POST['detail']; $name=$_POST['name']; $datetime=date("d/m/y h:i:s"); //create date time $sql="INSERT INTO $tbl_name(topic, detail, name, datetime)VALUES('$topic', '$detail', '$name', '$datetime')"; $result=mysql_query($sql); if($result){ echo "Successful<BR>"; echo "<a href=main_forum.php>View your topic</a>"; $email_from = "forums@thenewme.co.za"; $email_to = "info@thenewme.co.za"; $email_subject = "The New Me - New Forum Topic"; $email_message = "A new topic has been posted on the Forum!\n"; $email_message .= "Check it out : http://www.thenewme.co.za/forum/main_forum.php"; $headers = 'From: '.$email_from."\r\n"; 'Reply-To: '.$email_from."\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $email_subject, $email_message, $headers); } else { echo "ERROR"; } mysql_close(); ?> add_answer.php : Code: [Select] <?php $host="localhost"; // Host name $username="yvonnedp"; // Mysql username $password="yvonne"; // Mysql password $db_name="forum"; // Database name $tbl_name="forum_answer"; // Table name // Connect to server and select databse. mysql_connect('localhost', 'yvonnedp', 'yvonne')or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // Get value of id that sent from hidden field $id=$_POST['id']; // Find highest answer number. $sql="SELECT MAX(a_id) AS Maxa_id FROM $tbl_name WHERE question_id='$id'"; $result=mysql_query($sql); $rows=mysql_fetch_array($result); // add + 1 to highest answer number and keep it in variable name "$Max_id". if there no answer yet set it = 1 if ($rows) { $Max_id = $rows['Maxa_id']+1; } else { $Max_id = 1; } // get values that sent from form $a_name=$_POST['a_name']; $a_answer=$_POST['a_answer']; $datetime=date("d/m/y H:i:s"); // create date and time // Insert answer $sql2="INSERT INTO $tbl_name(question_id, a_id, a_name, a_answer, a_datetime)VALUES('$id', '$Max_id', '$a_name', '$a_answer', '$datetime')"; $result2=mysql_query($sql2); if($result2){ echo "Successful<BR>"; echo "<a href='view_topic.php?id=".$id."'>View your answer</a>"; // If added new answer, add value +1 in reply column $tbl_name2="forum_question"; $sql3="UPDATE $tbl_name2 SET reply='$Max_id' WHERE id='$id'"; $result3=mysql_query($sql3); $email_from = "forums@thenewme.co.za"; $email_to = "info@thenewme.co.za"; $email_subject = "The New Me - New Forum Answer"; $email_message = "A new answer to a forum topic has been posted on the Forum!\n"; $email_message .= "Check it out : http://www.thenewme.co.za/forum/main_forum.php"; $headers = 'From: '.$email_from."\r\n"; 'Reply-To: '.$email_from."\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $email_subject, $email_message, $headers); } else { echo "ERROR"; } mysql_close(); ?> view_topic : Code: [Select] <?php $tbl_name2="forum_answer"; // Switch to table "forum_answer" $sql2="SELECT * FROM $tbl_name2 WHERE question_id='$id'"; $result2=mysql_query($sql2); while($rows=mysql_fetch_array($result2)){ ?> <table width="400" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC"> <tr> <td><table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF"> <tr> <td bgcolor="#F8F7F1"><strong>ID</strong></td> <td bgcolor="#F8F7F1">:</td> <td bgcolor="#F8F7F1"><? echo $rows['a_id']; ?></td> </tr> <tr> <td width="18%" bgcolor="#F8F7F1"><strong>Name</strong></td> <td width="5%" bgcolor="#F8F7F1">:</td> <td width="77%" bgcolor="#F8F7F1"><? echo $rows['a_name']; ?></td> </tr> <tr> <td bgcolor="#F8F7F1"><strong>Answer</strong></td> <td bgcolor="#F8F7F1">:</td> <td bgcolor="#F8F7F1"><? echo $rows['a_answer']; ?></td> </tr> <tr> <td bgcolor="#F8F7F1"><strong>Date/Time</strong></td> <td bgcolor="#F8F7F1">:</td> <td bgcolor="#F8F7F1"><? echo $rows['a_datetime']; ?></td> </tr> </table></td> </tr> </table><br> <? } $sql3="SELECT view FROM $tbl_name WHERE id='$id'"; $result3=mysql_query($sql3); $rows=mysql_fetch_array($result3); $view=$rows['view']; // if have no counter value set counter = 1 if(empty($view)){ $view=1; $sql4="INSERT INTO $tbl_name(view) VALUES('$view') WHERE id='$id'"; $result4=mysql_query($sql4); } // count more value $addview=$view+1; $sql5="update $tbl_name set view='$addview' WHERE id='$id'"; $result5=mysql_query($sql5); mysql_close(); ?> the problem is. With add_answer, I am not able to insert an answer. This has worked for the very first question, but all subsequent questions, I am unable to add answers. It keeps telling me ERROR. This is where the live forum is : http://www.thenewme.co.za/forum/main_forum.php Can it be an issue with the field that gets autmatically incremented? i have echo'd the data which get entered in when someone types in an answer, and everything is perfect! Can anyone help me? Hello, i'm trying to server-side validate input from POST to insert it into mysql if the requirements for the insert are met. i was using jquery before but this isn't reliable at all, i want the data to get inserted into mysql only if the length is 19 chars and only if it starts with 3227580 the next 12 digits can be any number. So basically: IF chars=19 and data=3227580* insert into mysql -- else show error Thank you for help. I built a series of insertion forms to put entries into a mysql database. Everything is working fine, except that I just now realized my checkboxes don't put any entry in. It's just leaving it's respective smallint field as a default "0". Being new, I've must've overlooked how to handle these. The form's checkboxes have a bit of code in the value that remembers what users chose in case they have to backtrack and redo their form. How would I solve the problem and keep this code? Here's what all the checkboxes are written like: Code: [Select] <input type="checkbox" name="green_leaf" value="<?php if(isset($_POST['1'])) echo $_POST['1']; ?>" > green |