So I've created this function where you upload an image to the server together with some information.
The text information is saved to a database while the image is saved to a folder.
Then I echo out the image together with the information that was stored in the database.
But I want to enchance it some by adding a rating system.
The rating system that I have created store the stastistics inside a txt-file.
What I need help with is to swap the saving with statistics from the txt-file and store it inside the database instead.
This is how I echo out the image, along with the information and star function:
<?php
//Sortering
$order = "";
if(isset($_GET['order'])){
if($_GET['order'] == "date"){
$order = " ORDER BY date DESC";
}
}
if(isset($_GET['order'])){
if($_GET['order'] == "uppladdare"){
$order = " ORDER BY uppladdare";
}
}
//Database connection
$dbcon = mysqli_connect("");
$selectall = "SELECT * FROM mountains $order";
$result = mysqli_query($dbcon, $selectall);
while($row = mysqli_fetch_array($result)){
$information = ' Titel: ' . $row['titel'] . ' Uppladdare: ' . $row['uppladdare'] . ' Filnamn: ' . $row['filname'] . ' History: ' .$row['History'] . ' Datum: ' . $row['date'];
//Print out correct information to the uploaded image
echo "<br>";
echo "Title: " . $row['titel'] . "<br>";
echo "Uploader: " . $row['uppladdare'] . "<br>";
echo "Imagename: " . $row['filname'] . "<br>";
echo "History: " . $row['History'] . "<br>";
echo "Date: " . $row['date'] . "<br>";
echo "Image:";
echo "<br>";
echo "<form name='rating' id='rating'>
<div id='rating-area' class='shadow'>
<img src='stjärna.png' id='thumb1' data-value='1' />
<img src='stjärna.png' id='thumb2' data-value='2' />
<img src='stjärna.png' id='thumb3' data-value='3' />
<img src='stjärna.png' id='thumb4' data-value='4' />
<img src='stjärna.png' id='thumb5' data-value='5' />
</div>
</form>";
?>
<script>
jQuery('div#rating-area img').click(function(e){
var val = jQuery(this).data('value') ;
console.log(val) ;
jQuery.post('post.php',{ rating : val },function(data,status){
console.log('data:'+data+'/status'+status) ;
}) ;
}) ;
</script>
<script>
$(document).ready(function(){
setInterval(function(){
$('#resultat').load('ajax.php');
},500);
});
</script>
<?php
$original = $row['filname'];
echo "<a class='fancybox' rel='massoravbilder' href='bilder/$original'> <img src='bilder/thumb_" . $row['filname'] . "' alt='$information' /></a>" . "<br>";
}
?>
<script>
jQuery('div#rating-area img').click(function(e){
var val = jQuery(this).data('value') ;
console.log(val) ;
jQuery.post('post.php',{ rating : val },function(data,status){
console.log('data:'+data+'/status'+status) ;
}) ;
}) ;
</script>
Im still quite a beginner so I would appreciate if anyone could show me an easy way to solve this. Prefer it to be simple, like without restrictions when it comes to the vote.
Just upload each rate-onclick and echo the average of all the votes right beneath the stars.
Notes: The rating system works fine when just using textfile. ajax.php is the calculation master behind the function. And post.php sends the rating statistics to the tex-file.
You should do something like this. I don't know if fields exist but it's the way to follow. I hope it's give you an idea.
In your form
//...
while($row = mysqli_fetch_array($result)){
$information = ' Titel: ' . $row['titel'] . ' Uppladdare: ' . $row['uppladdare'] . ' Filnamn: ' . $row['filname'] . ' History: ' .$row['History'] . ' Datum: ' . $row['date'];
//Print out correct information to the uploaded image
echo "<br>";
echo "Title: " . $row['titel'] . "<br>";
echo "Uploader: " . $row['uppladdare'] . "<br>";
echo "Imagename: " . $row['filname'] . "<br>";
echo "History: " . $row['History'] . "<br>";
echo "Date: " . $row['date'] . "<br>";
echo "Image:";
echo "<br>";
// Add the input with image id value (I suppose it exist)
echo "<form name='rating' id='rating'>
<div id='rating-area' class='shadow'>
<input type='hidden' name= 'image_id' value = $row[image_id]>
<img src='stjärna.png' id='thumb1' data-value='1' />
<img src='stjärna.png' id='thumb2' data-value='2' />
<img src='stjärna.png' id='thumb3' data-value='3' />
<img src='stjärna.png' id='thumb4' data-value='4' />
<img src='stjärna.png' id='thumb5' data-value='5' />
</div>
</form>";
Ajax
<script>
jQuery('div#rating-area img').click(function(e){
// serialize the form and retrieve all value in PHP with $_POST['theNameOfInput']
jQuery.post('post.php',{ form : $(this).serialize() },function(data,status){
console.log('data:'+data+'/status'+status) ;
}) ;
}) ;
</script>
post.php
<?php
$imageId = (int) $_POST['image_id'];
// ... Your database treatments
$sql = "UPDATE image SET image_rating = image_rating + 1 WHERE image_id = $imageId";
//... Your code
Related
I have a database with some record which i output on my page using php. This all works fine but i want to be able to edit the outputted information using the toggle functionality. So basicly i output text when a button edit is clicked i want to toggle that specific table and show the information once more but then in an input form.
foreach( $result as $row2 )
$div = $row2['id'] ;
echo "<div id='d$div; '><table ><tr><td>" . 'Categorie: ' . '</td><td> ' . $row2['name'] . '</td></tr>'
. '<tr><td>' . 'Omschrijving: ' . '</td><td>' . $row2['comments'] . '</td></tr> . '<tr><td>' . '<button id="e1">' . 'Edit' . '</button>' . '</td></tr>' . ' </table><hr>'; } ?></p>
If I would then would then echo everything out again using <form> input fields and use as div id f$div every record would get its unique id.
foreach( $result as $row2 )
$di = $row2['id'] ;
echo "<div id='f$di; '><table ><tr><td>" . 'Categorie: ' . '</td><td> ' . $row2['name'] . '</td></tr>'
. '<tr><td>' . 'Omschrijving: ' . '</td><td>' . $row2['comments'] . '</td></tr> . '<tr><td>' . '<button id="e2">' . 'Safe' . '</button>' . '</td></tr>' . ' </table><hr>'; } ?></p>
Then I would toggle it but I don't have the ids as they still have to be generated. How would I go about this...same would go for the click function but I can generate an id for these in the same way.
<script>
$('#e1,#e2').click(function () {
$('#d?,#f?').toggle();
})
</script>
You can do this with javascript, too. This is one example. You can even use AJAX to update, otherwise you can update the data in database and come back to the same page.
<?php
foreach($result as $row2) {
$div = $row2['id'];
echo "<div id='d$div'><table ><tr><td>" . "Categorie: " . "</td><td> " . $row2["name"] . "</td></tr>" . "<tr><td>" . "Omschrijving: " . "</td><td>" . $row2["comments"] . "</td></tr>" . "<tr><td>" . "<button id=e$div onclick='makeForm(\"$div\",\"d$div\",\"$row2[name]\",\"$row2[comments]\")';>" . "Edit" . "</button>" . "</td></tr>" . "</table><hr></div>\n";
}
?>
<script>
function makeForm(id,mydiv,category,comment){
var div = document.getElementById(mydiv);
var divHTML = "<form action='update.php' method='POST'><table> <tr><td>Categorie: </td> <td><input type='text' name='cat_" +id+ "' value='"+category + "' /></td></tr> <tr> <td>Omschrijving:</td> <td><input type='text' name='comment_" +id+ "' value='"+comment+"' /></td></tr> <tr><td> <input type='submit' value='Safe'></td><td><button onclick='removeForm(\""+id+"\",\""+mydiv+"\",\""+category +"\",\" "+comment+"\" ); return false;'>Cancel</button></td></tr></table> </form><hr>";
div.innerHTML = divHTML;
}
function removeForm(id,mydiv,category,comment){
var div = document.getElementById(mydiv);
var divHTML = "<table> <tr><td>Categorie: </td> <td>"+category + "</td></tr> <tr> <td>Omschrijving:</td> <td>"+comment+"</td></tr> <tr><td><button onclick='makeForm(\""+id+"\",\""+mydiv+"\",\""+category +"\",\" "+comment+"\" ); '>Edit</button></td></tr></table><hr>";
div.innerHTML = divHTML;
}
</script>
Hope this helps...
i am creating a form through php html and ajax that is specific for each row of a database table. I send the form data through ajax to another page which then takes that form data and uses it to pull data from another database based upon the results given and displays them.
I am fairly sure the problem is either with my select statement on the recipedisplay.php page or my syntax is wrong on how to echo out a returned variable.
select.php
<?php <script>
$('.button').click(function (e){
e.preventDefault();
var id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'pages/recipes/recipedisplay.php',
data: $('#f'+id).serialize(),
success: function(d){
$('#infodisplay').html(d);
}
});
});
</script>
<div id=\"a".$row['id']."\">
<form id=\"f" . $row['id'] . "\">
<input type=\"hidden\" name=\"recipeid\" id=\"recipeid\" value=\"" . $row['id'] . "\">
<div id=\"reciperesultbutton\" class=\"button\"><div id=\"centering\">" . $row['name'] ." </div></div>
<div id=\"reciperesulttext\"> " . $row['id'] ." " . $row['longdesc'] ."</div>
</form>
<br>
</div>
";
}
?>
recipedisplay.php
<?php
$con=mysqli_connect("localhost","test","test","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$id = mysqli_real_escape_string($con, $_POST['recipeid']);
$sql= "SELECT * FROM recipes WHERE 'id' ='".$id."'";
$row = mysqli_fetch_array($sql);
$name = $row['name'];
$longdesc = $row['longdesc'];
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
echo " fail ";
echo " . $name . ";
};
echo " . $id . ";
echo " work ";
echo " . $longdesc . ";
echo "$row[name]";
mysqli_close($con);
?>
The problem is in :
$row = mysqli_fetch_array($sql);
because mysqli_fetch_array() takes mysqli_query() result not your $sql query
So try to run your query first by this code :
mysqli_query($con,$sql);
$row = mysqli_fetch_array($mysqli_query);
Also you can use mysqli_fetch_assoc() that takes mysqli_query() too as a parameter
This question already has answers here:
How can I call PHP functions by JavaScript?
(13 answers)
Closed 8 years ago.
<?php
session_start();
function printTable() {
$server = "XXXXXXXX";
$user = "XXXXXXXXX";
$password = "XXXXXXXX";
$database = "XXXXXXXX";
$conn = mysql_connect($server, $user, $password);
mysql_selectdb($database, $conn);
$query = "SELECT Image, ISBN, Name, Vol, Release_date, publisher, price FROM products p";
$resultset = mysql_query($query, $conn); // retrieve data from database
if ($resultset == null || $resultset == 1) {
echo mysql_error(); // print SQL error
die(); // exit PHP program
}
$numFields = mysql_num_fields($resultset);
echo "<table border=2 align=center><tr>";
echo "</tr>";
for ($i=0; $i<(mysql_num_rows($resultset)); $i++) { // print records
$fields = mysql_fetch_row($resultset);
echo "<tr>";
echo "<tr class=$color><td><img width=100px src=$fields[0]></td>";
echo "<td> Name: " . $fields[2] . " (vol.". $fields[3] . ")</br>";
echo "<br> ISBN: " . $fields[1] . "</br>";
echo "<br> Publisher: " . $fields[5] . "</br>";
echo "<br> Release Date: " . $fields[4] . "</br>";
echo "<br> Price: HK$ " . $fields[6] . "</td>";
echo "<td><input type=\"submit\" value=\"Add to Cart\" onclick=\"combine($fields[1], '$fields[2]', $fields[3]);\"/></td>";
$fields = mysql_fetch_row($resultset);
if ($fields == null) break;
echo "<td><img width=100px src=$fields[0]></td>";
echo "<td> Name: " . $fields[2] . " (vol.". $fields[3] . ")</br>";
echo "<br> ISBN: " . $fields[1] . "</br>";
echo "<br> Publisher: " . $fields[5] . "</br>";
echo "<br> Release Date: " . $fields[4] . "</br>";
echo "<br> Price: HK$ " . $fields[6] . "</td>";
echo "<td><input type=\"submit\" value=\"Add to Cart\" onclick=\"combine($fields[1], '$fields[2]', $fields[3]);\"/></td>";
echo "</tr>";
}
echo "</table>";
}
mysql_close();
?>
<html>
<head>
<script>
function combine(value1, value2, value3) {
alert (value1 + value2 + value3);
//setcookie(value1);
}
</script>
</head>
<title>
Product Page
</title>
<body>
<body style="background:#A2A2AE">
<h1> <center> Product Page </center> </h1>
<p><center>-----------------------------------------------------------------------------------------------------------------------------------------------------------</center></p>
<?php printTable(); ?>
</body></html>
how I can run the function addcookies() to save value 1 as the cookies... Thank you!
function addcookies(value) {
$pid = $_POST['pid'];
$expiry = time() + 60 * 60 * 24 * 30;
// Update the number of items
if(isset($_COOKIE['count']))
$count = $_COOKIE['count'];
else
$count = 0;
// Put the item into shopping cart
$key = "item: ".$count;
setcookie($key, $pid, $expiry);
setcookie("count", $count+1, $expiry);
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
First of all, your html code isn't correct. You oppened body tag 2 times and your title tag is out of the head tag, it's not even in the body.
As Biffen said in the comment, you cannot run the php after the page has loaded. Instead, you can use ajax. Ajax Documentation
You have to create a file with your php code inside it, and then execute it with ajax without reloading the page. And as I see you have written in a comment: "Put the item into shopping cart". Do not store shopping cart items in, neither, browser cookies nor session. Use your database instead because data stored in either cookies or session will be vulnerable.
How to create a php image uploader with file system in which i could preview the thumb of image before uploading it to server and also validate the file before uploading.
I am using following code for image manipulation and saving.
HTML code:
<form id="imageform" enctype="multipart/form-data" method="post" action='upload.php'>
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<label for="fileToUpload">Select a File to Upload</label><br />
<input type="file" name="fileToUpload" id="fileToUpload" />
</div>
PHP Code:
<?php
// include ImageManipulator class
require_once('ImageManipulator.php');
if ($_FILES['fileToUpload']['error'] > 0) {
echo "Error: " . $_FILES['fileToUpload']['error'] . "<br />";
} else {
// array of valid extensions
$validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
// get extension of the uploaded file
$fileExtension = strrchr($_FILES['fileToUpload']['name'], ".");
// check if file Extension is on the list of allowed ones
if (in_array($fileExtension, $validExtensions)) {
$newNamePrefix = 'Thumb' . '_';
$newNamePrefix1 = 'Highdef' . '_';
$manipulator = new ImageManipulator($_FILES['fileToUpload']['tmp_name']);
$manipulator1 = new ImageManipulator($_FILES['fileToUpload']['tmp_name']);
// resizing to 200x200
$newImage = $manipulator->resample(200, 200);
$newImage1 = $manipulator1->resample(1024, 768);
// saving file to uploads folder
$manipulator->save('uploads/thumbs/' . $newNamePrefix . $_FILES['fileToUpload'] ['name']);
$manipulator1->save('uploads/highDef/' . $newNamePrefix1 . $_FILES['fileToUpload']['name']);
echo 'Done ...';
$folder = 'uploads/thumbs/';
$filetype = '*.*';
$files = glob($folder . $filetype);
$count = count($files);
echo '<table>';
for ($i = 0; $i < $count; $i++) {
echo '<tr><td>';
echo '<a name="' . $i . '" href="#' . $i . '"><img src="' . $files[$i] . '" /></a>';
echo substr($files[$i], strlen($folder), strpos($files[$i], '.') - strlen($folder));
echo '</td></tr>';
}
echo '</table>';
} else {
echo 'You must upload an image...';
}
}
?>
Right now I have a grid and each grid part/bit contains an image, the name of the item and different buttons that can delete the item from the mysql database and update the price. What I want to do know is that when a user say clicks on the image a window would pop up where extra information would be displayed. However it is not a pop up in a usual sense that it would create another window but rather a pop up within the current window/tab. E.g. When you press on a photo in Facebook it creates almost like a popup on which you can comment or change to the next photo. Does anyone have any idea on how to do this or at least what is the whole thing/process called?
Sorry if I can't give a proper name but I don't know it myself :/
Here is the code to what I have now. I would prefer an actual code solution but if you can lead me to where I should look for it I would also be happy. I tried looking online however everything I get is window pop ups.
<div class="boxes">
<?php
$ID = $_SESSION['SESS_MEMBER_ID'];
$con = mysql_connect("", "", "");
if (!$con){
die("Cannot connect: " . mysql_error());
}
mysql_select_db("test", $con);
$sql = "SELECT * FROM items WHERE member_id = $ID";
$myData = mysql_query($sql, $con);
$dir = 'Images';
$symbol = '\\';
$end = 'r.jpg';
$currency = '£';
while($record = mysql_fetch_array($myData)) {
$real_name = str_replace('_', ' ', $record['Name']);
$result = $dir . $symbol . $record['Name'] . $end;
$value = $currency . $record['price_now'];
$link = $record['url'];
echo "<div class = frame>";
echo "<div class = bit-3>";
echo "<div class = box>" . "<img src=" . $result . " alt=some_text>";
echo "<br />";
echo "<br />";
echo $real_name;
echo "<br />";
echo "<br />";
echo "Price now: " . $value;
echo "<form action = member-profile-page.php method = post>";
echo "Desired price: ";
echo "<td>" . "<input type = text name = desired_price value = " . $record['desired_price'] . " </td>";
echo "<td>" . "<input type = hidden name = hidden value = " . $record['Id'] . " </td>";
echo " ";
echo "<td>" . "<input type = submit name = update value = Update" . " </td>";
echo "<br />";
echo "<br />";
echo "<td>" . "<input type = submit name = delete value = Delete" . " </td>";
echo "<br />";
echo "<br />";
echo "<td>" . "<input type = submit name = buy value = Buy" . " </td>";
echo "</form>";
echo "</div>";
echo "</div>";
echo "</div>";
}
if (isset($_POST['buy'])){
$query = "select url from items where Id = '$_POST[hidden]'";
if ($result = mysql_query($query)) {
$row = mysql_fetch_assoc($result);
$code = $row['url'];
echo "$code";
header("Location: $code");
}
};
if (isset($_POST['update'])){
$UpdateQuery = "UPDATE items SET desired_price = '$_POST[desired_price]' WHERE Id = '$_POST[hidden]'";
mysql_query($UpdateQuery, $con);
};
if (isset($_POST['delete'])){
$DeleteQuery = "DELETE FROM items WHERE Id = '$_POST[hidden]'";
mysql_query($DeleteQuery, $con);
};
mysql_close($con);
?>
</div>
Sounds like you're looking for an overlay:
http://jquerytools.org/demos/overlay/index.html
or a modal:
https://jqueryui.com/dialog/
These are by no means the only examples; there are hundreds of such solutions. These will get you started, though. Good luck!
What you think about is just a layer in the current browser viewport, having some controls to let the user handle it like a "desktop window".
There are quite a lot of JS frameworks offering handy solutions for this, i.e. jQuery UI. Within there, look for "dialog"