Is there a quick method to add a unique id to a php mysql upload- I have scrolled through these forums but was hoping there is a much simpler method to achieve my aim.
Essentially, I have an upload that works perfectly - and I am hoping to add a product code to each item that will be generated using the auto-incremented unique id field in mysql.
So far I have the following php:
<?php include 'dbc.php'; page_protect();
if(!checkAdmin()) {header("Location: login.php");
exit();
}
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$login_path = #ereg_replace('admin','',dirname($_SERVER['PHP_SELF']));
$path = rtrim($login_path, '/\\');
foreach($_GET as $key => $value) {
$get[$key] = filter($value);
}
foreach($_POST as $key => $value) {
$post[$key] = filter($value);
}
?>
<?php
if($_FILES['photo']) //check if we uploading a file
{
$target = "images/furnishings/";
$target = $target . basename( $_FILES['photo']['name']);
$title = mysql_real_escape_string($_POST['title']);
$desc = mysql_real_escape_string($_POST['desc']);
$price = mysql_real_escape_string($_POST['price']);
$pandp = mysql_real_escape_string($_POST['pandp']);
$pic = "images/furnishings/" .(mysql_real_escape_string($_FILES['photo']['name']));
$productcode = "FUR000" .(mysql_real_escape_string($_POST['id']));
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
mysql_query("INSERT INTO `furnishings` (`title`, `desc`, `price`, `pandp`, `photo`,`productcode`) VALUES ('$title', '$desc', '$price', '$pandp', '$pic', '$productcode')") ;
echo "The product has been added to the furnishings category";
}
else
{
echo "Please fill out the specifications and select the respective file to upload for the main image";
}
}
?>
And the following HTML:
<form enctype="multipart/form-data" action="addfurn.php" method="POST">
<table width="100%" border="2" cellpadding="5"class="myaccount">
<tr>
<td>Title: </td>
<td><input type="text" name="title" /></td>
</tr>
<tr>
<td>Description: </td>
<td><input type="text" name = "desc" /></td>
</tr>
<tr>
<td>Price: </td>
<td><input type="text" name = "price" /></td>
</tr>
<tr>
<td>P&P: </td>
<td><input type="text" name = "pandp" /></td>
</tr>
<tr>
<td>Main Image: </td>
<td><input type="file" name="photo" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" class="CMSbutton" value="Add" /></td>
</tr>
</table>
</form>
Now given everything works - the only "problem line" in the code is:
$productcode = "FUR000" .(mysql_real_escape_string($_POST['id']));
assuming that as the id hasnt yet been generated it cannot add it to the insert query - therefore the table in mysql simply returns FUR000 for each new item added.
Is there a way to amend this line to auto-increment in mysql in a similar fashion to the addition of new lines - or do I have to include a unique code for each item in my HTML table?
Any help much appreciated!
Thanks
JD
you need 2 queries for this.
first, insert your data without productcode.
next, get id using mysql_insert_id()
finally, create your productcode and update your table using this newly generated id
however, I see no point in such a field. Why not to create it on the fly?
You want to use uniqid, which generates unique ids. I'd recommend using it with more entropy to be on the safe side.
Related
I'm trying to put info I get from a form in html into a mysql database by way of php and do it all on the same page. My code so far is thus
<?php
require('conn.php');
if( isset($_POST['send'])){
$Product_Name = htmlspecialchars($_POST["product_name"]);
$Stock = htmlspecialchars($_POST["stock"]);
$Price = htmlspecialchars($_POST["price"]);
$insert = "INSERT INTO product (Product_Name, Stock, Price) VALUES ('$Product_Name','$Stock','$Price')";
if (mysqli_query($conn,$insert)){
echo "Values inserted!\n";
}
else {
echo "Error inserting values: " . mysqli_error($conn);
}
}
mysqli_close($conn);
?>
<html>
<body>
<form action="insert.php" method="post">
<table border="1">
<tr>
<td>Product Name</td>
<td align="center"><input type="text" name="product_name" size= "30" /></td>
</tr>
<tr>
<td>In Stock</td>
<td align="center"><input type="text" name ="stock" size="30"/></td>
</tr>
<tr>
<td>Price</td>
<td align="center"><input type="text" name="price" size="30"/></td>
</tr>
<tr>
<td>Submit</td>
<td align="center"><input type="submit" value="send"></td>
<tr>
However when I try and load the page its just comes up blank. It used to at least show the form before I added in the php code but I can't pin down what I broke. What do I need to change so that this puts the users data into the database?
Edit: changed code based upon Jeffry's catches
You're missing the name attribute in your submit button declaration.
update
<input type="submit" value="send">
to
<input type="submit" name = "send" value="send">
just quick check, you miss the closing ) in
$Product_Name = htmlspecialchars($_POST["product_name"];
i also think you need a dot to append the string
$insert = "INSERT INTO product (Product_Name, Stock, Price) VALUES ("$Product_Name","$Stock","$Price")";
and if your product name is a varchar, you might need to quote it
I am going to fetching table values in a html table along checkbox in each row and then inserting values in another database table from multi check boxes in php.
Only the values of checked boxes should be submitted to that table.
db name "laboratory":
test: fetching values.
package: inserting table.
view
Status
Active
Inactive
<?php
$conn=mysqli_connect("localhost","root","","laboratory") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$query="SELECT * FROM test";
$result=mysqli_query($conn,$query);
if ($result) {
while ($record=mysqli_fetch_array($result)) {
Please try to follow this code and implement in your program . Hope that this will cooperate you much
if(isset($_POST['name'])){
$name = $_POST['name'];
$status = $_POST['status'];
if(empty($name) || empty($status)){
echo "Field Must Not be empty";
} else{
$conn=new mysqli("localhost","root","","test");
if($conn){
$query = "SELECT * FROM userdata limit 5";
$stmt = $conn->query($query);
$val = '<form action="" method=""> ';
$val .= '<table> ';
if ($stmt) { ?>
<form action="" method="post">
<table>
<?php while ($result=$stmt->fetch_assoc()) { ?>
<tr>
<td><?php echo $result['post']; ?></td>
<td><input value="<?php echo $result['post']; ?>" type="checkbox" name="check[]" /></td>
</tr>
<?php } ?>
<tr>
<td>Actual Price </td>
<td>Discount</td>
<td>Final Price</td>
</tr>
<tr>
<td><input type="text" name="actual"/></td>
<td><input type="text" name="discount"/></td>
<td><input type="text" name="final"/></td>
</tr>
<tr>
<td>Description</td>
<td><textarea name="description" id="" cols="30" rows="10"></textarea></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
<td><input type="reset" value="Cancel" /></td>
</tr>
</table>
</form>
<?php }} }}?>
<?php
if(isset($_POST)){
echo "<pre>";
print_r($_POST);
echo "<pre>";
}
?>`enter code here`
First of all you have to decide that what are you using either mysqli or mysql, if you are using mysqli then you have to improve your code
$query="SELECT * FROM test";
$result=mysqli_query($conn,$query);
if ($result) {
while ($record=mysqli_fetch_array($result)) {
and when you want to insert the checked data will be inserted in package table. If package table in another database then you have to give us the full detail i mean tell us the database name of package table.
When I enter a video ID and the length of loan and then hit button FindDetails my form will show the name of the video, it's price to hire and the total cost of hire.
This causes two problems:
Submitting the form wipes video ID and the length of loan. Rats!
I cant adjust how many days I want to borrow a video and watch
the cost of the loan automatically adjust.
NB I include all php script as I will actually need to submit the form to write details of the reservation in a csv file. I'm not sure if this will stop a work around solution.
PHP:
<?php
if (isset($_POST['FindDetails'])) {
$ID = $_POST['videoID'];
$Days = $_POST['days'];
//Open the CSV file
$file_handle = fopen("video.csv", "r");
//loop until hit the last line feof)
while (!feof($file_handle))
{
//put data in each line [0],[1] etc into a variable.
$info = fgetcsv($file_handle);
// Check its the one we want.
if($info[0]==$_POST["videoID"])
{
$videoName = "$info[2]";
$videoCost ="$info[4]";
$costOfHire= $videoCost*$Days;
}
}
fclose($file_handle);
}
if (isset($_POST['submit'])) {
$ID = $_POST['videoID'];
$VideoName = $_POST['videoName'];
$VideoCost = $_POST['videoCost'];
$Days = $_POST['days'];
$Total = $_POST['total'];
$DateFrom = $_POST['date_from'];
$DateTo = $_POST['date_to'];
$StudentName = $_POST['studentName'];
//Saving loan details
$csv_file = 'loans.csv';
if (is_writable($csv_file)) {
if (!$csv_handle = fopen($csv_file,'a')) {
// this line is for troubleshooting
echo "<p>Cannot open file $csv_file</p>";
exit;
}
$csv_item = "\"$ID\",\"$VideoName\",\"$VideoCost\",\"$Days\",\"$Total\",\"$DateFrom\",\"$DateTo\",\"$StudentName\"\n";
if (is_writable($csv_file)) {
if (fwrite($csv_handle, $csv_item) === FALSE) {
//for testing
//echo "Cannot write to file";
exit; }
}
fclose($csv_handle);
}
}
if (isset($_POST['submit'])) {
echo "<p style='padding: .5em; border: 2px solid red;'>Thanks for booking the Video. Please collect from E24 on the date ordered.</p>";
}
?>
HTML:
Loans
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Enter the Video ID below
<table id="tables" class="form" style="width:100%;">
<tr>
<td>Video ID</td>
<td><input type="text" value="" name="videoID" id="videoID" placeholder= "Enter A Number between 1 and 8"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="FindDetails" id="FindDetails" value="Search Video" /></td>
</tr>
<tr>
<td>Video Name</td>
<td><input type="text" value="<?php echo (isset($videoName))?$videoName:'';?>" name="videoName" id="videoName"/></td>
</tr>
<tr>
<td>Video Rental Cost (per day)</td>
<td><input type="text" value="<?php echo (isset($videoCost))?$videoCost:'';?>" name="videoCost" id="videoCost"/></td>
</tr>
<tr><td></td><td></td></tr>
<tr>
<td>Number of days</td>
<td><input type="text" value="" name="days" id="days" placeholder= "Enter the number of days you wish to borrow the video for" /></td>
</tr>
<tr>
<td>Total cost</td>
<td><input type="text" value="<?php echo (isset($costOfHire))?$costOfHire:'';?>" name="total" id="total"/></td>
</tr>
Part 1
I assume the HTML and PHP portions presented are in the same file.
You use <?php echo (isset($costOfHire))?$costOfHire:'';?> for example to access variables set in the PHP code.
Why not use <?php echo (isset($ID))?$ID:'';?> to simply recycle the submitted video ID? Then do the same for the length of loan variable.
Part 2
Here is one way live loan cost calculation could work. The javascript will go between <script></script> tags in the <head> of the document.
function updateLoanCost(loanPeriod) {
var costDisplayEl = document.getElementById("loanCostDisplay");
var dollarsPerDay = 3;
costDisplayEl.innerText = "$" + loanPeriod * dollarsPerDay;
}
Enter a number of days <br />
<input type = "number" id = "test" onchange = "updateLoanCost(this.value);"/>
<div id = "loanCostDisplay"></div>
I have been working on a project and i am at the final stages of the project. My problem is whenever i try to update data in my database table into returns a blank screen with no error messages. Please find the php script and html form (the form responsible for updating the database table) below, i have divided it into about four sections:
Thanks in advance
Update Form:
<a name="inventoryEditForm" id="inventoryEditForm"></a>
<h3>↓Add New Question Form↓</h3>
<form action="inventory_edit.php" enctype="multipart/from-data" name="myForm" id="myForm" method="post">
<table width="80%" border="0" cellspacing="3" cellpadding="7">
<tr>
<td width="20%"> </td>
<td width="80%"> </td>
</tr>
<tr>
<td>Question</td>
<td><textarea rows="" name="question" cols=""><?php echo $question; ?></textarea></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Venue</td>
<td><input type="text" name="venue" maxlength="50" value="<?php echo $venue; ?>"></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Date</td>
<td><input type="date" name="questiondate" value="<?php echo $date; ?>"></td>
</tr>
</table>
<br>
<input name="thisID" type="hidden" value="<?php echo $targetID; ?>"/>
<input type="submit" name="submit" value="Update Question">
<input type="reset" name="clear" value="Clear Form">
</form>
PHP Script:
<?php
//Error reporting due to long script
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php
error_reporting(E_PARSE);
//Update question table
If (isset($_POST['question'])) {
$id = mysqli_real_escape_string($link, $_POST['thisID']);
$question = mysqli_real_escape_string($link, $_POST['question']);
$venue = mysqli_real_escape_string($link, $_POST['venue']);
$date = mysqli_real_escape_string($link, $_POST['questiondate']);
//Update question in the table
$sql = mysqli_query($link, "UPDATE DebateQuestion SET question='$question',venue='$venue',date='$date' WHERE qQuestionNo='$id'LIMIT 1") or die(mysql_error());
header("location: inventory.php");
exit();
}
?>
<?php
error_reporting(E_PARSE);
//Gather this questions full information and insert automatically into the edit form
if (isset($_GET['qid'])) {
$targetID = $_GET['qid'];
$sql = mysqli_query($link, "SELECT * FROM DebateQuestion WHERE qQuestionNo='$targetID'LIMIT 1") or die(mysql_error());
$questionCount = mysqli_num_rows($sql); // count the output amount
if ($questionCount > 0) {
while ($row = mysqli_fetch_array($sql, MYSQLI_ASSOC)) {
$id = $row["qQuestionNo"];
$question = $row["qQuestion"];
$venue = $row["qDebateVenue"];
$date = strftime("%b %d, %Y", strtotime($row["qDate"]));
}
} else {
echo "Oops, no questions like that exists. Check <a href='inventory.php'>inventory</a>again";
exit();
}
}
?>
In your update query you have the data column without using ` back ticks , date is also a mysql's function try to wrap up your column names with back ticks if you are not sure whether they conflict with mysql's reserved keywords
$sql = mysqli_query($link,"UPDATE DebateQuestion SET
`question`='$question',`venue`='$venue',`date`='$date'
WHERE qQuestionNo='$id'LIMIT 1")
"SELECT * FROM DebateQuestion WHERE qQuestionNo='$targetID'LIMIT 1"
Here is qQuestionNo column a string type?if not remove quotes around $targetID.
Note : I have not tested the code - just read it on screen.
I've never seen an IF statement capitalized before :
If (isset($_POST['question'])) {
I'd guess this makes a difference however.
There's lots of other weird things going on in your files, but none that should give you white screen. Try lowercase 'I' in your if statement first.
ALSO - re: the UPDATE statement, you are missing a space between the $id and the LIMIT :
**qQuestionNo='$id'LIMIT 1**
I have an upload to mysql script in php that works perfectly for a property website - inserting all relevant fields and the main image.
The problem is however, this image is used in a slideshow which identifies the thumbnail as xxxxxt.png where the main image is xxxxx.png for example.
My php code is:
<?php include 'dbc.php'; page_protect();
if(!checkAdmin()) {header("Location: login.php");
exit();
}
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$login_path = #ereg_replace('admin','',dirname($_SERVER['PHP_SELF']));
$path = rtrim($login_path, '/\\');
foreach($_GET as $key => $value) {
$get[$key] = filter($value);
}
foreach($_POST as $key => $value) {
$post[$key] = filter($value);
}
$uniqid = md5(uniqid(mt_rand()));
?>
<?php
if($_FILES['photo']) //check if we uploading a file
{
$target = "images/properties/";
$target = $target . basename( $_FILES['photo']['name']);
$title = mysql_real_escape_string($_POST['title']);
$desc = mysql_real_escape_string($_POST['desc']);
$extra = mysql_real_escape_string($_POST['extra']);
$postcode = mysql_real_escape_string($_POST['postcode']);
$price = mysql_real_escape_string($_POST['price']);
$pandp = mysql_real_escape_string($_POST['pandp']);
$pic = "images/properties/" .(mysql_real_escape_string($_FILES['photo']['name']));
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
mysql_query("INSERT INTO `furnishings` (`title`, `postcode`, `desc`, `extra`, `productcode`, `price`, `status`, `pandp`, `photo`) VALUES ('$title', '$postcode', '$desc', '$extra', '" . $uniqid . "', '$price', 'tolet.png', '$pandp', '$pic' )") ;
echo "The property has been added to the lettings portfolio";
}
else
{
echo "Error uploading new property - please ensure all the fields are correctly entered and the file is an image";
}
}
?>
The html code for the upload form is:
<form enctype="multipart/form-data" action="addlet.php" method="POST">
<table width="600px" border="2" cellpadding="5"class="myaccount">
<tr>
<td width="135">Title: </td>
<td width="427"><input name="title" type="text" size="40"/></td>
</tr>
<tr>
<td>Description: </td>
<td><textarea name = "desc" rows="3" cols="40"></textarea></td>
</tr>
<tr>
<td>Property Features: </td>
<td><textarea name = "extra" rows="3" cols="40"></textarea></td>
</tr>
<tr>
<td>Postcode: </td>
<td><input name = "postcode" type="text" size="40" /></td>
</tr>
<tr>
<td>Price per week (£): </td>
<td><input name = "price" type="text" size="40" /></td>
</tr>
<tr>
<td>Furnished/Unfurnished: </td>
<td><input name = "pandp" type="text" size="40" /></td>
</tr>
<tr>
<td>Main Image: </td>
<td><input type="file" name="photo" class="forms" /></td>
</tr> </table></p>
<p> <input type="submit" class="CMSbutton" value="Add" /></p>
</form>
Is there a simple way to add an extra line of code which will insert two images into the desired target on the server, (images/properties/) - one the original name of the image, and one the thumbnail version (with a "t" on the end of the image name).
As they are both reasonably small I am not fussed about resizing the thumbnail as the code is pretty much done I dont want to have to rebuild everything!
Any help much appreciated
Thanks
JD
If your image file is being moved into place successfully, I would take this strategy: create columns is_uploaded, is_thumb_created and is_image_created in your database table. Upon successful upload and move, set the first one.
Then run a cron or other background system that generates a 'main' and a 'thumb' view from the uploaded image (bearing in mind that the uploaded image may be way too large for an ordinary screen-size picture). Upon the successful generation of these images, the relevant columns can be set as 'done', and the row remains non-live until this happens.
This approach is a great deal more scalable, incidentally, since it is not clogging up your web request with expensive image processing.