Inserting Image to MySQL Database - php

I am working on a solution that will help me submit specific images from a list of images to a MySQL Database.
My database consists of the following:
Database
id(INT)
photo(BLOB)
caption(VAR)
Code
I am first retreiving images from a list and giving them each a submit button.
foreach ($media->data as $data) {
echo $pictureImage = "<img src=\"{$data->images->thumbnail->url}\">";
echo "<form action='tag.php' method='post'>";
echo "<input type='submit' name='submit' value='Click Me'>";
echo "</form>";
}
$pictureImage parses the data URL and then puts it into an actual image.
The submit button is below each of those images.
I am then making it so that when the submit button is pressed, it is added to the database.
if(isset($_POST['submit'])) {
//Database code would be above the following
$sql="INSERT INTO $usertable (image) VALUES ('$pictureImage')";
}
Problem
I am running into an issue where the last image in my list is the one being submitted to the database, rather than the image with the corresponding submit button. How do I make it so that it is grabbing the photo with the corresponding submit button?
Any help would be appreciated greatly.

You need to include any identifier to the image inside the form in order to store it.
For example you can try building the forms like this:
foreach ($media->data as $data) {
echo $pictureImage = "<img src=\"{$data->images->thumbnail->url}\">";
echo "<form action='tag.php' method='post'>";
echo "<input type='hidden' name='imageid' value='{$data->images->thumbnail->url}'>";
echo "<input type='submit' name='submit' value='Click Me'>";
echo "</form>";
}
And when you want to store the image on the form submit you can actually pick up the identifier of the image (in this case I used the URL you posted):
if(isset($_POST['submit'])) {
$sql="INSERT INTO $usertable (image) VALUES ('$_POST[imageid]')";
}

You are not posting any data when you click on your submit buttons.. i would suggest that for each form you would have a hidden field with the url of the image.
something like this:
<form action='tag.php' method='post'>
<input type="hidden" value="{$data->images->thumbnail->url}" name="pic"/>
<input type='submit' name='submit' value='Click Me'>
</form>

Problem
foreach ($media->data as $data) {
echo $pictureImage = "<img src=\"{$data->images->thumbnail->url}\">";
echo "<form action='tag.php' method='post'>";
echo "<input type='submit' name='submit' value='Click Me'>";
echo "</form>";
}
By the time this loop is done, you will have the last image in the loop as the value for $pictureImage.
So when it gets to this point, you're $pictureImage is still... the last image.
if(isset($_POST['submit'])) {
//Database code would be above the following
$sql="INSERT INTO $usertable (image) VALUES ('$pictureImage')";
}
Solution
I'm not exactly sure what data value you want to save because right now it looks like the whole tag. But whatever it is, you need to put it into a form field first ...
foreach ($media->data as $data) {
..
echo "<form action='tag.php' method='post'>";
echo "<input type='hidden' name='imageurl' value='<img src=\"{$data->images->thumbnail->url}\">' />";
..
}
and then retrieve it in the POST part of your script:
if(isset($_POST['submit'])) {
$imageurl = $_POST['imageurl'];
//Database code would be above the following
$sql="INSERT INTO $usertable (image) VALUES ('$imageUrl')";
}
This way, it won't always be the last value in your list, rather, it will be the one you selected.

Related

Retrieve DIV-content inside a Form

I have been searching for help from various forums and similar posts, but without any progress.
I have three pages, one that lets me insert information about projects into my database, a second that show the images and names of every project in the database, and a third page which I want to have a function that shows the image and name of the selected project in the second page.
Code on the second page(dashboardadmin.php):
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$conn = mysqli_connect("localhost","root","","wildfire");
if(mysqli_connect_errno())
{
echo mysqli_connect_error();
}
$sql= "SELECT pid, project_name, image, image_type FROM project";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
echo "<form action='omprojekt.php' method='post'>
<div id='comp' name='comp'>
<img src=pic.php?pid=".$row['pid']." width=100xp height=100xp/>"." ".$row['project_name']."
</div>
<input type='submit' name='submit' value='Choose' />
</form>";
}
}
else {
echo "0 results";
}
mysqli_close($conn);
?>
Code on the third page (omprojekt.php):
<?php
/* Tried both of the $val variables but of course only one at a time. This is only to show you what I have tried. */
$val = isset($_POST['comp']) ? $_POST['comp'] : '';
$val = $_POST['comp'];
if(isset($_POST['submit'])){
echo "$val";
}
?>
In the last code you can see that I have two $val variables, but I have only used one of them at a time in my codes. The purpose of showing both of them here is to show you that I have tried both of them.
What I want to do is to make the third page show the image and name of the selected project in the second page. As you see, I have tried to retrieve the content from the DIV using the same "name". The problem is that the third page(omprojekt.php) doesn't show any content at all, and not even any errors.
You're expecting the div to submit like an input, but it won't, because it's not an input. So put it in an input.
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
// Don't use and id attribute because you're in a loop and you might have multiple id's with the same value.
echo "<form action='omprojekt.php' method='post'>
<div>
<img src=pic.php?pid=".$row['pid']." width=100xp height=100xp/>"." ".$row['project_name']."
</div>
<input type='hidden' name='pid' value='".$row['pid']."'>
<input type='hidden' name='project_name' value='".$row['project_name']."'>
<input type='submit' name='submit' value='Choose' />
</form>";
}
}
Then on the next page,
$val = (isset($_POST['pid']) && isset($_POST['project_name'])) ?
"<img src=pic.php?pid={$_POST['pid']} width=100xp height=100xp/> {$_POST['project_name']}" : '';
For the sake of completeness, there are a few other things wrong with your code.
1) The width and height attributes on the iamge should have quotes, and do not accept "px", they are just numbers. If you want to use "px" you should use style instead. <img src='' style='width:20px; height:20px;' />
2) You should be escaping user input before running it through your query.
Data will only be sent from a <form> to the action script if it exists in an <input...> HTML tag. You cannot pick data out of randon <DIV> tags etc.
So you could do this by using a hidden input field like this ( this is only one way )
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
echo "<form action='omprojekt.php' method='post'>
<div>
<img src=pic.php?pid=".$row['pid'] .
" style="width:100px;height:100px" /> " .
$row['project_name']."
</div>
<input type='hidden' name='comp' value='" . $row['pid'] . "' />
<input type='submit' name='submit' value='Choose' />
</form>";
}
}
Now when you get to omprojekt.php the $_POST['comp'] variable will exist.
You can have as many hidden input fields as you like so if you want to pass the project_name as well just add another hidden field.

Send column name from button

I have made a php page. On which I am displaying table 'prod' from my data base.
each row is displayed nicely. Today i tried to add a button named 'rate' at the end of each row of my table. which I did successfully. Now I want to send the the value of the first column of that row to another php page when that button is clicked. I am stuck that how to do so? can you help please ??
I know i have to use the method post in my form and i have to use $_post[that value] on the other php page to inculcate the value for further function.
I just need to ask that where to add the value of my first column in the button line. so that onclick it can send that value. I hope I am clear over this. Thank You very much for help :)
<?php
include("connection.php");
$query = "select * from prod";
$res = oci_parse($conn,$query);
usleep(100);
if (oci_execute($res)){
usleep(100);
print "<TABLE border \"1\">";
$first = 0;
while ($row = #oci_fetch_assoc($res)){
if (!$first){
$first = 1;
print "<TR><TH>";
print implode("</TH><TH>",array_keys($row));
print "</TH></TR>\n";
}
print "<TR><TD>";
print #implode("</TD><TD>",array_values($row));
print "</TD></TR>\n";
echo "<td><form action='detailform.php' method='POST'><input type='submit' name='submit-btn' value='Rate'/></form></td></tr>";
}
print "</TABLE>";
}
?>
you have to add inputs in your form whatever kind u prefer
echo "<td>
<form action='detailform.php' method='POST'>
<input type='hidden' name='your_val_key' value='".$row[your_val_key_in_query]."'> <!-- input hidden, change to text 4 debug -->
<input type='submit' name='submit-btn' value='Rate'/>
</form>
</td></tr>";
and than, in your detailform.php u can get the val with
echo $_POST["your_val_key"];
if u are not sure how much data u send or somthing, try this and u get the full data:
echo "<pre>".print_r($_POST,true)."</pre>";
BTW: why are u mixing print and echo?
Use hidden input
echo "<td><form action='detailform.php' method='POST'><input type='hidden' name='col-name' value='you-col-value'><input type='submit' name='submit-btn' value='Rate'/></form></td></tr>";

onclick action not working as intended with radio buttons

For the last 4 hours I've been struggling to get something to work. I checked SO and other sources but couldn't find anything related to the subject. Here is the code:
<?php
$email=$_SESSION['email'];
$query1="SELECT * FROM oferte WHERE email='$email'";
$rez2=mysql_query($query1) or die (mysql_error());
if (mysql_num_rows($rez2)>0)
{
while ($oferta = mysql_fetch_assoc($rez2))
{
$id=$oferta['id_oferta'];
echo "<input type='radio' name='selectie' value='$id' id='$id'> <a href='oferta.php?id={$oferta['id_oferta']}'>{$oferta['denumire_locatie']}</a>";
echo "</br>";
}
echo "</br>";
//echo "<input type=\"button\" id=\"cauta\" value=\"Vizualizeaza\" onclick=\"window.location.href='oferta.php?id={$oferta['id_oferta']}'\" />";
//echo " <input type=\"button\" id=\"cauta\"value=\"Modifica\" onclick=\"window.location.href='modifica.php?id={$oferta['id_oferta']}'\" />";
echo " <input type=\"button\" id=\"sterge\" value=\"Sterge\" onclick=\"window.location.href='delete.php?id=$id'\" />";
echo "</form>";
echo "</div>";
}
else
{
}
?>
The while drags all of the user's entries from the database and creates a radio button for each one of them with the value and id (because I don't really know which one is needed) equal to the entry's id from the db. I echoed that out and the id is displayed as it should so no problems there.
The delete script works ok as well so I won't attach it unless you tell me to. All good, no errors, until I try to delete an entry. Whatever I choose from the list of entries, it will always delete the last one. Note that I have two other inputs echoed out, those will be the "view" and "modify" buttons for the entry.
I really hope this is not JavaScript related because I have no clue of JS. I think this will be of major help to others having this problem. Please let me know if I need to edit my question before downrating. Thanks!
After edit:
This is the delete script, which as I said earlier works fine.
<?php
if (isset($_GET['id']))
{
$id = $_GET['id'];
echo $id;
require_once('mysql_connect.php');
$query = "DELETE FROM oferte Where id_oferta = '$id'";
mysql_query($query) or die(mysql_error());
//header('Location: oferte.php');
}
else
{
//header('Location: oferte.php');
}
?>
The session is started as well, like this:
<?php
session_start();
?>
The reason the last $id is deleted is because this line is outside/after the while loop:
echo " <input type=\"button\" id=\"sterge\" value=\"Sterge\" onclick=\"window.location.href='delete.php?id=$id'\" />";
You want to move this line inside the loop so that you have a button that executes delete for each radio button.
Update:
To have links to delete and
echo "<input type='radio' name='selectie' value='$id' id='$id'> ";
echo "<a href='oferta.php?id={$oferta['id_oferta']}'>{$oferta['denumire_locatie']}</a> ";
echo "<a href='delete.php?id=$id'>delete</a>";
Also I do not think the radio button is needed here at all since you are not really doing anything with it. You could simply echo out the value of your choice and have these links as follows:
echo $oferta['denumire_locatie'] . ' '; // replace $oferta['denumire_locatie'] with something of your choice
echo "<a href='oferta.php?id={$oferta['id_oferta']}'>{$oferta['denumire_locatie']}</a> ";
echo "<a href='delete.php?id=$id'>delete</a>";
echo "<br />";
The problem, in this case, is JavaScript related, yes. What I recommend you to do is to simply add a Remove link for each item.
echo "<a href='oferta.php?id={$oferta['id_oferta']}'>{$oferta['denumire_locatie']}</a>";
echo " - <a href='delete.php?id={$oferta['id_oferta']}'>Remove</a>";
echo "</br>";
Your $id is outside your while() loop.
The last one is getting deleted because the $id has the last one's value when the loops is exited.
Include all your code :
echo "</br>";
//echo "<input type=\"button\" id=\"cauta\" value=\"Vizualizeaza\" onclick=\"window.location.href='oferta.php?id={$oferta['id_oferta']}'\" />";
//echo " <input type=\"button\" id=\"cauta\"value=\"Modifica\" onclick=\"window.location.href='modifica.php?id={$oferta['id_oferta']}'\" />";
echo " <input type=\"button\" id=\"sterge\" value=\"Sterge\" onclick=\"window.location.href='delete.php?id=$id'\" />";
Inside your while loop.
When the rendered html reaches the browser, it will be something like this:
<input type='radio' name='selectie' value='1' id='1'> <a href='oferta.php?id=1'>TEXT</a>
<input type='radio' name='selectie' value='2' id='2'> <a href='oferta.php?id=2'>TEXT</a>
<input type='radio' name='selectie' value='3' id='3'> <a href='oferta.php?id=3'>TEXT</a>
<input type='radio' name='selectie' value='4' id='4'> <a href='oferta.php?id=4'>TEXT</a>
<br/>
<input type="button" id="sterge" value="Sterge" onclick="window.location.href='delete.php?id=5'" />
With this markup you won't be able to accomplish what you want without using javascript to update the onclick attribute whenever you select a radio button.
On the other hand, instead of using the client-side onclick event you can use the button's default behaviour, which is to submit the form.
You'll just have to set the action attribute:
<form method="post" action="http://myurl.php">
and write the myurl.php page which will just read the posted variable $_POST['selectie'] and call the delete method with the posted id.

Endless Query/Loop in PHP?

Hello I'm querying a database of names by the first letter of the last name. However when I excute the query and print the results, the first name prints over and over again when in reality theres more than one name to print out. here is what I have so far. the data passed in is a letter in which it supppose to gather all the last names with that beginning letter. what I'm I doing wrong that can cause this infinite loop?
function displayprofs()
{
print"<div>";
print "<p><a href = '$_SERVER[PHP_SELF]'>return to start</a>\n";
$abc=($_POST['abc']);
print"$abc";
$db = adodbConnect();
$query="Select * FROM Category WHERE Description LIKE '$abc%'";
$result=$db->Execute($query);
$row=$result->FetchRow();
while($row)
{
$name= $row['Description'];
print "<form method='post' enctype='multipart/form-data' action='$_SERVER[PHP_SELF]'>\n";
print"<input type='hidden' name='profy' value='$name'>";
print"<p>$name<input type='submit' name='add' value ='Submit'/></p>\n"; //submit button
print"</form>\n";
//break;
}
print"</div>";
}
You fetch $row once and then start while loop with its condition always true. Missing $row=$result->FetchRow(); inside the while block.
Replace while($row) with while($row=$result->FetchRow())
and remove $row=$result->FetchRow(); you've written before starting while
Since you have while($row) you will iterate over the same row over and over again. Change to while($row=$result->FetchRow()) instead and remove the previous fetch or keep as is and put $row=$result->FetchRow(); in the end of the while block.
Solution 1:
while($row=$result->FetchRow())
{
$name= $row['Description'];
print "<form method='post' enctype='multipart/form-data' action='$_SERVER[PHP_SELF]'>\n";
print"<input type='hidden' name='profy' value='$name'>";
print"<p>$name<input type='submit' name='add' value ='Submit'/></p>\n"; //submit button
print"</form>\n";
}
Solution 2:
$row=$result->FetchRow();
while($row)
{
$name= $row['Description'];
print "<form method='post' enctype='multipart/form-data' action='$_SERVER[PHP_SELF]'>\n";
print"<input type='hidden' name='profy' value='$name'>";
print"<p>$name<input type='submit' name='add' value ='Submit'/></p>\n"; //submit button
print"</form>\n";
$row=$result->FetchRow();
}
By now, you know the while($row) bit is probably a mistake. Just to avoid you having to post a second question in a minute: This isn't the best of ideas:
print "<form method='post' enctype='multipart/form-data' action='$_SERVER[PHP_SELF]'>\n";
Perhaps consider writing this as either:
print "<form method='post' enctype='multipart/form-data' action='{$_SERVER['PHP_SELF']}'>\n";
or:
print "<form method='post' enctype='multipart/form-data' action='".$_SERVER[PHP_SELF]."'>\n";

Passing data between PHP webpages from a dynamically generated list

I have a PHP code which generates a dynamic list inside a form like the following, note that the list is built dynamically from database:
echo '<form name="List" action="checkList.php" method="post">';
while($rows=mysqli_fetch_array($sql))
{
echo "<input type='password' name='code' id='code'>";
echo "<input type='hidden' name='SessionID' id='SessionID' value='$rows[0]' />";
echo "<input type='submit' value='Take Survey'>";
}
What I need is to POST the data corresponding to the user choice when he clicks on the button for that row to another page.
If we use hyperlinks with query strings there will be no problem as I'll receive the data from the other page using a GET request and the hyperlinks would be static when showed to the user.
Also I need to obtain the user input from a textbox which is only possible with POST request.
Simply from the other page (checkList.php) I need these data for further processing:
$SessionID=$_POST['SessionID'];
$Code=$_POST['code'];
As I have a while loop that generates the fields, I always receive the last entry form the database and not the one corresponding to the line (row) that the user chosed from the LIST.
I'm going to recommend that you clean up the names of variables so that your code can
at least tell us what it's supposed to do. It should be rare that someone looks at your code
and has a lot of trouble trying to see what you're trying to accomplish :P, ESPECIALLY when you need help with something ;]. I'm going to try some things and hope that it makes doing what you want easier to comprehend and perhaps get you your answer.
It's good to try your best to not echo large amounts of HTML unnecessarily within a script , so firstly I'm going to remove the
echos from where they are not necessary.
Secondly, I'm going to use a mysql function that returns an easier to process result.
$user = mysqli_fetch_assoc($sql)
Third, I don't know if form having a name actually does anything for the backend or frontend of php, so I'm
just going to remove some of the extra crust that you have floating around that is either invalid HTML
or just doesn't add any value to what you're trying to do as you've presented it to us.
And yes, we "note" that you're building something from the database because the code looks like it does =P.
I'm also sooo sad seeing no recommendations from the other answers in regard to coding style or anything in regard to echoing html like this :(.
<?php while($user = mysqli_fetch_assoc($sql)): ?>
<form action="checkList.php" method="post">
<input type='password' name='code' value='<?php echo $user['code'] ?>' />
<input type='hidden' name='SessionID' value='<?php echo $user['id'] //Whatever you named the field that goes here ?>' />
<input type='submit' value='Take Survey' />
</form>
<?php endwhile; ?>
i not sure this is correct
echo '<form name="List" method="post">';
while($rows=mysqli_fetch_array($result))
{
echo "<input type='password' name='code' id='code'>";
echo "<input type='button' value='Take Survey' onclick=show($rows[0])>";
echo "<br>";
}
and javascript
<script>
function show(id)
{
alert(id);
window.location="checkList.php?id="+id;
}
</script>
On checkList.php
$id=$_GET['id'];
echo $id;
You can just check in checkList.php whether $_POST['code'] exists and if exists retrieve $_POST['SessionID'] which will be generated from database. But one thing, if You have all hidden fields in one form, they all will be sent, so You need to think how to correct that - maybe seperate forms for each hidden field, submit button and maybe other POST fields.
And afterwards, You will be able to get data in the way You need - $SessionID=$_POST['SessionID'];
I suppose it is the easiest way to solve that.
You can try something like this:
while($rows=mysqli_fetch_array($sql))
{
$index = 1;
echo "<input type='password' name='code' id='code'>";
//Attach $index with SessionID
echo "<input type='hidden' name='SessionID_$index' id='SessionID' value='$rows[0]' />";
echo "<input type='submit' value='Take Survey'>";
}
On checkList.php
<?php
$num = explode('_', $_POST['SessionID']);
$num = $num[1];
//in $num you will get the number of row where you can perform action
?>
$form = 1;
while($rows=mysqli_fetch_array($sql))
{
echo '<form name="List_$form" action="checkList.php" method="post">';
echo "<input type='password' name='code' id='code_$form'>";
echo "<input type='hidden' name='SessionID' id='SessionID_$form' value='$rows[0]' />";
echo "<input type='submit' value='Take Survey'>";
echo '</form>';
$form++;
}

Categories